← blog
NuxtOctober 18, 2026 · 13 min read

Nuxt 4.6 useSession: Server Sessions Without a Database

Nuxt 4.6 ships useSession and runtimeConfig.appSecret — real, sealed-cookie sessions with no database or session store. How it works, plus a cheat sheet.

Parsa Jiravand · Frontend engineer · building bestpractic
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.

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

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.

Here's a login handler that looks reasonable:

TypeScript
1
2
3
4
5
6
7
8
9
10
11
// 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 } })
TypeScript
1
2
3
4
5
6
// server/api/me.get.ts import { defineEventHandler } from 'nuxt/server' export default defineEventHandler(() => { return { user: currentUser } // undefined for the next visitor, or worse })

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: 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:

  • reads the session cookie on the incoming request, if one exists;
  • unseals it — decrypts it and verifies it hasn't been tampered with, using a key derived from your app's secret;
  • hands you a session.data object to read and a session.update() to change it;
  • 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.

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.

Shell
1
2
# generate one, once, per environment openssl rand -base64 32
Shell
1
2
# .env (never commit this) NUXT_APP_SECRET=the-output-of-the-command-above

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.

TypeScript
1
2
3
4
5
6
7
8
9
10
// 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 } })

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.

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
// 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 } })
TypeScript
1
2
3
4
5
6
7
8
// 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 } })

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.

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:

TypeScript
1
2
3
4
5
6
7
// ❌ 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) // … })

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.

  • 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.

You need…Reach for
Data to reach the client within this render's payload, safely per-requestuseState
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 ownA real database, keyed by a session ID
A value every request needs and that never changes per-visitorruntimeConfig, 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.

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.

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.

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.

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.

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.

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 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 })
TaskDo thisNotes
Set the one required secretNUXT_APP_SECRET env varDev auto-generates one; prod never does
Read session dataconst s = await useSession(event) → s.dataReturns {} if none exists yet
Change session dataawait s.update({ key: value })Merges and reseals the cookie
End the sessionawait s.clear()Removes data and the cookie
Reach it from a Vue componentExpose it from an endpoint, call with useFetchuseSession is server-only
Avoid NUXT_E8012Import everything in that handler from nuxt/serverDon't mix with classic auto-imports

  • 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.

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

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:

Keep reading

One post a day, in your inbox

Each one with a runnable playground and a quiz. No pitch, no digest, unsubscribe in one click.

0 comments

Sign in to join the discussion, like comments, and save articles for later.