Sessions on Nitro
Keep a signed session cookie on Nitro with one server util keyed from the runtime config, three routes, and a WebSocket that reads the session at the upgrade.
Nitro hands every route an h3 event, { req, res, context }, and the session reads that shape as it is. One file in server/utils/ defines the session and every route imports it. 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 has the vocabulary.
#Before you start
Install both packages in your Nitro app:
pnpm add nitro unjwtA session key that survives restarts. Generate it once, in your project folder:
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 asNITRO_SESSION_KEYin your host's secrets, or in a.envfile you never commit. Whoever holds it can sign a session for any user. Replacing it signs everyone out.HTTPS, or
localhostwhile you develop. The cookie is called__Host-unjwt-jwsand carriesSecure, so a browser drops it on plain HTTP anywhere else.Nitro has no auto-imports here:
defineHandler,definePlugin,defineWebSocketHandlerandHTTPErrorcome fromnitro,readBodyfromnitro/h3, and the util is imported by path.
#Read the key from the runtime config
Declare the key in nitro.config.ts, with an empty default, next to the WebSocket switch the last section needs. Nitro fills runtimeConfig.sessionKey from NITRO_SESSION_KEY when the server starts:
import { defineConfig } from "nitro";
export default defineConfig({
serverDir: "./server",
features: { websocket: true },
runtimeConfig: {
sessionKey: "", // NITRO_SESSION_KEY: the JSON of an HS256 JWK
},
});The util defines the session the first time it's asked for, and exports what the routes need:
import { HTTPError } from "nitro";
import { useRuntimeConfig } from "nitro/runtime-config";
import { type SessionDefinition, type WebSessionEvent, defineJWSSession } from "unjwt/session";
export interface SessionData {
user: string;
}
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;
const { sessionKey } = useRuntimeConfig();
if (!sessionKey) throw new Error("NITRO_SESSION_KEY is not set");
definition = defineJWSSession<SessionData, "1h">({
key: JSON.parse(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 new HTTPError({ status: 401, message: "Sign in first" });
return session;
}A plugin asks for it once while the server starts, so a missing key, or one of the wrong kind, stops the server instead of the first sign-in:
import { definePlugin } from "nitro";
import { appSession } from "../utils/session.ts";
// A missing or malformed key stops the server at start-up, not at the first sign-in
export default definePlugin(() => {
appSession();
});- Defined on first use: the runtime config is read inside a function, once Nitro has loaded the environment, not when a route imports the file.
- Any event:
useAppSessiontakes aWebSessionEvent, which covers a route's event, the WebSocket upgrade request below, and a token in hand. See Read, update and clear. - 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 ofupdate(), or use a JWE session.
#Sign users in and out
One file per route under server/routes/:
import { HTTPError, defineHandler } from "nitro";
import { readBody } from "nitro/h3";
import { useAppSession } from "../utils/session.ts";
export default defineHandler(async (event) => {
const body = await readBody<{ user?: unknown }>(event);
if (typeof body?.user !== "string") {
throw new HTTPError({ status: 400, message: "user required" });
}
const session = await useAppSession(event);
await session.update({ user: body.user });
return { user: session.data.user };
});import { defineHandler } from "nitro";
import { requireAppSession } from "../utils/session.ts";
export default defineHandler(async (event) => {
const session = await requireAppSession(event);
return session.data;
});import { defineHandler } from "nitro";
import { useAppSession } from "../utils/session.ts";
export default defineHandler(async (event) => {
const session = await useAppSession(event);
await session.clear();
return { ok: true };
});- No session yet:
session.idstaysundefineduntilupdate()signs a first token, andrequireAppSessionturns that into a 401. - Cookie on the way out:
update()andclear()writeSet-Cookieonto the event's response, so it leaves with the value the route returns.clear()sendsMax-Age=0. The header stays on a thrown error too, soclear()followed by a thrownHTTPErrorstill signs the user out. - Try it:
curl -c jar -X POST localhost:3000/login -H 'content-type: application/json' -d '{"user":"user_1a2b"}', thencurl -b jar localhost:3000/me.
#Read the session in a WebSocket
A WebSocket can only refuse a client before it opens, in upgrade, and nothing reaches the client's cookies once it's open. So the route reads the session once there, refuses a client without one, and keeps a copy for the socket's later hooks:
import { defineWebSocketHandler } from "nitro";
import type { SessionManager } from "unjwt/session";
import { type SessionData, useAppSession } from "../utils/session.ts";
export default defineWebSocketHandler({
async upgrade(request) {
// Named, not spread: 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) throw new Response("Sign in first", { status: 401 });
// `headers` ride on the 101 response; `context` becomes every later hook's `peer.context`
return { headers, context: { ...session } };
},
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">;
}The features: { websocket: true } line in nitro.config.ts turns WebSockets on. Then:
- A response for the handshake: passing a fresh
Headersasreslets the read sign a rolled token or drop an expired cookie, and returning those headers sends them on the101response. Keep the session small enough for one cookie here, since the upgrade keeps oneSet-Cookieline. - Refusal: throwing a
Responseanswers the upgrade with that status, and the socket never opens. - A snapshot:
contextholds the session's values as they were at the upgrade. The socket can't renew the cookie, so it closes with4401onceexpiresAthas passed and lets the client reconnect after signing in again.
#When it fails
| Situation | What happens |
|---|---|
NITRO_SESSION_KEY unset or empty | The plugin throws NITRO_SESSION_KEY is not set and the server doesn't start. In development, nitro dev logs it and answers 503. |
NITRO_SESSION_KEY is not JSON | JSON.parse throws a SyntaxError at start-up, 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. |
An HS256 JWK whose k doesn't decode | Every request that opens the session answers 500: use() throws ERR_SESSION_KEY_INVALID. |
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 and the onExpire hook fires. The browser has already deleted the cookie by then, since its Expires is the token's. |
| Cookie signed with another key, or changed by hand | 401. The onError hook gets ERR_SESSION_TOKEN_INVALID; nothing is thrown from use(). |
clear() followed by a thrown error | The client is signed out: the error response carries the Max-Age=0 line clear() wrote, as on h3. |
#Going further
- Hide the data:
defineJWESessionencrypts the token, so the user can't read it either. It takes anoctkey such asgenerateJWK("A256GCM"); see Configure a session. - API clients: set
sessionHeaderso a client that keeps no cookies 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. - Revocation and audit: hooks run when a session is read, updated, cleared or expires. See Hooks.
- Inside Nuxt: the Nuxt recipe runs the same util under
nuxt/server.