Having trouble setting up my Vuex store with the logged-in user's account details from localStorage
.
I've looked at numerous Auth examples in Nuxt, but none explain how to retrieve an authToken
from localStorage
on the client side for subsequent API requests when the page is refreshed or the user navigates to the app.
Disclaimer: Not using Nuxt in SSR (this may impact your response).
What's frustrating is that I can fetch and initialize my state from localStorage
, but then it gets overwritten. See this code snippet:
buildInitialState () {
if (!process.server) {
// Retrieve accessToken, refreshToken, and account details from localStorage
return {accessToken: <valid-string>, refreshToken: <valid-string>, account: <valid-json-blob>}
} else {
// Return "INVALID" placeholders for demonstration
return {accessToken: "INVALID", refreshToken: "INVALID", account: "INVALID"}
}
}
export const state = () => buildInitialState()
Although initially all looks good as I correctly set the state values from localStorage
, once I use Axios for requests and add an interceptor to include the accessToken
, things go awry.
In the interceptor plugin:
export default ({ app, store }) => {
axios.interceptors.request.use((config) => {
const accessToken = _.get(store.state, ['account', 'accessToken'])
if (accessToken) {
config.headers.common['x-auth-token'] = accessToken
}
return config
}, (error) => Promise.reject(error))
}
It seems that despite initializing the state correctly, the accessToken
reverts back to "INVALID" when a request is made. This behavior contradicts the initial setup from localStorage
.
If anyone familiar with Nuxt could shed light on this issue, it would be greatly appreciated. The goal is to maintain the user session intact even after page refresh without requiring a new login each time.
Thanks and regards, Jason.