Search code examples
vuexnuxt3.jsnuxt-middleware

Nuxt3 - accessing Vuex store from middleware?


How can I access a Vuex store from within a middleware?

I know Nuxt3 suggests using Pinia, but I had problems installing/integrating it due to dependencies conflicts, so I used the ol' good Vuex.

Problem is, in Nuxt3 my middleware has no access to the context object but just to the routes that are being navigated to/from.

So the question probably became: is that even possible or am I enforced to use Pinia?


Solution

  • Create a plugin to handle that instead. It works even on present Nuxt 3.6.5

    Here:

    import { useUserStore } from '@/store';
    
    export default defineNuxtPlugin(nuxt => {
        const store = useUserStore(nuxt.$pinia);
    
        addRouteMiddleware('my-middleware', async (to, from) => {
            // TODO:
        }, { global: true });
    });
    
    

    For non global middleware you just remove the global flag,thus

    
      addRouteMiddleware('named-test', () => {
        console.log('this named middleware was added in a plugin')
      })
    })
    
    

    Edited:

    You could then save the plugin with .client suffix so it only becomes active on the client side

    auth.client.js
    

    Here a link to help https://nuxt.com/docs/guide/directory-structure/middleware#adding-middleware-dynamically