
# Sessions on Nuxt

> Keep a signed session cookie in a Nuxt app: a server util keyed from the runtime config, three routes on `nuxt/server`, and a page that calls them.

A Nuxt route defined with `defineEventHandler` from `nuxt/server` receives a request event, `{ req, res, context }`, and the session reads that shape as it is. One file in `server/utils/` defines the session; Nuxt auto-imports it into every route. The session is a JWS, a token with a signature across it: the server can tell whether it wrote the cookie, and the user can read what's inside. [Concepts](/getting-started/concepts) has the vocabulary.

## Before you start

- Nuxt 4.6 or later, then add the package:

  ```sh
  pnpm add unjwt
  ```

- A session key that survives restarts. Generate it once, in your project folder:

  ```sh
  node --input-type=module -e 'import { generateJWK } from "unjwt/jwk"; console.log(JSON.stringify(await generateJWK("HS256")))'
  ```

  It prints one line of JSON, `{"alg":"HS256","kty":"oct","k":"…","kid":"…"}`. Store that whole line as `NUXT_SESSION_KEY` in your host's secrets, or in `.env` while you develop (`NUXT_SESSION_KEY=` followed by the line). Whoever holds it can sign a session for any user. Replacing it signs everyone out.

- HTTPS, or `localhost` while you develop. The cookie is called `__Host-unjwt-jws` and carries `Secure`, so a browser drops it on plain HTTP anywhere else.
- Import `defineEventHandler`, `readBody` and `createError` from `nuxt/server` in every route. The auto-imported `defineEventHandler` passes an older event shape that the session refuses.

## Read the key from the runtime config

Declare the key in `nuxt.config.ts`, with an empty default. Nuxt fills `runtimeConfig.sessionKey` from `NUXT_SESSION_KEY` when the server starts:

<!-- automd:region src="../../playgrounds/nuxt-4/nuxt.config.ts" -->

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  compatibilityDate: "2026-10-01",

  runtimeConfig: {
    sessionKey: "", // NUXT_SESSION_KEY: the JSON of an HS256 JWK
  },

  nitro: {
    experimental: { websocket: true },
  },
});
```

<!-- /automd -->

The util defines the session the first time it's asked for. `SessionData` is a type in `shared/types/`, so the server and the page agree on it:

<!-- automd:region src="../../playgrounds/nuxt-4/server/utils/session.ts" -->

```ts [session.ts]
import { createError, useRuntimeConfig } from "nuxt/server";
import {
  type JWK_oct,
  type SessionDefinition,
  type WebSessionEvent,
  defineJWSSession,
} from "unjwt/session";

let definition: SessionDefinition<SessionData, "1h"> | undefined;

/** Reads the key from the runtime config once, on first use. */
export function appSession(): SessionDefinition<SessionData, "1h"> {
  if (definition) return definition;
  // Nuxt parses a JSON environment variable into an object; a value set in nuxt.config stays a string
  const { sessionKey } = useRuntimeConfig() as { sessionKey: string | JWK_oct };
  if (!sessionKey) throw new Error("NUXT_SESSION_KEY is not set");
  definition = defineJWSSession<SessionData, "1h">({
    key: typeof sessionKey === "string" ? JSON.parse(sessionKey) : sessionKey,
    maxAge: "1h",
    rolling: "15m",
  });
  return definition;
}

export function useAppSession(event: WebSessionEvent) {
  return appSession().use(event);
}

export async function requireAppSession(event: WebSessionEvent) {
  const session = await useAppSession(event);
  if (!session.id) throw createError({ statusCode: 401, message: "Sign in first" });
  return session;
}
```

<!-- /automd -->

A server plugin asks for it once while the server starts, so a missing key, or one of the wrong kind, stops a production server at boot:

<!-- automd:region src="../../playgrounds/nuxt-4/server/plugins/session-key.ts" -->

```ts [session-key.ts]
// A missing or malformed key stops the server at start-up, not at the first sign-in
export default defineNitroPlugin(() => {
  appSession();
});
```

<!-- /automd -->

- **Object or string**: Nuxt turns an environment variable that holds JSON into an object before your code sees it, so the util parses only a string.
- **Defined on first use**: the runtime config is read inside a function, once Nuxt has loaded it, not when a route imports the file.
- **The name**: Nuxt already auto-imports a `useSession`, so the util's exports are called `useAppSession` and `requireAppSession`.
- **Lifetime**: `maxAge: "1h"` ends a token an hour after it was signed. `rolling: "15m"` signs a fresh hour on the first request that finds the token at least 15 minutes old, so an active user stays in.
- **Readable data**: the cookie is `HttpOnly`, so page scripts can't read it, but the user can decode it. Keep secrets out of `update()`, or use a JWE session.

## Sign users in and out

One file per route under `server/routes/`:

<!-- automd:region src="../../playgrounds/nuxt-4/server/routes/login.post.ts" -->

```ts [login.post.ts]
import { createError, defineEventHandler, readBody } from "nuxt/server";

