Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท SSR and Nuxt

Using Pinia in Nuxt

Set up Pinia in a Nuxt app with the @pinia/nuxt module, auto-imported stores, fetching with callOnce and $fetch, route middleware and Nuxt-specific plugins.

Nuxt is the most popular full-stack framework for Vue, and it renders on the server by default. Everything you learned in the SSR lesson (one pinia per request, serialized state, hydration) is handled for you by the official module @pinia/nuxt. You write stores as usual; Nuxt creates the pinia, ships the state in the page payload and restores it in the browser.

Nuxt needs Node and a build tool, so the code in this lesson is read-only. A small interactive stand-in at the end lets you experiment with the most important idea: fetch once on the server, do not fetch again in the browser.

Installing

Terminal
npx nuxi module add pinia

That installs @pinia/nuxt and pinia and adds the module to nuxt.config.ts. You can also do it by hand:

Terminal
npm install pinia @pinia/nuxt
TypeScript
// nuxt.config.ts
export default defineNuxtConfig({
  modules: ["@pinia/nuxt"],
});

You never call createPinia() or app.use(pinia). The module does both, once per request on the server and once in the browser.

Stores and auto-imports

Put stores in the stores/ directory. The module auto-imports defineStore, storeToRefs and the other helpers, and auto-imports the stores themselves from stores/* (top level only), so components can call them without an import:

TypeScript
// stores/counter.ts
export const useCounterStore = defineStore("counter", {
  state: () => ({ count: 0 }),
  actions: {
    increment() { this.count++; },
  },
});
VUE
<!-- pages/index.vue -->
<script setup lang="ts">
const counter = useCounterStore();     // no import needed
</script>

<template>
  <button @click="counter.increment()">{{ counter.count }}</button>
</template>

To auto-import nested folders too, configure the module:

TypeScript
export default defineNuxtConfig({
  modules: ["@pinia/nuxt"],
  pinia: {
    storesDirs: ["./stores/**", "./custom-folder/stores/**"],
  },
});

Explicit imports (import { useCounterStore } from "~/stores/counter") always work too, and many teams prefer them for clarity.

Fetching data

The classic Nuxt pattern is useFetch or useAsyncData inside a page. When data belongs in a store (shared by many components), fetch it through a store action and call that action once.

Two details are important:

  • Use $fetch inside store actions, not useFetch. useFetch is a composable meant for component setup; it manages its own SSR payload and does not belong inside an action.
  • Call the action once during server render. Nuxt provides callOnce for this: it runs on the server, and the browser skips it because the payload says it already ran.
TypeScript
// stores/products.ts
export const useProductsStore = defineStore("products", {
  state: () => ({ list: [] as Product[] }),
  actions: {
    async load() {
      this.list = await $fetch<Product[]>("/api/products");
    },
  },
});
VUE
<!-- pages/products.vue -->
<script setup lang="ts">
const products = useProductsStore();
await callOnce("products", () => products.load());
</script>

<template>
  <ul><li v-for="p in products.list" :key="p.id">{{ p.name }}</li></ul>
</template>

If you only need the data on one page and nowhere else, plain useAsyncData without a store is simpler. Use a store when several pages or components read or change the same data.

Seeing it with a stand-in

The editor below imitates what callOnce and the payload do. A tiny "payload" records which keys already ran. The first page view is the "server render" (it fetches); moving between the two "pages" afterwards does not fetch again, because the key is in the payload and the store keeps its state. This is a hand-written stand-in, not Nuxt: real Nuxt serializes the payload into the HTML.

Stand-in: fetch once, share across pages

Switch between the pages as often as you like: the fetch counter stays at 1.

Route middleware

Because stores work anywhere inside the Nuxt context, route middleware can use them for guards:

TypeScript
// middleware/auth.ts
export default defineNuxtRouteMiddleware((to) => {
  const auth = useAuthStore();
  if (!auth.isLoggedIn && to.path !== "/login") {
    return navigateTo("/login");
  }
});

Attach it in a page with definePageMeta({ middleware: "auth" }). The middleware runs on the server for the first request and in the browser for later navigations.

Plugins in Nuxt

A Pinia plugin, as in Writing a Pinia Plugin, is registered from a Nuxt plugin file because there is no main.js where you create pinia:

TypeScript
// plugins/pinia-logger.ts
import { defineNuxtPlugin } from "#app";

export default defineNuxtPlugin(({ $pinia }) => {
  $pinia.use(({ store }) => {
    store.$onAction(({ name }) => console.log("action:", store.$id, name));
  });
});

For persistence, use the dedicated module @pinia-plugin-persistedstate/nuxt. It stores state in cookies by default, because cookies are sent to the server on the next request, so server-rendered HTML already contains the saved values. localStorage is not available during SSR.

Common Nuxt + Pinia mistakes

  • Using useFetch in an action. Use $fetch there.
  • Calling useStore() at module level in a file that runs on import. Call it inside setup, middleware, actions or plugins.
  • Module-level state outside stores (const cache = {} at file scope). On the server it is shared between all requests. Put state in a store (or useState).
  • Non-serializable state. Nuxt's payload is serialized, so avoid class instances in state, or use Nuxt's payload reducers.
  • Browser-only APIs in state initializers. state: () => ({ token: localStorage.getItem("t") }) crashes on the server.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do you need to call to set up Pinia in a Nuxt app?

    The module creates the pinia per request on the server and once in the browser; you do not call createPinia yourself.
  2. 2. Which should you call inside a store action in Nuxt?

    $fetch is the plain request function. useFetch and useAsyncData are component composables with their own payload handling.
  3. 3. What does callOnce('products', fn) do?

    callOnce makes a setup task run once per page load across the server and client, avoiding duplicate fetching.
  4. 4. Why does the persistedstate Nuxt module default to cookies?

    localStorage does not exist on the server; cookies travel with the request and are readable during SSR.

Summary

  • Add @pinia/nuxt to modules; Nuxt handles creation, serialization and hydration.
  • Stores in stores/ are auto-imported; use storesDirs for nested folders.
  • Fetch with $fetch in actions and trigger them once with callOnce or useAsyncData.
  • Stores work in route middleware, plugins and components.
  • Register Pinia plugins from a Nuxt plugin file; use cookies for persistence.

Next: SSR Pitfalls and Request State