nuxt3 pinia localStorage is not defined #2336
-
Reproductionnuxt3 pinia localStorage is not defined Steps to reproduce the bugExpected behaviorcan use localStorage Actual behaviorcan use localStorage Additional informationNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
That error happens on server because localStorage is browser only (not related to pinia) |
Beta Was this translation helpful? Give feedback.
-
Quick update, if it helps anyone, to avoid this error from happening while using vite-ssg, you can use // This plugin is used for state persistence in Pinia stores.
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
export const install = ({ isClient, app, router }) => {
// Create a new Pinia instance.
const pinia = createPinia()
pinia.use(({ store }) => {
// The 'router' instance is marked as raw using 'markRaw'.
// This prevents Vue from observing and tracking it in the reactivity system.
store.router = markRaw(router)
})
if (isClient) {
//Very important to only do this client-side, to avoid localStorage being undefined during ssg-build.
// Use the 'piniaPluginPersistedstate' for state persistence in Pinia stores.
pinia.use(piniaPluginPersistedstate)
}
app.use(pinia)
} otherwise, you will get console errors like |
Beta Was this translation helpful? Give feedback.
That error happens on server because localStorage is browser only (not related to pinia)
I recommend you to use or check Vue use useLocalStoarge to handle things