Pinia Outside a Component: "No Active Pinia" Is a Timing Bug
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 /dashboard bounced to /login, then clicking through from the home page worked fine, so I spent a day blaming the backend.
The console had been telling me for days. I just did not like the answer.
[๐]: "getActivePinia()" was called but there was no active Pinia.
Are you trying to use a store before calling "app.use(pinia)"?
See https://pinia.vuejs.org/core-concepts/outside-component-usage.html for help.
This will fail in production.
I never typed getActivePinia() anywhere; it comes out of useStore(). The offending line was in the router file, at module scope, three lines above the guard that used it.
The line is in the wrong place in time, not in the wrong file
Here is the version that broke. It type checks, and every store access inside the callback works because auth is already in scope:
// router/index.ts
import { useAuthStore } from '@/stores/auth'
const auth = useAuthStore() // evaluated when this module is imported
router.beforeEach((to) => {
if (to.meta.requiresAuth && !auth.token) return '/login'
})
main.ts imports the router at the top of the file. That import runs the whole router module before a single line of main.ts executes, which means before createPinia() and long before app.use(pinia). No active instance exists yet, so Pinia throws. Vite reports nothing: the module graph is valid, it just ran too early.
Moving the call inside the callback fixes it. The guard body runs when a navigation starts, after the app is mounted.
router.beforeEach((to) => {
const auth = useAuthStore() // runs per navigation, app already installed
if (to.meta.requiresAuth && !auth.token) return '/login'
})
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 /dashboard the guard ran first. Same code, two outcomes.
useStore() sets a global, and that is why your fix seems to work
Most posts skip this part. Pinia 3's useStore opens with:
function useStore(pinia, hot) {
const hasContext = hasInjectionContext()
// (the NODE_ENV === 'test' branch is elided here)
pinia = pinia || (hasContext ? inject(piniaSymbol, null) : null)
if (pinia) setActivePinia(pinia)
// ...
}
Passing an instance does not just resolve that one call. It assigns the global activePinia. Ran against pinia 3.0.4 and vue 3.5.46 in plain Node to see how far the side effect reaches:
getActivePinia() before any createPinia() -> undefined
useUserStore(piniaA) -> store created
getActivePinia() after that call -> piniaA
useUserStore() with no argument -> same store instance
So an implicit useStore() 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.
The recommended fix can hand you a second, empty store
The Stack Overflow answers I found all say to import the pinia instance and call useAuthStore(pinia). Fine. But that only reads from whichever instance you passed, and nothing stops a project from having two. Mine had one in main.ts and another in a helper module someone added for tests.
const piniaA = createPinia()
const piniaB = createPinia()
const a = useUserStore(piniaA)
const b = useUserStore(piniaB)
a.login('token-from-A')
a.token // 'token-from-A'
b.token // null
a === b // false
No warning, no error. Both roots register a store under the id user, each with its own state. The guard reads B, sees null, 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".
The tell is a store that is empty in exactly one place. Log the object and getActivePinia() 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 createPinia(). Mine was a leftover from a Vitest setup, copy-pasted into app code.
In production you do not get that message at all
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 NODE_ENV !== 'production' check. Strip it and execution continues into pinia._s.get(id) with pinia undefined. Reproduced with node's production condition:
node --conditions=production -e "import('pinia').then(({defineStore}) => {
const s = defineStore('x', { state: () => ({ n: 1 }) })
s()
})"
# TypeError: Cannot read properties of undefined (reading '_s')
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 router/index.ts. If you only see this in production, the dev build was not protecting you. It was printing a friendlier error for the same crash.
How I set it up now
One module owns the instance and imports nothing from the app.
// app/pinia.ts
import { createPinia } from 'pinia'
export const pinia = createPinia()
// main.ts
import { pinia } from './pinia'
app.use(pinia)
app.use(router) // router registered after pinia, never the other way round
Then: no store calls at module top level, ever. Guards and interceptors are the only places outside setup() where useStore() belongs, and they pass pinia explicitly, because the implicit path depends on whatever file ran before it. In tests, setActivePinia(createPinia()) in beforeEach. A root shared across files leaks state and only fails when the whole suite runs.
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 its own write-up. Chasing a similar symptom inside a component instead? The lost reactivity cases in destructuring Pinia state fail differently but look the same from the browser.
Two days went into a diff that deleted one createPinia() call and moved three lines into a callback. What unblocked it: the message points at getActivePinia(), a function I never call, and import order was the only variable left. The guard and the axios-interceptor version of it live in Snippet Ark now, mostly so I stop rebuilding them from memory and getting the ordering wrong again.
If your store is empty in one file and populated in another, do not touch the actions. Count your pinia instances first.