Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 38 ยท Composition and Setup Stores

Using Stores Outside Components

Use Pinia stores in router guards, API helpers and plain modules: when the active pinia exists, how to pass the pinia instance explicitly, and the mistakes that cause errors.

Stores are not limited to components. Router guards, API clients, event handlers and utility modules often need the current user or a token. This works well, as long as you understand one rule: a useXStore() call needs to find a pinia instance, and inside components Pinia finds it automatically. Outside them you must make sure one is available.

Why the call can fail

When you call useUserStore() in a component's setup, Pinia gets the pinia instance from the app through inject. In plain code there is no component, so Pinia falls back to the active pinia, which is the one most recently installed with app.use(pinia). That value only exists after the app has installed Pinia.

The classic error looks like this:

TEXT
getActivePinia() was called but there was no active Pinia.
Are you trying to use a store before calling "app.use(pinia)"?

It almost always means the use call ran too early: at the top of a module that is imported before app.use(pinia) executes.

sequenceDiagram
    participant M as main.js
    participant P as Pinia
    participant X as Your module
    M->>P: createPinia()
    M->>M: app.use(pinia)  (pinia becomes active)
    M->>X: later, function called
    X->>P: useUserStore()  works
    Note over X,P: Calling at import time, before app.use(pinia), fails

Call stores inside functions that run after installation, not at import time.

Rule 1: call it inside a function

Wrong, runs when the module is imported:

JavaScript
// api.js
import { useUserStore } from "./stores/user";
const user = useUserStore();            // too early

export function authHeaders() {
  return { Authorization: `Bearer ${user.token}` };
}

Right, runs when the function is called:

JavaScript
// api.js
import { useUserStore } from "./stores/user";

export function authHeaders() {
  const user = useUserStore();          // looked up now
  return { Authorization: `Bearer ${user.token}` };
}

Rule 2: router guards

Router guards run after the app is installed, so call the store inside the guard:

JavaScript
import { createRouter } from "vue-router";
import { useAuthStore } from "./stores/auth";

const router = createRouter({ /* ... */ });

router.beforeEach((to) => {
  const auth = useAuthStore();
  if (to.meta.requiresAuth && !auth.isSignedIn) {
    return { path: "/login", query: { next: to.fullPath } };
  }
});

There is one subtle trap: if the router is installed before pinia (app.use(router) and then app.use(pinia)), the initial navigation can run a guard before pinia exists. Install Pinia first:

JavaScript
app.use(createPinia());
app.use(router);
app.mount("#app");

Rule 3: pass the pinia explicitly when in doubt

Every use function accepts a pinia instance as an argument. This makes the dependency visible and removes any guessing about what is "active". It is required when you use several apps or pinias (tests, micro-frontends), and it is the only safe way during SSR, where many requests run at the same time and a single global "active pinia" would be wrong:

JavaScript
import { pinia } from "./pinia";       // your exported instance
import { useUserStore } from "./stores/user";

const user = useUserStore(pinia);

To do this, create the instance in its own module and import it everywhere that needs it:

JavaScript
// pinia.js
import { createPinia } from "pinia";
export const pinia = createPinia();
JavaScript
// main.js
import { createApp } from "vue";
import { pinia } from "./pinia";
createApp(App).use(pinia).mount("#app");

Try it: a store used from plain code

The demo below starts a timer outside any component. A plain function updates the store every second through useClockStore(pinia), with the pinia passed explicitly. The component only reads the store. Notice that the plain code runs before the app is even mounted.

A plain function updating a store

The component and the plain function see the same store, because both use the same pinia.

Rule 4: components that outlive setup

Inside a component's setup the use call works. Inside an event handler defined in setup it also works, since it runs later and the active pinia is set. But code that runs in a setTimeout after the app was destroyed, in a test, or in a worker has no active pinia. In tests, create one first:

JavaScript
import { setActivePinia, createPinia } from "pinia";

beforeEach(() => setActivePinia(createPinia()));

The testing chapter builds on this.

Outside the Vue app entirely

You can use Pinia with no component at all, for example in a Node script or a worker. Create the pinia, make it active, then use stores. createPinia() needs no app to exist, though without one the plugins that rely on app are unavailable:

JavaScript
import { createPinia, setActivePinia } from "pinia";

setActivePinia(createPinia());
const todos = useTodoStore();
todos.add("works without Vue components");

Pitfalls summary

Symptom Cause Fix
"no active Pinia" at startup use call at module top level Move it into a function
Guard fails on first load Router installed before pinia app.use(pinia) first
Two different states Two pinia instances Export one instance and reuse it
Wrong user on the server Global active pinia shared by requests Pass the pinia explicitly

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does useStore() fail at the top level of a module imported by main.js?

    The active pinia is set by app.use(pinia), which has not run yet when the module is evaluated.
  2. 2. Where in a router guard should the store be called?

    Guards run after installation, so calling the store inside them finds the active pinia.
  3. 3. Which argument lets you control exactly which pinia a store uses?

    Every use function accepts a pinia instance; it is the safe choice for SSR and tests.
  4. 4. What does setActivePinia(createPinia()) do?

    It is how scripts and tests get an active pinia without a Vue app.

Summary

  • Outside components, Pinia uses the active pinia set by app.use(pinia).
  • Call useXStore() inside functions, never at import time.
  • In router guards call it inside the guard, and install pinia before the router.
  • Pass the pinia explicitly for SSR, multiple apps and clarity; export one shared instance.
  • In scripts and tests use setActivePinia(createPinia()).

Next: Writing a Pinia Plugin