Sessions on h3

Sign users in with a signed session cookie on h3, read it on every request, and guard a group of routes with one middleware.

An h3 event already has the shape a session reads: the incoming Request on event.req, the response headers on event.res, and a context that lives for one request. So you hand the event to the session as it is, with no adapter in between. The session is a JWS, a token with a signature across it: the server can tell whether it wrote the cookie, and anyone holding the cookie can read what's inside. Concepts has the vocabulary.

#Before you start

  • Install both packages:

    pnpm add h3 unjwt
  • A 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 as SESSION_KEY in your secret manager, or in a .env file you never commit and load with node --env-file=.env. 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.

#Sign users in and out

The app reads the key at start-up, defines the session once, and opens it in each route with appSession.use(event):

h3.ts
import { H3, HTTPError, readBody } from "h3";
import { defineJWSSession } from "unjwt/session";

const SESSION_KEY = process.env.SESSION_KEY;
if (!SESSION_KEY) throw new Error("SESSION_KEY is not set");

export const appSession = defineJWSSession<{ user: string }, "1h">({
  key: JSON.parse(SESSION_KEY),
  maxAge: "1h",
  rolling: "15m",
});

export const app = new H3()
  .post("/login", 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 appSession.use(event);
    await session.update({ user: body.user });
    return { user: session.data.user };
  })
  .get("/me", async (event) => {
    const session = await appSession.use(event);
    if (!session.id) throw new HTTPError({ status: 401, message: "Sign in first" });
    return session.data;
  })
  .post("/logout", async (event) => {
    const session = await appSession.use(event);
    await session.clear();
    return { ok: true };
  });

Start it with serve(app) from h3, or hand app.fetch to any runtime that takes a fetch handler. What each part does:

  • Start-up check: without SESSION_KEY the module throws before the server listens, so a forgotten variable stops the deploy instead of the first sign-in.
  • The event as it is: use(event) reads the cookie from event.req and writes Set-Cookie onto event.res, so the cookie leaves with whatever the route returns.
  • No session yet: session.id stays undefined until update() signs a first token. That's the check /me makes, and reading alone never sets a cookie.
  • 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 and an idle one is out 45 to 60 minutes after their last request.
  • 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 (see Going further).
  • Sign out: clear() sends the cookie back with Max-Age=0, and the browser deletes it.

#Guard a group of routes

An h3 middleware sees the same event as the route after it, and the session keeps its state on event.context. A middleware can therefore refuse a request without a session, and the route opens the same session again without a second read:

h3.ts
app.use("/account/**", async (event) => {
  const session = await appSession.use(event);
  if (!session.id) throw new HTTPError({ status: 401, message: "Sign in first" });
});

app.get("/account/profile", async (event) => {
  // Same event, same session: the middleware's read is reused
  const session = await appSession.use(event);
  return { user: session.data.user, expiresAt: session.expiresAt };
});
  • One read per request: the second use(event) returns the session the middleware opened. The token is verified once, and the onRead hook fires once.
  • Returning nothing continues: a middleware that returns undefined hands the request on; the thrown HTTPError ends it with a 401 before the route runs.

#What else the definition does

appSession does more than use(). It also hands you the token a request carries without opening it, mints a token without a request, and opens a token that arrived some other way. The routes below join the app above, in a file of their own.

#Pass the raw token on

token(event) returns the token the request carries, unopened and unchecked. Use it to forward the token to a service that verifies it with its own copy of the key:

h3-definition.ts
import { HTTPError, readBody } from "h3";
import { isJWTError } from "unjwt/error";
import { app, appSession } from "./h3.ts";

app.get("/reports", (event) => {
  const token = appSession.token(event);
  if (!token) throw new HTTPError({ status: 401, message: "Sign in first" });
  // Passed on unopened: the reports service checks it with its own copy of the key
  return fetch("https://reports.example.com/v1/summary", {
    headers: { authorization: `Bearer ${token}` },
  });
});
  • Unchecked: an expired or forged cookie is forwarded too, so the service on the other end decides. A use(event) earlier in the request doesn't change that, even when it could not open the token; after update() it is the new token, after clear() undefined. session.token is the token behind the session's data, undefined after a failed read: see Two views of the token.

#Hand out a token in a response body

issue(data) mints a token with a fresh ID and the definition's maxAge, and reads or writes no request. Here a signed-in user gets a first API token in the JSON body, and { maxAge: "15m" } shortens this one token:

h3-definition.ts
app.post("/api-token", async (event) => {
  const session = await appSession.use(event);
  if (!session.id) throw new HTTPError({ status: 401, message: "Sign in first" });
  const token = await appSession.issue({ user: session.data.user }, { maxAge: "15m" });
  return { token };
});
  • A session token: it opens like the cookie, so whoever holds it is signed in as that user until it expires. A client that keeps no cookies sends it back once you set sessionHeader, as Sessions without cookies does.

#Open a token that arrived some other way

open(token) checks a token with the same rules as the cookie and returns { id, createdAt, expiresAt, data, source }, with source always "token". It runs no hooks and throws instead: ERR_JWT_EXPIRED for an expired token, ERR_SESSION_TOKEN_INVALID for any other. Here another service of yours posts a token and asks whether it is still good:

h3-definition.ts
app.post("/internal/session-check", async (event) => {
  const body = await readBody<{ token?: unknown }>(event);
  if (typeof body?.token !== "string") return { valid: false };
  try {
    const { data, expiresAt } = await appSession.open(body.token);
    return { valid: true, user: data.user, expiresAt };
  } catch (error) {
    if (isJWTError(error)) return { valid: false };
    throw error;
  }
});
  • Keep it internal: anyone who reaches the route can test tokens against it, so serve it on your internal network or behind your own service auth.

#The session use() returns

  • session.source is "cookie", "header" or "token", and decides what update() and clear() reach.
  • session.update(data, { maxAge }) merges data and issues a new token with its own lifetime, written to the cookie on a cookie session.
  • session.clear() empties the session and expires the cookie on a cookie session.

Read, update and clear has the details of each.

Wrap the definition in a useAppSession(event) helper, as the Nitro and Nuxt recipes do, when the key comes from a runtime config read on first use or when routes in many files share one guard. An app that reads its key at start-up, as this one does, calls appSession.use(event) directly.

#When it fails

SituationWhat happens
SESSION_KEY unset or emptyThe module throws SESSION_KEY is not set at start-up.
SESSION_KEY is not JSONJSON.parse throws a SyntaxError at start-up. Store the line generateJWK printed, quotes included.
JSON that is not a signing key, such as a public JWKdefineJWSSession throws ERR_SESSION_KEY_INVALID at start-up, and the server doesn't start. See Handle errors.
An HS256 JWK whose k doesn't decodeEvery 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 cookiesession.id is undefined, so /me and every /account/** route answer 401.
Token older than maxAgeThe session opens empty, /me answers 401, and the response drops the cookie. The onExpire hook fires.
Cookie signed with another key, or changed by handSame 401 and cookie drop. The onError hook gets ERR_SESSION_TOKEN_INVALID; nothing is thrown from use().
/login without a user string400, and no cookie is set.

#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.
  • API clients: set sessionHeader so a client that keeps no cookies, such as a command-line tool, 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.
  • Every route the same way: the Nitro recipe runs this flow with one file per route and a WebSocket on top.