DEV Community

Cover image for Nuxt 4.6 useSession: Server Sessions Without a Database
Parsa Jiravand
Parsa Jiravand

Posted on Originally published at bestpractic.org

Nuxt 4.6 useSession: Server Sessions Without a Database

You build a login endpoint. It checks the password, and now you need to remember that this particular visitor is logged in the next time their browser shows up — which, on a server, is a completely new, unrelated request. Reach for useState and it resets every time, because it only lives for one server render. Reach for a module-scope variable and you've just reintroduced the cross-request leak this series already covered. So you either stand up a database table for sessions, or reach for a third-party module to seal a cookie for you.

As of Nuxt 4.6, released October 5, 2026, you don't need either. Nuxt core now ships useSession, a server session that lives entirely inside a tamper-proof cookie — no session store, no database row, no Redis.

What you'll learn

By the end of this article you'll be able to:

  • Explain why useState and a module-scope variable both fail to "remember" a visitor across real, separate requests
  • Set runtimeConfig.appSecret and understand what it's actually for
  • Use useSession to read, update, and clear session data from a server route
  • Explain why a sealed cookie is safe to trust — what happens when someone edits it
  • Avoid the one import mistake (NUXT_E8012) that trips people up migrating to nuxt/server

Who this is for

You've read or can follow the useState vs ref episode — or at least you accept its conclusion: Nuxt's server has no memory of its own between requests unless you give it one on purpose. This article is about the tool Nuxt 4.6 gives you for that: a cookie-backed session. No prior auth-library experience needed.

