Cant access Pinia Store from Nuxt3 Plugin code (error says "outside of plugin" when it's not)

769 views Asked by At

Installed:

[email protected]
@pinia/[email protected]
[email protected]

Relevant portion of nuxt.config.ts:

    modules: [
        '@pinia/nuxt',
    ],
    plugins: [
        { src: '~/plugins/router.ts' }
    ],
    imports: {
        dirs: ['stores'],
        presets: [
            {
                from: 'pinia',
                imports: ['storeToRefs']
            }
        ]
    }

~/plugins/router.ts: (Imports via auto-import)

export default defineNuxtPlugin((nuxtApp) => {
    useRouter().beforeEach(() => {
        const store = useAuthStore();
        console.log(store.isAuthenticated);
    });
});

OK so this makes no sense to me. I'm literally going around in circles. None of the documentation I'm following for this is making any sense or working with my setup.

As far as I understand it, the fact that I'm calling useAuthStore() inside of the router beforeEach(<closure>) means I should have access to the pinia store. However this is not the case.

The above code results in the following browser console output and the app refuses to load:

Uncaught Error: [nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug. Find out more at 'https://nuxt.com/docs/guide/concepts/auto-imports#using-vue-and-nuxt-composables'.

So here is the really messed up part. If I change the plugin code to this:

export default defineNuxtPlugin((nuxtApp) => {
    useRouter().beforeEach(() => {
        console.log(nuxtApp.vueApp.$nuxt.$pinia);
    });
});

I get the "pinia" object log in my console (app functions fine - useRouter() call is no problem!):

enter image description here

So as far as I can tell, at this point in the code, Pinia is not only created, the stores are initialized and they are populated with the data. So why can I not access my store?

I'm going nuts here so any help will be greatly appreciated. I just can't fathom what the problem is and what I need to do to fix it. I've been at this for HOURS.

Edit For clarity on my incorrect assumption regarding the console screenshot:

The $pinia object had the data when the log was written, I had forgot that objects logged to the console are "reactive" so when the $pinia object in the screen shot above was logged it was actually not loaded, but by the time I was able to open the object panel the rest of the code had ran and the $pinia stores were available.

1

There are 1 answers

1
Rick Kukiela On

False alarm (one of those want to crawl in hole and not come out for a while moments).

Quite embarrassing to admit the problem was actually quite simple and the stack trace accompanying the A composable that requires access to the Nuxt instance was called outside of a plugin error message was literally pointing at the offending line (which I looked at literally hours before making this post and didn't realize what I was looking at).

Here is what was going on:

  1. Plugin was loading and registering the "imported" deps in my plugin during app initialization.
  2. When useAuthStore() was used in any capacity (with or without a $pinia instance), my store ~/stores/useAuthStore.ts was being initaizlied.
  3. My auth store has one method that handles refreshing the CSRF token from the back-end, so my useFetch() wrapper composable ~/composables/useApi.ts was being initialized.
  4. At the very top of my useApi.ts file, I was running const config = useRuntimeConfig(); -- not inside a method, in effort to make it available to all methods in the file -- And this line is what was ultimately causing the issue as it was being run outiside a plugin/middleware/setup/etc scenario, not my useAuthStore() call.

How I finally figured this out was, I started really "throwing crap at the wall to see what would stick" as I was grasping at straws. One thing I finally did was to init a different store useToastStore() in my plugin as a test and it worked perfectly! This is what made me realize there was something "inside" the authStore that was causing the issue. Once I had that realization it was a matter of minutes to figure out the actual problem.

So problem solved.... Thanks to everyone that tried to help me. I really appreciate the efforts!