Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 38 ยท SSR and Nuxt

Pinia with SSR and Hydration

Understand how Pinia works with server-side rendering: one pinia per request, fetching data in stores, serializing state into the HTML and hydrating it in the browser.

With server-side rendering (SSR), your Vue app runs twice: first on a server, which produces HTML so the visitor sees content immediately and search engines can read it, and then in the browser, where Vue attaches to that HTML and makes it interactive. This second step is called hydration.

Pinia fits SSR well, but only if you respect one idea: the state the server fetched must travel to the browser inside the page, or the browser would start empty, refetch everything and may render something different from the server's HTML (a hydration mismatch). This lesson explains the whole round trip and lets you run it in the browser with a simulated server.

The round trip

sequenceDiagram
  participant B as Browser
  participant S as Server
  B->>S: GET /products
  S->>S: createPinia() for this request
  S->>S: render app, stores fetch data
  S->>B: HTML + serialized pinia.state
  B->>B: createPinia(), state.value = serialized state
  B->>B: mount app (hydrate existing HTML)

One pinia per request on the server; the state is shipped inside the HTML.

Four steps matter:

  1. Create a new pinia for each request on the server.
  2. Fill the stores (usually by awaiting an action while rendering).
  3. Serialize pinia.state.value into the HTML, for example into window.__pinia.
  4. On the client, assign it back (pinia.state.value = window.__pinia) before mounting.

Why a new pinia per request

A Node server handles many visitors with one process. Anything stored at module level is shared by all of them. If your app created one pinia at import time, user A's cart would end up in user B's HTML. So both Vue and Pinia use a factory:

JavaScript
// main.js (shared by server and client)
import { createSSRApp } from "vue";
import { createPinia } from "pinia";
import App from "./App.vue";

export function createApp() {
  const app = createSSRApp(App);
  const pinia = createPinia();
  app.use(pinia);
  return { app, pinia };
}

Each request calls createApp() and gets a fresh pinia. We look at the dangers of sharing in SSR pitfalls.

The server entry (read-only)

A typical Vite SSR project has these two entries. They need Node, so they are shown read-only; the live example further down simulates them.

JavaScript
// entry-server.js
import { renderToString } from "vue/server-renderer";
import { createApp } from "./main";

export async function render(url) {
  const { app, pinia } = createApp();
  const html = await renderToString(app);       // stores can fetch in onServerPrefetch
  const state = JSON.stringify(pinia.state.value);
  return { html, state };
}

The HTML template then contains the state, escaped so it cannot break out of the script tag:

HTML
<div id="app"><!--app-html--></div>
<script>
  window.__pinia = <!--pinia-state-->;
</script>

JSON.stringify alone is not safe here: a string like </script><script>alert(1) in your data would end the tag. Use a serializer that escapes < (for example serialize-javascript) or replace < with <.

JavaScript
// entry-client.js
import { createApp } from "./main";

const { app, pinia } = createApp();

if (window.__pinia) {
  pinia.state.value = window.__pinia;     // before mounting
}

app.mount("#app");                         // hydrates the server HTML

Fetching data on the server

Components call a store action while rendering. In <script setup>, Vue's onServerPrefetch waits for it:

VUE
<script setup>
import { onServerPrefetch, onMounted } from "vue";
import { useProductsStore } from "@/stores/products";

const products = useProductsStore();

onServerPrefetch(async () => {
  await products.load();            // runs on the server; state is serialized
});

onMounted(() => {
  if (!products.list.length) products.load();   // client fallback (e.g. client-side navigation)
});
</script>

On the first page load the store already has data from the server, so the browser skips the fetch. On later client-side navigations there is no server step, so onMounted (or a router hook) loads it.

A simulated server and browser

Here is the same flow in one page. The "server" step builds a pinia, loads data with an action, renders to a string (using Vue's server renderer, loaded from a CDN) and serializes the state. The "browser" step creates a second, separate pinia, restores the state and hydrates the HTML. Press Run, then click the hydrated button.

The component uses a render function because the browser build of the server renderer cannot compile template strings. That is a limit of this demo, not of Pinia.

Simulate SSR: render, serialize, hydrate

The quote in step 3 was never fetched in the browser: it came from the serialized state. The Like button works because hydration attached the event handler to the server's HTML.

What if you skip the state transfer?

Comment out the line pinia.state.value = JSON.parse(state) and run again. The browser pinia is empty, so the client renders (empty: nothing was loaded) where the server rendered the quote. Vue warns about a hydration mismatch in development. In a real app the user would see content flash and change, or the page would refetch everything.

Checklist for SSR-safe stores

  • A new pinia per request on the server; a single pinia per page in the browser.
  • Do not call useStore() at module level; call it in setup, in actions or pass the pinia: useStore(pinia).
  • Make state serializable: plain objects, arrays, strings, numbers, booleans, null. No functions, class instances, Map or Set.
  • Avoid browser-only APIs (window, localStorage) during state creation; use onMounted or guard with typeof window.
  • Escape serialized state in HTML.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the server create a new pinia for every request?

    A Node process serves many users; a module-level pinia would leak one user's state into another user's page.
  2. 2. When do you assign pinia.state.value = window.__pinia on the client?

    The state must be restored before the app mounts, so the first client render matches the server HTML.
  3. 3. Which value can NOT be reliably serialized into SSR state?

    State is sent as JSON text; functions and class instances do not survive it.
  4. 4. What does onServerPrefetch do?

    It lets a component await a store action while the server renders, so the HTML contains real data.

Summary

  • SSR renders HTML on the server and hydrates it in the browser.
  • Create a fresh pinia per request; serialize pinia.state.value into the page; restore it before mounting.
  • Fetch data in actions called from onServerPrefetch, with a client fallback for navigation.
  • Keep state serializable and escape it when writing it into HTML.
  • Skipping the state transfer causes empty or mismatched hydration.

Next: Pinia in Nuxt