pinia-plugin-persistedstate
pinia-plugin-persistedstate copied to clipboard
[nuxt] Unable to persist if using store in middleware
Nuxt version: 3.0.0-rc.1 Pinia plugin persistedstate version: 1.6.1 Pinia version: 2.0.13
Hello, I reproduced your Nuxt example and it works well but if I want to use my store in a middleware, that doesn't work anymore. I have no error, just the cookie is not setted.
// /middleware/authentication.global.ts
import { defineNuxtRouteMiddleware, navigateTo, useCookie } from "#app"
import { useUser } from "~/store/user"
export default defineNuxtRouteMiddleware((to) => {
console.log(useUser()) // this line prevents cookie creation, but reading cookie works
if (!useCookie("user").value && to.path !== "/login") {
return navigateTo("/login")
}
})
// /store/user.ts
import { defineStore } from "pinia"
export const useUser = defineStore("user", {
state: () => ({
refreshToken: "",
token: "",
roles: [] as Array<string>
}),
getters: {
isLogged: state => !!state.refreshToken
},
persist: {
paths: ["refreshToken", "roles"]
}
})
// /plugins/persistedstate.ts
import { createNuxtPersistedState } from "pinia-plugin-persistedstate"
import { defineNuxtPlugin, useCookie } from "#app"
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.$pinia.use(createNuxtPersistedState(useCookie))
})
Thank you !
Hi, i may need to look deeper into nuxt to know what is accessible from middleware and what is not 🤔
Oh yes this is not accessible inside a nuxt middleware.
what i did is

as much as i'd like to have an impact on that issue from the plugin, it may be more of a Nuxt/cookie thing ?
Yes @prazdevs , I think middleware is being called first than plugin. So nothing is being restored from storage when middleware loads.
i'll read some more code and undestand nuxt deeper, esp. middleware to see what we can do and if there's something the plugin should be responsible of. not sure but we'll see :)
Thanks @prazdevs
@prazdevs I noticed that this behavior is also present inside Plugins not just middleware This makes createNuxtPersistedState useless as I can't access anything in SSR inside some plugins.
I was wondering if this was still an issue with the v3 and the nuxt module (@pinia-plugin-persistedstate/nuxt).
I played with middlewares a bit, and i can access and change stores values with it being always up to date and stored (in cookies by default).
Did you try it in your app/project ? Is the problem solved ?
I'll be closing this issue, as it seems resolved with nuxt3 and the nuxt module. If you still have problems with it, feel free to reopen!