Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 38 ยท SSR and Nuxt

SSR Pitfalls and Request State in Pinia

Avoid the classic Pinia SSR bugs: state leaking between visitors, stores used outside setup, browser-only code on the server, non-serializable state and hydration mismatches.

SSR bugs are special: your app works perfectly on your laptop with one visitor, then misbehaves in production when two people use it at the same time. Most of these bugs fall into a few families. This lesson names them, shows the worst one (state leaking between visitors) running live, and gives you a checklist.

Pitfall 1: shared state between requests

On the client, one browser tab runs one copy of your app, so module-level variables belong to one user. On the server, one Node process answers many visitors, and module-level variables are shared by everyone. If a store lived at module level, Alice's data would appear in Bob's page.

The correct way, which Vue and Pinia frameworks use, is a fresh pinia per request. The incorrect way is creating the pinia when the file is imported:

JavaScript
// WRONG on a server: created once, shared by all requests
export const pinia = createPinia();
JavaScript
// RIGHT: created inside a function, called for every request
export function createApp() {
  const pinia = createPinia();
  // ...
  return { app, pinia };
}

The demo below simulates a server answering two requests, Alice's and then Bob's. Bob's request does not set a user name (he is not logged in). Press the buttons and compare the two strategies. The rendering uses Vue's server renderer.

Leaking state: shared pinia vs one pinia per request

In the shared version, Bob is greeted with Alice's name. In a real application the leaked value could be a session, a cart or a private email address. This is a security bug, not just a visual one.

Never keep per-user data in module-level variables, singletons or caches on the server, even outside Pinia. Anything created at import time is shared between all requests.

Pitfall 2: using a store outside setup without a pinia

In a component's setup, useStore() finds the pinia through the current app. Outside components (in a router guard, an API helper, a server entry) there is no current component, and on the server there may be several pinias alive at once. Pass the right one explicitly:

JavaScript
// router guard in an SSR app
export function createGuards(router, pinia) {
  router.beforeEach((to) => {
    const auth = useAuthStore(pinia);       // pass the request's pinia
    if (to.meta.requiresAuth && !auth.isLoggedIn) return "/login";
  });
}

On the client, with one pinia, you can often omit the argument, but passing it is correct everywhere. Never call useStore() at the top of a module: it runs at import time, before any pinia is installed.

Pitfall 3: browser APIs on the server

On the server there is no window, document, localStorage or navigator. A state initializer that touches them throws and the whole page fails with a 500 error:

JavaScript
// crashes on the server
state: () => ({ theme: localStorage.getItem("theme") ?? "light" })

Instead start with a neutral default and read the browser value after mounting:

JavaScript
state: () => ({ theme: "light" }),
actions: {
  restoreTheme() {
    if (typeof window === "undefined") return;
    this.theme = window.localStorage.getItem("theme") ?? "light";
  },
},

Call restoreTheme() from onMounted. For values the server needs (a theme that affects the HTML), store them in a cookie, which the server can read.

Pitfall 4: state that cannot be serialized

The state travels as JSON. These do not survive: functions, class instances (their methods vanish), Map, Set, Symbol, undefined values in objects (dropped), and circular references (throw). A Date becomes a string. Keep state as plain data, and derive richer objects in getters:

JavaScript
state: () => ({ createdAt: "2026-01-15T10:00:00Z" }),     // string, not Date
getters: { createdDate: (s) => new Date(s.createdAt) },

Pitfall 5: hydration mismatches

If the HTML from the server differs from what the client renders first, Vue warns and may rebuild part of the page. Typical causes with stores:

  • Values that differ per environment: Date.now(), Math.random(), time-zone formatted dates, window.innerWidth.
  • State not restored before mount (see the SSR basics).
  • A getter that reads browser-only state, such as dark mode from matchMedia, and renders it immediately.

The fix is to render the same thing on both sides first, then update after mount. This sketch shows the pattern with a "mounted" flag, which you can run: before onMounted the page shows a stable placeholder; after, it shows the client-only value.

Client-only values after mount

Pitfall 6: forgetting the client fallback

A page loaded by the server has its data. A page reached by client-side navigation (clicking a link) never touches the server, so the data must be loaded in the browser. Use a guard such as if (!store.loaded) await store.load() in a route hook or onMounted, so both paths work.

SSR checklist

Check Why
New pinia per request No data shared between visitors
No module-level user data Same reason, outside Pinia too
useStore(pinia) outside setup Right pinia for the request
No window/localStorage in initializers Server has none
State is plain JSON data It is serialized into the HTML
Same first render on server and client No hydration mismatch
Client fallback for fetching Client-side navigation skips the server

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a pinia created at module level dangerous on a server?

    A Node process handles many requests, and module-level variables are shared by all of them.
  2. 2. Which state initializer breaks SSR?

    localStorage does not exist on the server, so reading it while creating state throws.
  3. 3. What happens to a Date object in serialized state?

    JSON turns a Date into a string, so store it as a string and build the Date in a getter.
  4. 4. What is a common cause of hydration mismatches?

    The server and the browser compute different values, so the first client render differs from the server HTML.

Summary

  • One pinia per request on the server; never keep per-user data at module level.
  • Outside setup, pass the pinia: useStore(pinia); never call useStore() at import time.
  • Keep browser APIs out of state initializers; apply them after mount or use cookies.
  • Make state plain, serializable data.
  • Render the same first output on server and client; update client-only values in onMounted.
  • Load data in the browser too, for client-side navigation.

Next: Vuex Concepts Mapped to Pinia