Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 32 ยท Data and state

State with useState and Pinia

Share state safely in a server-rendered Nuxt app: useState, why module-level refs leak data between visitors, Pinia stores and useCookie for small persistent values.

In a Vue single-page app, shared state is easy: create a ref in a module, import it anywhere, and every component sees the same value. That works because the app runs in one browser tab, for one person. A Nuxt app also runs on a server, and the server handles requests from many visitors with one long-lived process. A ref created at the top of a module lives as long as that process does, so it is shared by everyone. One visitor's data can show up on another visitor's page.

This lesson explains that leak, then shows the tools Nuxt gives you: useState for small shared values, Pinia for larger stores, and useCookie for values that must survive between visits. The real Nuxt code is read-only. The stand-ins model the server with plain JavaScript so you can watch the leak happen and see why the fix works.

One server, many visitors

Visitor A Signs in as Ada.
Visitor B Browses as a guest.
One process Handles both. Module variables are shared.

Shared module state is shared between people.

1 / 2

The leak: module-level state on a server

Look at this composable. It looks harmless and is perfectly fine in a client-only Vue app:

TypeScript
// composables/useCurrentUser.ts  (real Nuxt code, read-only, and WRONG on a server)
const user = ref<{ name: string } | null>(null)   // created once per server process

export function useCurrentUser() {
  return user
}

During server rendering, a request sets user.value = { name: 'Ada' }. The module is still loaded when the next request arrives, so the next visitor, who is not signed in, is rendered with Ada's name. This is a data leak, and it is hard to catch in development because you are the only visitor.

The same problem appears with plain objects, arrays, caches and counters declared at module scope, and with anything created outside a function that Nuxt calls once per request. The rule is: on the server, state must belong to a request, not to the module.

The stand-in below models a server as an async function that handles requests. Real parts: the leak itself (it is how Node modules behave) and the idea of state that belongs to a request. Stand-in parts: the "request" objects and the render function. Request A starts first and sets the user. Before it finishes, request B (a guest) arrives. Run it to compare the leaky and the safe version.

JS Two visitors, one server process

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the leaky run the guest is greeted as Ada, and visit numbers count everybody together. In the safe run each request starts clean. The real framework hides the "new object per request" step for you: that is exactly what useState does.

useState

useState creates a reactive value that is shared by every component during one request (or one browser session), is stored on the Nuxt app instance rather than in a module, and is serialized into the page payload, so the browser starts with the same value the server rendered.

TypeScript
// composables/useCurrentUser.ts  (real Nuxt code, read-only)
export const useCurrentUser = () =>
  useState<{ name: string } | null>('current-user', () => null)
VUE
<script setup lang="ts">
const user = useCurrentUser()
</script>

<template>
  <p v-if="user">Signed in as {{ user.name }}</p>
  <NuxtLink v-else to="/login">Sign in</NuxtLink>
</template>

The details that matter:

  • The first argument is a key. Components that call useState with the same key get the same ref. Give every piece of state a unique, descriptive key.
  • The second argument is an init function. It runs only if the key has no value yet. If the server already set it and the browser received it in the payload, the browser does not run init again, which also prevents hydration mismatches from values like random numbers (see Hydration and SSR pitfalls).
  • The value must be serializable. Do not put functions, class instances or DOM nodes in it.
  • Call it during setup, in a plugin or in route middleware (see Navigation and route middleware), and wrap it in a composable as above so the key lives in one place.

Notice that useState is, in effect, the "safe" version from the stand-in: a map of key to value attached to the current request. The next stand-in builds that map and adds the payload step.

JS A tiny useState with payload hand-off

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The random number is chosen once, on the server, and the browser reuses it. A Math.random() inside a component would give a different value in the browser and cause a mismatch.

Pinia

useState is perfect for a handful of values. When state grows into something with actions, computed values and devtools support, such as a shopping cart, use Pinia, the official store library for Vue. Nuxt has a module for it: install @pinia/nuxt and add it to the modules list in nuxt.config.ts. The module makes sure each request gets its own Pinia instance and that store state is carried to the browser in the payload.

TypeScript
// nuxt.config.ts (real Nuxt code, read-only)
export default defineNuxtConfig({
  modules: ['@pinia/nuxt'],
})
TypeScript
// stores/cart.ts (real Nuxt code, read-only)
export const useCartStore = defineStore('cart', () => {
  const items = ref<{ id: number; qty: number }[]>([])
  const count = computed(() => items.value.reduce((sum, i) => sum + i.qty, 0))

  function add(id: number) {
    const found = items.value.find((i) => i.id === id)
    if (found) {
      found.qty++
    } else {
      items.value.push({ id, qty: 1 })
    }
  }

  return { items, count, add }
})
VUE
<script setup lang="ts">
const cart = useCartStore()
const { count } = storeToRefs(cart)
</script>

Pinia's own syntax and ideas are the same as in the plain Vue world, so if you need the basics, read Pinia basics and State sharing. What is new in Nuxt is the server side:

  • State must live inside defineStore. A store defined this way is created per request. A ref you declare next to it at module level is leaky again.
  • The module can auto-import stores from folders you list in its storesDirs option; otherwise import the store file yourself.
  • Do not put secrets in stores that are rendered on the server. Their state is serialized into the HTML.

A good rule: start with useState. Move to Pinia when you want actions, getters and devtools for a real domain model.

useCookie

State in memory disappears on reload. For small values that should persist, such as a theme choice or a "dismissed banner" flag, use a cookie. useCookie gives you a ref that is backed by a cookie, on both server and browser: on the server it reads the request's Cookie header and writes a Set-Cookie header, in the browser it uses document.cookie. That means the server can render the right theme on the first byte.

TypeScript
// real Nuxt code, read-only
const theme = useCookie<'light' | 'dark'>('theme', {
  default: () => 'light',
  maxAge: 60 * 60 * 24 * 365, // one year, in seconds
  sameSite: 'lax',
})

theme.value = 'dark'   // updates the cookie
theme.value = null     // removes it

Two cautions. Cookies are sent with every request and capped at roughly four kilobytes, so keep them tiny. And a cookie that JavaScript can read is not a safe place for a session token: set a session cookie from a server route with the HttpOnly flag instead (see Forms, validation and auth flows).

The last stand-in is a model of the cookie format: parsing the header the server receives and building the header it sends. The names and attributes are the real HTTP ones.

JS What useCookie reads and writes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is const user = ref(null) at the top of a composable file dangerous in a server-rendered Nuxt app?

    A server process handles many requests. State at module level outlives each request, so one visitor's data can appear in another visitor's page.
  2. 2. What does the second argument of useState('count', () => 0) do?

    The init function is skipped when the key already has a value, for example one restored from the server payload.
  3. 3. How does the browser get the same useState value the server rendered?

    State is part of the payload, which is why values must be serializable.
  4. 4. Which is the better home for a shopping cart with add and remove actions and a computed total?

    Pinia stores are created per request in Nuxt and support actions, getters and devtools.
  5. 5. A teammate wants to keep the login session token in useCookie('token'). What is the problem?

    HttpOnly cookies are invisible to scripts. Set the session cookie from a server route instead.

Summary

  • A Nuxt server is one long-lived process for many visitors, so module-level state is shared between people and leaks data.
  • useState(key, init) gives per-request, SSR-safe shared state that travels to the browser in the payload; use unique keys and serializable values.
  • Use Pinia (via @pinia/nuxt) when state needs actions and getters; keep all state inside defineStore.
  • useCookie gives a ref backed by a cookie that works on both server and browser; keep it small and never store session secrets in it.

Next: Components and composables in Nuxt