export default defineEventHandler(async (event) => {
  const body = await readBody<{ user?: unknown } | undefined>(event);
  if (typeof body?.user !== "string") {
    throw createError({ statusCode: 400, message: "user required" });
  }
  const session = await useAppSession(event);
  await session.update({ user: body.user });
  return { user: session.data.user };
});
```

<!-- /automd -->

<!-- automd:region src="../../playgrounds/nuxt-4/server/routes/me.get.ts" -->

```ts [me.get.ts]
import { defineEventHandler } from "nuxt/server";

export default defineEventHandler(async (event) => {
  const session = await requireAppSession(event);
  return session.data;
});
```

<!-- /automd -->

<!-- automd:region src="../../playgrounds/nuxt-4/server/routes/logout.post.ts" -->

```ts [logout.post.ts]
import { defineEventHandler } from "nuxt/server";

export default defineEventHandler(async (event) => {
  const session = await useAppSession(event);
  await session.clear();
  return { ok: true };
});
```

<!-- /automd -->

- **No session yet**: `session.id` stays `undefined` until `update()` signs a first token, and `requireAppSession` turns that into a 401.
- **Cookie on the way out**: `update()` and `clear()` write `Set-Cookie` onto the event's response. The header stays on a thrown error too, so `clear()` followed by `createError` still signs the user out.

## Call the routes from a page

`$fetch` from the browser sends the cookie with every request to the same origin, so the page needs no session code of its own:

<!-- automd:region src="../../playgrounds/nuxt-4/app.vue" lang="vue" -->

```vue [app.vue]
<script setup lang="ts">
const log = ref<string[]>([]);
const say = (line: string) => log.value.unshift(line);

async function call(path: string, method: "GET" | "POST" = "GET", body?: Record<string, unknown>) {
  try {
    const result = await $fetch(path, { method, body });
    say(`${method} ${path} → ${JSON.stringify(result)}`);
  } catch (error) {
    const failure = error as { statusCode?: number; data?: { message?: string }; message?: string };
    say(
      `${method} ${path} → ${failure.statusCode ?? "?"} ${failure.data?.message ?? failure.message}`,
    );
  }
}

function openSocket() {
  const ws = new WebSocket(`${location.origin.replace("http", "ws")}/ws`);
  ws.addEventListener("open", () => ws.send("ping"));
  ws.addEventListener("message", (event) => say(`ws ← ${event.data}`));
  ws.addEventListener("error", () => say("ws → refused"));
  ws.addEventListener("close", (event) => say(`ws closed (${event.code})`));
}
</script>

<template>
  <main style="font-family: system-ui; max-width: 40rem; margin: 2rem auto">
    <h1>unjwt on Nuxt 4</h1>
    <p>
      <button @click="call('/login', 'POST', { user: 'user_1a2b' })">login</button>
      <button @click="call('/me')">me</button>
      <button @click="call('/logout', 'POST')">logout</button>
      <button @click="openSocket()">websocket</button>
      <button @click="call('/throw-after-clear')">throw after clear</button>
    </p>
    <pre v-for="(line, i) in log" :key="i">{{ line }}</pre>
  </main>
</template>
```

<!-- /automd -->

- **No token in the page**: the cookie is `HttpOnly`, so the page never sees the token. It learns who is signed in by asking `/me`.
- **During server rendering**: a `$fetch` that runs on the server during the first render forwards no cookie by itself. Call the routes from the browser, as the buttons do, or use `useRequestFetch()` for a call that has to run while the page renders.

## Read the session in a WebSocket

`nuxt/server` has no WebSocket API, so the route uses h3's `defineWebSocketHandler`. The session is read once, in `upgrade`, the only hook that can still refuse a client:

<!-- automd:region src="../../playgrounds/nuxt-4/server/routes/ws.ts" -->

```ts [ws.ts]
import { defineWebSocketHandler } from "h3";
import type { SessionManager } from "unjwt/session";

