SSR VUEX Nuxt.Js doesn't load localStorage while initialization
Nuxt.Js SSR Mode failed to load LocalStorage
2022-08-13Recently my new static hosted webapp have run in a bug. I discovered: Some bots and search indexes, doesn't index meta Tags correctly when SSR mode is disabled.
SSR Mode
I thought it will be obvious not to enable SSR mode because my webapp is pre-rendered with nuxt generate.
The documentation for this mode is super light and there is no other reason to disable it, other then you use a SPA. This wasn't my case, so after setting SSR to default i ran in another bug.
The Vuex store doesn't load my initial State anymore. After many trials and error, googling around and finding dead traps. I implemented a solution by myself.
Solution
store/index.js
const loadLocalStorage = process.client
? JSON.parse(localStorage.getItem('state'))
: undefined
export const state = () => ({
cookiesAccepted: false
})
export const mutations = {
initStore: state => {
state.cookiesAccepted = loadLocalStorage?.cookiesAccepted || false
}
}
layouts/default.vue
export default {
updated() {
if (process.client) {
console.log('updated')
this.$store.commit('initStore')
}
}
}
Now the initial State loading will be delayed, until the default page layout is updated.
Maybe this solution will also helps you.Good Luck.