Hello,
I'd like to grab JWT out of cookie and set it to the axios instance as authorization, but this only works on server side. After initial load, subsequent AsyncData ajax requests throw an error that token is not given.
'check-auth.js' available in nuxt.config router as global middleware
import { getTokenFromCookie, getTokenFromLocalStorage } from '~/utils/auth'
import { setBearerToken } from '~/utils/axiosHeaders'
export default async function ({ isServer, store, req, app }) {
// If nuxt generate, pass this middleware
if (isServer && !req) return
const token = isServer ? getTokenFromCookie(req) : getTokenFromLocalStorage()
if (token) {
await setBearerToken(app, token)
await store.dispatch('auth/set_user')
}
}
Here I set the bearer token using the 'context.app' as axios instance.
async function setBearerToken(vm, token) {
return new Promise((resolve, reject) => {
vm.$axios.setToken(token, 'Bearer')
resolve(true)
})
}
async set_user({ commit }) {
try {
const { data } = await this.$axios.get('auth/user')
commit('SET_USER', data.data)
} catch (error) {
// Token doesn't work anymore, throw it out local storage
unsetToken()
}
},
Using this, the user loads perfectly and the initial data on the loaded page aswell, but when I navigate through the app, all asyncData axios requests fail because token is not set. My guess is that the axios instance is completely different on clientside and doen't have the bearer token. But how to solve this?
I used to set token in localstorage and load user after app has loaded, but this brought other issues. (For example if I load the account page (not navigate to it, but fresh refresh), I want to redirect to login page if not logged in using middleware. But if the token is in localstorage, the user is loaded after the middleware and always thinks a user is not logged in. Therefore always redirecting. So I've read that other people use JWT in cookie to grab user beforehand, but this brings me to the above issue
<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c1589">#c1589</a>)</em></sub></div>