export default defineWebSocketHandler({
  async upgrade(request) {
    // Named, not spread: on Nitro 3 the request is a `Request`, and a spread loses its `headers`
    const headers = new Headers();
    const session = await useAppSession({
      headers: request.headers,
      context: request.context,
      res: { headers },
    });
    if (!session.id) return new Response("Sign in first", { status: 401 });

    // `request.context` becomes every later hook's `peer.context`; `headers` ride on the 101 response
    Object.assign(request.context, session);
    return { headers };
  },

  open(peer) {
    const { data } = getContext(peer);
    peer.send(`hello ${data.user}`);
  },

  message(peer, message) {
    const { expiresAt } = getContext(peer);
    if (expiresAt < Date.now()) {
      peer.close(4401, "Session expired");
      return;
    }
    peer.send(`echo: ${message.text()}`);
  },
});

function getContext(peer: { context: Record<string, unknown> }): SessionManager<SessionData, "1h"> {
  return peer.context as unknown as SessionManager<SessionData, "1h">;
}
```

<!-- /automd -->

- **A response for the handshake**: passing a fresh `Headers` as `res` lets the read sign a rolled token or drop an expired cookie, and returning those headers sends them on the `101` response.
- **Refusal**: returning a `Response` answers the upgrade with that status, and the socket never opens.
- **A snapshot**: `request.context` keeps the session's values as they were at the upgrade. The socket can't renew the cookie, so it closes with `4401` once `expiresAt` has passed.
- **Only here**: server middleware doesn't run for a WebSocket upgrade, so `upgrade` is the one place the socket's session is read.

## When it fails

| Situation                                            | What happens                                                                                                                                                |
| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `NUXT_SESSION_KEY` unset or empty                    | A built server stops at boot with `NUXT_SESSION_KEY is not set`. Under `nuxt dev` every request answers 500 with that message until you set it and restart. |
| `NUXT_SESSION_KEY` is not JSON                       | Nuxt keeps it as a string and `JSON.parse` throws a `SyntaxError`, the same way.                                                                            |
| JSON that is not a signing key, such as a public JWK | `defineJWSSession` throws `ERR_SESSION_KEY_INVALID` when the plugin asks for the session, the same way. See [Handle errors](/safety/errors).                |
| An `HS256` JWK whose `k` doesn't decode              | Every request that opens the session answers 500: `use()` throws `ERR_SESSION_KEY_INVALID`.                                                                 |
| A route on the auto-imported `defineEventHandler`    | `use()` throws `ERR_SESSION_INVALID`: `use() got an event whose "req" is not a web Request`. Import it from `nuxt/server`.                                  |
| Plain HTTP on a host other than `localhost`          | `/login` answers 200 with the cookie, the browser refuses a `Secure` cookie over HTTP, and `/me` stays 401. Serve over HTTPS.                               |
| Request without the cookie                           | `/me` answers 401, and the WebSocket upgrade is refused with 401.                                                                                           |
| Token older than `maxAge`                            | `/me` answers 401, the response drops the cookie, and the [`onExpire` hook](/sessions/hooks) fires.                                                         |
| Cookie signed with another key, or changed by hand   | Same 401 and cookie drop. The `onError` hook gets `ERR_SESSION_TOKEN_INVALID`; nothing is thrown from `use()`.                                              |

## Going further

- **Hide the data**: `defineJWESession` encrypts the token, so the user can't read it either. It takes an `oct` key such as `generateJWK("A256GCM")`; see [Configure a session](/sessions/configure).
- **API clients**: set `sessionHeader` so a mobile app that calls the same routes sends the token in a header. A header that holds the cookie's own token keeps the request a cookie session. See [Sessions without cookies](/sessions/api-clients).
- **Revocation and audit**: hooks run when a session is read, updated, cleared or expires. See [Hooks](/sessions/hooks).
- **Without Nuxt**: the [Nitro](/examples/nitro) recipe is the same server code on a bare Nitro app.
