[{"data":1,"prerenderedAt":6},["ShallowReactive",2],{"post-content-pinia-use-store-outside-component-no-active-pinia":3},{"content":4,"lastModified":5},"\u003Cp>An auth guard on a Vue 3 app built on Pinia rejected real sessions about one page load in six. Same build, same account. A hard refresh on \u003Ccode>\u002Fdashboard\u003C\u002Fcode> bounced to \u003Ccode>\u002Flogin\u003C\u002Fcode>, then clicking through from the home page worked fine, so I spent a day blaming the backend.\u003C\u002Fp>\n\n\u003Cp>The console had been telling me for days. I just did not like the answer.\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-text\">[🍍]: \"getActivePinia()\" was called but there was no active Pinia.\nAre you trying to use a store before calling \"app.use(pinia)\"?\nSee https:\u002F\u002Fpinia.vuejs.org\u002Fcore-concepts\u002Foutside-component-usage.html for help.\nThis will fail in production.\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>I never typed \u003Ccode>getActivePinia()\u003C\u002Fcode> anywhere; it comes out of \u003Ccode>useStore()\u003C\u002Fcode>. The offending line was in the router file, at module scope, three lines above the guard that used it.\u003C\u002Fp>\n\n\u003Ch2>The line is in the wrong place in time, not in the wrong file\u003C\u002Fh2>\n\n\u003Cp>Here is the version that broke. It type checks, and every store access inside the callback works because \u003Ccode>auth\u003C\u002Fcode> is already in scope:\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-ts\">\u002F\u002F router\u002Findex.ts\nimport { useAuthStore } from '@\u002Fstores\u002Fauth'\n\nconst auth = useAuthStore() \u002F\u002F evaluated when this module is imported\n\nrouter.beforeEach((to) => {\n  if (to.meta.requiresAuth &amp;&amp; !auth.token) return '\u002Flogin'\n})\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>\u003Ccode>main.ts\u003C\u002Fcode> imports the router at the top of the file. That import runs the whole router module before a single line of \u003Ccode>main.ts\u003C\u002Fcode> executes, which means before \u003Ccode>createPinia()\u003C\u002Fcode> and long before \u003Ccode>app.use(pinia)\u003C\u002Fcode>. No active instance exists yet, so Pinia throws. Vite reports nothing: the module graph is valid, it just ran too early.\u003C\u002Fp>\n\n\u003Cp>Moving the call inside the callback fixes it. The guard body runs when a navigation starts, after the app is mounted.\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-ts\">router.beforeEach((to) => {\n  const auth = useAuthStore() \u002F\u002F runs per navigation, app already installed\n  if (to.meta.requiresAuth &amp;&amp; !auth.token) return '\u002Flogin'\n})\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>That explains the one-in-six rate. Coming from the home page, a component had already touched a store, so an active instance was sitting there and the guard's stored reference happened to be fine. On a cold load of \u003Ccode>\u002Fdashboard\u003C\u002Fcode> the guard ran first. Same code, two outcomes.\u003C\u002Fp>\n\n\u003Cfigure>\n  \u003Cimg src=\"https:\u002F\u002Fimages.pexels.com\u002Fphotos\u002F36575138\u002Fpexels-photo-36575138.jpeg?auto=compress&amp;cs=tinysrgb&amp;w=1200\" alt=\"A ring of old skeleton keys hanging on a dark wooden door\" loading=\"lazy\" width=\"1200\" height=\"1800\">\n  \u003Cfigcaption>Several keys, and only one of them is the lock you meant.\u003C\u002Ffigcaption>\n\u003C\u002Ffigure>\n\n\u003Ch2>useStore() sets a global, and that is why your fix seems to work\u003C\u002Fh2>\n\n\u003Cp>Most posts skip this part. Pinia 3's \u003Ccode>useStore\u003C\u002Fcode> opens with:\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-js\">function useStore(pinia, hot) {\n  const hasContext = hasInjectionContext()\n  \u002F\u002F (the NODE_ENV === 'test' branch is elided here)\n  pinia = pinia || (hasContext ? inject(piniaSymbol, null) : null)\n  if (pinia) setActivePinia(pinia)\n  \u002F\u002F ...\n}\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>Passing an instance does not just resolve that one call. It assigns the global \u003Ccode>activePinia\u003C\u002Fcode>. Ran against pinia 3.0.4 and vue 3.5.46 in plain Node to see how far the side effect reaches:\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-text\">getActivePinia() before any createPinia()   -> undefined\nuseUserStore(piniaA)                        -> store created\ngetActivePinia() after that call            -> piniaA\nuseUserStore() with no argument             -> same store instance\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>So an implicit \u003Ccode>useStore()\u003C\u002Fcode> elsewhere can start working just because an unrelated file passed an instance first. Worst kind of fix: passes code review and the demo, then dies on the one path nobody clicked by hand. If your guard works while you navigate around but fails on refresh, this is the shape of the bug.\u003C\u002Fp>\n\n\u003Ch2>The recommended fix can hand you a second, empty store\u003C\u002Fh2>\n\n\u003Cp>The Stack Overflow answers I found all say to import the pinia instance and call \u003Ccode>useAuthStore(pinia)\u003C\u002Fcode>. Fine. But that only reads from whichever instance you passed, and nothing stops a project from having two. Mine had one in \u003Ccode>main.ts\u003C\u002Fcode> and another in a helper module someone added for tests.\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-ts\">const piniaA = createPinia()\nconst piniaB = createPinia()\n\nconst a = useUserStore(piniaA)\nconst b = useUserStore(piniaB)\n\na.login('token-from-A')\n\na.token \u002F\u002F 'token-from-A'\nb.token \u002F\u002F null\na === b \u002F\u002F false\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>No warning, no error. Both roots register a store under the id \u003Ccode>user\u003C\u002Fcode>, each with its own state. The guard reads B, sees \u003Ccode>null\u003C\u002Fcode>, and redirects a user whose component is happily logged in through A. Two auth states in one app, and a bug report that says \"sometimes I get logged out\".\u003C\u002Fp>\n\n\u003Cp>The tell is a store that is empty in exactly one place. Log the object and \u003Ccode>getActivePinia()\u003C\u002Fcode> from both the component and the guard, then compare identities, not values. If the objects differ, stop reading your actions and go find the second \u003Ccode>createPinia()\u003C\u002Fcode>. Mine was a leftover from a Vitest setup, copy-pasted into app code.\u003C\u002Fp>\n\n\u003Ch2>In production you do not get that message at all\u003C\u002Fh2>\n\n\u003Cp>The last line of that dev error says \"This will fail in production\", and it is not a scare sentence. The friendly throw is wrapped in a \u003Ccode>NODE_ENV !== 'production'\u003C\u002Fcode> check. Strip it and execution continues into \u003Ccode>pinia._s.get(id)\u003C\u002Fcode> with \u003Ccode>pinia\u003C\u002Fcode> undefined. Reproduced with node's production condition:\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-bash\">node --conditions=production -e \"import('pinia').then(({defineStore}) => {\n  const s = defineStore('x', { state: () => ({ n: 1 }) })\n  s()\n})\"\n# TypeError: Cannot read properties of undefined (reading '_s')\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>What lands in your error tracker is a TypeError about a private field, thrown from a vendor chunk, with the word Pinia nowhere in it. Sentry groups it with every other \"cannot read property of undefined\" and the stack points at the bundle, not at \u003Ccode>router\u002Findex.ts\u003C\u002Fcode>. If you only see this in production, the dev build was not protecting you. It was printing a friendlier error for the same crash.\u003C\u002Fp>\n\n\u003Ch2>How I set it up now\u003C\u002Fh2>\n\n\u003Cp>One module owns the instance and imports nothing from the app.\u003C\u002Fp>\n\n\u003Cpre>\u003Ccode class=\"language-ts\">\u002F\u002F app\u002Fpinia.ts\nimport { createPinia } from 'pinia'\nexport const pinia = createPinia()\n\n\u002F\u002F main.ts\nimport { pinia } from '.\u002Fpinia'\napp.use(pinia)\napp.use(router) \u002F\u002F router registered after pinia, never the other way round\u003C\u002Fcode>\u003C\u002Fpre>\n\n\u003Cp>Then: no store calls at module top level, ever. Guards and interceptors are the only places outside \u003Ccode>setup()\u003C\u002Fcode> where \u003Ccode>useStore()\u003C\u002Fcode> belongs, and they pass \u003Ccode>pinia\u003C\u002Fcode> explicitly, because the implicit path depends on whatever file ran before it. In tests, \u003Ccode>setActivePinia(createPinia())\u003C\u002Fcode> in \u003Ccode>beforeEach\u003C\u002Fcode>. A root shared across files leaks state and only fails when the whole suite runs.\u003C\u002Fp>\n\n\u003Cp>On Nuxt I do not create an instance at all. The framework installs one per request, and a store grabbed at module scope holds the previous request's state, a nastier version of the same bug and worth \u003Ca href=\"\u002Fposts\u002Fnuxt-ssr-state-leak-between-users\u002F\" rel=\"noopener\">its own write-up\u003C\u002Fa>. Chasing a similar symptom inside a component instead? The lost reactivity cases in \u003Ca href=\"\u002Fposts\u002Fvue-destructuring-lost-reactivity\u002F\" rel=\"noopener\">destructuring Pinia state\u003C\u002Fa> fail differently but look the same from the browser.\u003C\u002Fp>\n\n\u003Cp>Two days went into a diff that deleted one \u003Ccode>createPinia()\u003C\u002Fcode> call and moved three lines into a callback. What unblocked it: the message points at \u003Ccode>getActivePinia()\u003C\u002Fcode>, a function I never call, and import order was the only variable left. The guard and the axios-interceptor version of it live in \u003Ca href=\"\u002Fsnippetark\u002F\" rel=\"noopener\">Snippet Ark\u003C\u002Fa> now, mostly so I stop rebuilding them from memory and getting the ordering wrong again.\u003C\u002Fp>\n\n\u003Cp>If your store is empty in one file and populated in another, do not touch the actions. Count your pinia instances first.\u003C\u002Fp>\n","2026-11-21",1795678594079]