I have such a problem: I need to get localStorage data before nuxt layout is loaded in pages/index.vue
/pages/index.vue
<script>
export default {
layout (context) {
if (localStorage.getItem('AUTH_TOKEN')){
this.$store.dispatch('changeAuthStatus', {
authStatus: true,
accessToken: localStorage.getItem('AUTH_TOKEN'),
profileData: JSON.parse(localStorage.getItem('PROFILE_DATA'))
}).then(() => {
this.$store.dispatch('changeLoadedStatus', {
isLoaded: true
})
})
}
else {
this.$router.push('/auth')
}
}
</script>
The error when the page is loaded: localStorage is not defined
Maybe I can get localStorage data using context? Or maybe you can suggest to me any package so I can use it in the layout function?
I found the solution:
I just installed nuxt-universal-storage module, that Amirhossein Shahbazi suggested. So I have just done this:
/pages/index.vue:
<script>
export default {
middleware: ['auth'],
layout (context) {
let currentRole = context.app.$storage.getUniversal('PROFILE_DATA')
console.log(currentRole)
let currentLayout = 'default'
let defaultRoles = ['customer_support_manager', 'checker', 'storekeeper']
let tabletRoles = ['deputy_cutting_shop']
if (defaultRoles.includes(currentRole.role)) {
currentLayout = 'default'
}
else if (tabletRoles.includes(currentRole.role)) {
currentLayout = 'tablet'
}
return currentLayout
}
</script>
/middleware/auth.js:
export default function ({ redirect, app, store }) {
// some token checkers for existing, for 401 error and for their validity
}
If I'm not mistaken, Nuxt is the SSR solution for Vue (same as Next for React), right?
If so, you don't have access to the localStorage. Server Side is not running in your browser!
This kind of code works fine
<script>
export default {
layout({ store }) {
if (process.client) {
console.log('localStorage?', localStorage.getItem('myCat'))
console.log('store?', store)
}
},
}
</script>
Because localStorage is not available on the server.
Try to use localStorage.setItem('myCat', 'Tom'), move to your page and see how it displays the localStorage and the store (don't forget to use the context since this is not available here).