This article is written against Nuxt 4.6 (verified against the nuxt package's GitHub releases and npm dist-tags on October 17, 2026 — 4.6.0 shipped October 5, with patch releases 4.6.1 and 4.6.2 following; neither patch touches session handling, so everything below applies unchanged across all three). Code uses the Nuxt 4 app/ directory convention; server/ stays at the project root either way, same as every other episode in this series.

Table of contents

The problem: nothing the server does survives the request

Here's a login handler that looks reasonable:

// server/api/login.post.ts
import { defineEventHandler, readBody } from 'nuxt/server'

let currentUser: { id: number; name: string } | null = null // wrong — see below

export default defineEventHandler(async (event) => {
  const { username, password } = await readBody(event)
  const user = await verifyCredentials(username, password)
  currentUser = user // "remember" them... where, exactly?
  return { ok: true }
})
Enter fullscreen mode Exit fullscreen mode
// server/api/me.get.ts
import { defineEventHandler } from 'nuxt/server'

export default defineEventHandler(() => {
  return { user: currentUser } // undefined for the next visitor, or worse
})
Enter fullscreen mode Exit fullscreen mode

This is the same bug the useState episode walked through: currentUser is a module-scope variable, created once when the server process starts, shared by every request that process ever handles. In development, with one tab open, it looks like it works — you log in, you call /api/me, you get your user back. In production, with concurrent traffic, a second visitor's request can run between the two and overwrite currentUser before you read it. You'd see someone else's session, or a login that silently "loses" itself under load.

The instinct to fix this with useState doesn't work either, for a different reason: useState isolates data within a single server-side render — it exists to get data safely into the SSR payload for one request's Vue app instance, and that instance is thrown away the moment the response is sent. It was never meant to persist between two separate HTTP requests made minutes apart; it isn't that kind of tool, and calling it from server/ doesn't even work (there's no Vue app instance there — that's the Nitro server routes episode's subject).

What you actually need is something that survives between requests without living in server memory at all — because the server might restart, and in production it's rarely a single process.

The mental model: stateless server, stateful cookie

The mental model: a Nitro request handler, by itself, is stateless — it has no memory of any earlier request, by design. The only way information crosses from one request to the next is if the client carries it back: either a reference (a session ID the server looks up in a database) or the data itself, sealed so the client can carry it without being able to read or forge it.

useSession, new in Nuxt 4.6 via the nuxt/server import source, is the second approach. When you call it, Nuxt:

  1. reads the session cookie on the incoming request, if one exists;
  2. unseals it — decrypts it and verifies it hasn't been tampered with, using a key derived from your app's secret;
  3. hands you a session.data object to read and a session.update() to change it;
  4. on update(), reseals the (possibly new) data into a fresh cookie and attaches it to the response.

Nothing is stored on the server. The cookie is the session. That's also why it needs a secret: without one, anyone could write their own cookie and hand your server whatever session data they wanted.

A term of art: "sealing" here means authenticated encryption — the data is both encrypted (unreadable without the key) and signed (any edit invalidates it). Nuxt's session helpers use the iron sealing format via h3, the same primitive underneath, so a one-character edit to the cookie doesn't produce different session data — it just fails to unseal at all, and the request is treated as having no session.

Building it, stage by stage

Stage 1 — the one secret your whole app needs

Nuxt 4.6 introduces a single root secret: runtimeConfig.appSecret, set via the NUXT_APP_SECRET environment variable. Session sealing, and any future module that needs a secret, derives its own purpose-specific key from it internally — you configure one value, not a different secret per feature.

# generate one, once, per environment
openssl rand -base64 32
Enter fullscreen mode Exit fullscreen mode
# .env (never commit this)
NUXT_APP_SECRET=the-output-of-the-command-above
Enter fullscreen mode Exit fullscreen mode

Key concept: in local development, if you haven't set one, Nuxt generates and saves a secret for you automatically and warns the first time something derives a key from it. That convenience is dev-only — a production build never auto-generates a secret. If you deploy without setting NUXT_APP_SECRET, you're deploying without one, not getting a free one; treat it the same as any other missing required credential, and set it before your first production deploy, not after something breaks.

Stage 2 — reading and writing session data

// server/api/visit.get.ts
import { defineEventHandler, useSession } from 'nuxt/server'

export default defineEventHandler(async (event) => {
  const session = await useSession<{ visits: number }>(event)

  await session.update({ visits: (session.data.visits ?? 0) + 1 })

  return { visits: session.data.visits }
})
Enter fullscreen mode Exit fullscreen mode

Call /api/visit once and you get { "visits": 1 }. Refresh and it climbs: 2, 3, 4 — across completely separate requests, with no database anywhere in this code. Open the same route in a different browser (no shared cookie) and it starts at 1 again, independently. That's the whole point: the state travels with the visitor, sealed into their own cookie, not with the server process.

Key concept: unlike using h3's session utility directly — where you must pass a password of at least 32 characters yourself — Nuxt's wrapper derives that password from runtimeConfig.appSecret for you. appSecret really is the only secret you manage.

Stage 3 — logging someone in, and out

// server/api/login.post.ts
import { defineEventHandler, readBody, useSession } from 'nuxt/server'

export default defineEventHandler(async (event) => {
  const { username, password } = await readBody<{ username: string; password: string }>(event)
  const user = await verifyCredentials(username, password) // your own check

  const session = await useSession<{ userId: number }>(event)
  await session.update({ userId: user.id })

  return { ok: true }
})
Enter fullscreen mode Exit fullscreen mode
// server/api/logout.post.ts
import { defineEventHandler, useSession } from 'nuxt/server'

export default defineEventHandler(async (event) => {
  const session = await useSession(event)
  await session.clear() // removes the session data AND the cookie
  return { ok: true }
})
Enter fullscreen mode Exit fullscreen mode

Every later request that carries the resulting cookie can call useSession(event) again and read session.data.userId straight back — no lookup, no round trip to anywhere.

Stage 4 — the migration trap: NUXT_E8012

nuxt/server is a new, parallel import source alongside the classic auto-imported server/ utilities (which come from h3 under the hood either way). They are not meant to be mixed in the same handler:

// ❌ mixes an auto-imported helper with an explicit nuxt/server import
import { useSession } from 'nuxt/server'

export default defineEventHandler(async (event) => { // defineEventHandler here is auto-imported, not explicit
  const session = await useSession(event)
  // …
})
Enter fullscreen mode Exit fullscreen mode

Doing this throws NUXT_E8012 at build or runtime, depending on what's mixed. The fix is mechanical: once a handler touches nuxt/server, import everything it uses — defineEventHandler, readBody, useSession, whatever else — from nuxt/server explicitly, as every example above does. Nothing requires you to migrate existing handlers that only use the classic auto-imports; the rule only bites when you start mixing the two styles in the same file.

Edge cases and gotchas

  • The cookie has a size limit, because it's a cookie. A database-backed session can hold anything; a sealed-cookie session is bounded by how much a browser will send back in a header (a few KB, practically). Keep session.data small — an ID, a role, a couple of flags — not a shopping cart's full contents.
  • It isn't reachable from a Vue component. useSession lives in nuxt/server, for server routes and middleware only. To get session-derived data into a page, expose it from an endpoint and read it with useFetch/useAsyncData — the same request/dedupe rules from the useAsyncData episode apply.
  • Rotating appSecret logs everyone out at once. Every existing cookie was sealed with keys derived from the old secret; once the secret changes, every one of them fails to unseal and is treated as "no session." That's correct behavior, not a bug — but plan rotations knowing the blast radius.
  • This scales horizontally for free. Because there's no server-side store, any number of server instances can validate the same session as long as they share the same appSecret — no shared Redis, no sticky sessions, nothing to keep in sync.
  • maxAge and idleTimeout are separate knobs. maxAge is an absolute lifetime from creation; idleTimeout is a sliding window measured from the last request that touched the session. Set at least maxAge explicitly — don't rely on defaults you haven't checked for your use case.

Best practices: useSession vs useState vs a database

You need… Reach for
Data to reach the client within this render's payload, safely per-request useState
A small, server-only fact that must survive across separate requests from the same visitor (login status, a role, a cart ID) useSession
Data too large for a cookie, shared across devices, or queryable/auditable on its own A real database, keyed by a session ID
A value every request needs and that never changes per-visitor runtimeConfig, not a session at all

Never put secrets inside session data expecting them to stay hidden from the visitor who owns that session — sealing hides the data from everyone else, not from the person whose cookie it is. And never reach for a module-scope variable to "remember" anything about a specific visitor; that bug is exactly what this series' useState vs ref episode walked through.

FAQ

Is Nuxt's useSession the same as h3's useSession?

It's built on the same underlying session and sealing mechanism from h3, exposed through the new nuxt/server import source so it's portable across Nitro v2, Nitro v3, and the experimental Vite-based server Nuxt is also building. The difference that matters day to day is that Nuxt fills in the password for you from runtimeConfig.appSecret.

Do I still need a module like nuxt-auth-utils?

For the cookie-sealing mechanism itself, no — that's now in Nuxt core. A full auth module still earns its keep for things core doesn't do: OAuth provider flows, refresh-token rotation, pre-built login UI. Read what a module adds on top before assuming you still need it for sessions alone.

What happens if I forget to set NUXT_APP_SECRET in production?

Nothing generates one for you — that only happens in local development. Treat a missing appSecret the same as any other missing required environment variable: set it before your first deploy, store it the way you store any other secret, and never commit it.

Can a visitor edit their own session cookie to grant themselves more access?

No, as long as sealing is doing its job: editing even one character of a sealed cookie breaks the seal, and useSession treats an unsealable cookie as no session at all — not as the edited data. They can delete their session or get logged out; they can't forge a different one without your appSecret.

Does this replace a database for user accounts?

No. useSession holds the small, ephemeral fact that a particular request belongs to a particular already-authenticated visitor. The accounts themselves — usernames, hashed passwords, profile data — still belong in a real datastore; the session just carries a reference to one, such as a user ID.

Cheat sheet

// 1. One secret, once per environment
// .env → NUXT_APP_SECRET=<openssl rand -base64 32>
// (dev: auto-generated if missing. prod builds: never auto-generated — you must set it.)

// 2. Always import everything from nuxt/server once you touch it (avoids NUXT_E8012)
import { defineEventHandler, readBody, useSession } from 'nuxt/server'

export default defineEventHandler(async (event) => {
  // 3. Read + create
  const session = await useSession<{ userId?: number; visits?: number }>(event)

  // 4. Update (reseals the cookie automatically)
  await session.update({ visits: (session.data.visits ?? 0) + 1 })

  // 5. Read back
  const current = session.data

  // 6. Log out / destroy
  // await session.clear()

  return current
})
Enter fullscreen mode Exit fullscreen mode
Task Do this Notes
Set the one required secret NUXT_APP_SECRET env var Dev auto-generates one; prod never does
Read session data const s = await useSession(event) → s.data Returns {} if none exists yet
Change session data await s.update({ key: value }) Merges and reseals the cookie
End the session await s.clear() Removes data and the cookie
Reach it from a Vue component Expose it from an endpoint, call with useFetch useSession is server-only
Avoid NUXT_E8012 Import everything in that handler from nuxt/server Don't mix with classic auto-imports

Key takeaways

  • A Nitro request handler has no memory between requests on its own — that's the same lesson as the cross-request state leak, applied constructively this time.
  • Nuxt 4.6's useSession, from nuxt/server, seals session data into the cookie itself: no database, no Redis, and it scales across instances for free.
  • runtimeConfig.appSecret (NUXT_APP_SECRET) is the one secret everything derives from — set it yourself before deploying; Nuxt only auto-generates one in development.
  • Sealing means tampering breaks the cookie instead of forging new data — that's why it's safe to trust.
  • useSession and useState solve different problems: one survives across real requests, the other gets data into a single render's payload. Mixing them up is the bug.

🎮 Try it yourself

▶️ Open the interactive playground →

Runs right in your browser — poke at it and watch the concept react live.

🧠 Test yourself

Think it clicked? Take the 9-question quiz →

Instant feedback, a hint on every question, and an explanation for each answer — right or wrong.

That cart-losing, login-dropping bug from the top of this article doesn't need a database migration or a Redis instance to fix anymore — runtimeConfig.appSecret and useSession are already sitting in Nuxt 4.6. What's the smallest piece of per-visitor state your own app is currently faking with something that doesn't actually survive a request? Drop it in the comments — there's a good chance useSession is the fix.


🚀 Want more like this? Every guide, playground, and quiz lives on bestpractic.org — open it and sign up free so the next one finds you.

Thanks for reading! Let's stay connected:

Top comments (0)