pinia-plugin-persistedstate: [nuxt] Pinia State doesn't persist when set from middleware

Describe the bug

This is my Pinia module:

import { defineStore } from "pinia";
export const useStore = defineStore("store", {
    state: () => ({
        token: '',
    }),

    actions: {
        setToken(token: string) {
            this.token = token;
        }
    },

    persist: true
});

I set the state with setToken function from the middleware

import {useStore} from "~/store/useStore";

export default defineNuxtRouteMiddleware(() => {
    const store = useStore();
    console.log('store.token1', store.token)
    store.setToken('token')
    console.log('store.token2', store.token)
});

Now on first app reload I would expect to see logs:

store.token1
store.token2 token

and on the second reload I would expect to see

store.token1 token store.token2 token

Instead I see:

image

Reproduction

https://github.com/d0peCode/nuxt3-pinia-middleware-issue

System Info

MacOS, Chrome

Used Package Manager

npm

Validations

About this issue

  • Original URL
  • State: open
  • Created a year ago
  • Comments: 24 (13 by maintainers)

Most upvoted comments

you can do this

export default defineNuxtRouteMiddleware(to => {
  // skip middleware on server
  if (process.server) return
  // skip middleware on client side entirely
  if (process.client) return
  // or only skip middleware on initial client load
  const nuxtApp = useNuxtApp()
  if (process.client && nuxtApp.isHydrating && nuxtApp.payload.serverRendered) return
})

https://nuxt.com/docs/guide/directory-structure/middleware

I have done a lot of stupid things. 😦 after trying several possibilities, I found that just using it store.$persist() is enough. just like your code @d0peCode :

import {useStore} from "~/store/useStore";

export default defineNuxtRouteMiddleware(() => {
    const store = useStore();
    console.log('store.token1', store.token)
    store.setToken('token')
    console.log('store.token2', store.token)
    // just do this
    preset_cookie.$persist()
});

This was the missing piece, thanks!!

I’m using a check-auth.global.ts middleware to refresh and store the session token and faced this issue as well.

Just adding the $persist method after refreshing the token fixed my issue.

Now its okay with adding middleware to this.

  if (process.server) {
    return
  }

Now middleware.


...
export default defineNuxtRouteMiddleware(async (to, from) => {
  const nuxtApp = useNuxtApp()
  
  const store =  useMainStore();
  const config = useRuntimeConfig();
  
  if (process.server) {
    return
  }

  const authRequiredPages = ["/panel", "/teklif-al"];
  // ? if user is not logged in and to.path.startsWith authRequiredPages
  const isLoginRequired = authRequiredPages.some((authPaths) => {
    if (to.path.startsWith(authPaths)) {
      return true;
    }
  });

....

I have done a lot of stupid things. 😦 after trying several possibilities, I found that just using it store.$persist() is enough. just like your code @d0peCode :

import {useStore} from "~/store/useStore";

export default defineNuxtRouteMiddleware(() => {
    const store = useStore();
    console.log('store.token1', store.token)
    store.setToken('token')
    console.log('store.token2', store.token)
    // just do this
    preset_cookie.$persist()
});

I’m sorry that my thought is wrong before you explained. but the good news is that I have an idea, and I’m trying to solve it tomorrow.

PRs are always welcome 😃

That being said, keep in mind the nuxt module is an implementation of the base plugin, to work easily with Nuxt, and for most uses. Not everyone uses middleware and modify pinia stores in there.

So, yes, the library is SSR friendly with most use cases.

There are lots of cases that could be improved on the nuxt part, but the nuxt implementation is very simple. Keep in mind most of it is my work, on my free time, over nights, so I’d ask to stay respectful, for me and everyone who has contributed so far.

SSR is a very complex topic, and Nuxt still changes a lot. Keeping server and client in sync is ridiculously difficult, let alone middleware or server components… The Nuxt module was created when Nuxt3 was released officially, and docs were not even complete. Nuxt module docs are still not complete, and unit testing is still in RFC!

tl;dr: be respectful. the module fulfils most people’s needs (ssr included) and there will be improvement eventually.

also thanks @Abernethy-BY & @MZ-Dlovely for the answers 👍