Read, update and clear

Open the session of a request, sign a visitor in, change what the session holds, sign them out, and mint or open tokens without a request.

Every request starts with use(event): it reads the token the request carries and gives you the session, a small object with the visitor's data and two actions, update() and clear(). The examples on this page run in any handler that receives a Request and returns a Response, such as Cloudflare Workers, Bun, Deno or Hono, and they use the appSession definition from Configure a session. For h3, Nitro and Nuxt, their event goes to use() as it is: Sessions points to each recipe.

#Before you start

  • A session definition, made once at start-up, as in Configure a session.
  • Pass use() the request you are handling, never an object you keep between requests. The session of a request is remembered on that request, so a second use() in the same request returns the same session.
  • One name is one cookie. Two definitions of the same kind with the same name share one session on a request, and a JWS and a JWE definition under one name on the same request throw ERR_SESSION_CONFIG_INVALID.
  • Update or clear the session before you build the Response. new Response(body, { headers }) copies the headers when it is created, so a cookie written afterwards never reaches the client, and nothing tells you so.

#What use() takes

You passThe session readsupdate() and clear() on a cookie session
{ req, res: { headers } }the cookie of req, or the session header when you name onewrite Set-Cookie lines onto headers
a Request, { req } or { headers }the sameupdate() throws, clear() empties the session
{ token }that tokennot a cookie session: see below

req is the incoming Request, and headers is the Headers you send the response with. Any other object throws ERR_SESSION_INVALID.

#Where the token came from

session.source says where this request's token comes from, and it decides what update() and clear() reach. It is picked before the token is opened and holds for the whole request:

session.sourceThe token came fromupdate()clear()
"cookie"the cookie, also when the session header holds the same tokenwrites the new token to the cookieexpires the cookie
"header"the session header, when the request sends no cookie or one holding another tokenputs the new token on session.token aloneempties the session for this request; the client keeps its token
"token"the token you passed as use({ token })puts the new token on session.token aloneempties the session for this request; the client keeps its token

A header or token session writes nothing to the response and never rolls: a new token reaches the client only if you send it, as Sessions without cookies does. Configure a session has the rule for a request that sends both a header and a cookie.

#Sign a visitor in

After your own check of the credentials, write the visitor into the session:

handlers.ts
/** Call once your own credential check has passed. */
export async function signIn(req: Request, user: { id: string; role: "member" | "admin" }) {
  const headers = new Headers();
  const session = await appSession.use({ req, res: { headers } });
  await session.update({ userId: user.id, role: user.role });
  return Response.json({ expiresAt: session.expiresAt }, { headers });
}
  • No session yet: before update(), session.id is undefined and session.token too. Calling use() alone sets no cookie, so visitors who never sign in never get one.
  • update(): merges the object into session.data, issues a new token with a fresh id, and adds its Set-Cookie line to headers.
  • Reserved names: jti, iat, exp and nbf are the session's own claims. They are dropped from what you pass and never appear in session.data.

#Read the session

A request that carries a valid token gets its data back. One without a token, or with a token that is expired, tampered with or not a session at all, gets an empty session:

handlers.ts
export async function profile(req: Request) {
  const headers = new Headers();
  const session = await appSession.use({ req, res: { headers } });
  if (!session.id) return new Response("Sign in first", { status: 401, headers });
  return Response.json(session.data, { headers });
}

if (!session.id) is the check for "signed in". The response passes headers on even here, because rolling may replace the token as it is read, and a token that fails its checks has its cookie expired. The session has these members:

MemberHolds
idThe token's ID (jti), or undefined without a session. Changes with every update().
dataYour data, typed by the definition. {} without a session.
createdAtWhen the current token was issued, in milliseconds.
expiresAtWhen it expires, in milliseconds: its exp, or issue time plus maxAge if that is sooner.
tokenThe token behind data: read and opened, or issued by update(). undefined after a failed read.
source"cookie", "header" or "token": where the token of this request comes from.
errorThe JWTError the read ended with, or undefined: see Tell what happened to the token.
update()Merges data, issues a new token, writes the cookie on a cookie session. Resolves to the same session.
clear()Empties the session and expires the cookie on a cookie session. Resolves to the same session.

Data travels as JSON: the request that writes it keeps the values you gave, and later requests get them back the way JSON.parse would. A Date comes back as a string.

#Change the session

update() with an object changes only the keys you name:

handlers.ts
export async function switchWorkspace(req: Request, workspaceId: string) {
  const headers = new Headers();
  const session = await appSession.use({ req, res: { headers } });
  if (!session.id) return new Response("Sign in first", { status: 401, headers });
  await session.update({ workspaceId });
  return new Response(null, { status: 204, headers });
}

update() also takes a function of the current data. It returns the keys to change, or changes the data in place and returns nothing. undefined with no change keeps the data as it is. A second argument gives this one token its own lifetime:

await session.update((data) => (data.role === "member" ? { role: "admin" } : undefined));
await session.update((data) => {
  delete data.workspaceId; // in place, returns nothing
});
await session.update(undefined, { maxAge: "15m" }); // a new token, same data, 15 minutes

update() with no arguments issues a new token with a new ID and a fresh expiry, and keeps the data. A token issued earlier keeps working until it expires. A longer maxAge than the config's still ends at the config's maxAge when the token is read back.

Await each update() and clear() before the next one. Calls that overlap on one session run in no set order, and the last cookie write wins.

#Sign a visitor out

handlers.ts
export async function signOut(req: Request) {
  const headers = new Headers();
  const session = await appSession.use({ req, res: { headers } });
  await session.clear();
  return new Response(null, { status: 204, headers });
}

clear() leaves an empty session for the rest of the request and writes a Set-Cookie line with Max-Age=0 for the cookie, and for every part of a split one. It works when the request carried no session too.

#What the response carries

You didheaders gets
use() only, on a valid tokennothing, unless rolling replaced the token
use() on a cookie that fails its checksa Max-Age=0 line that removes it
use() when onKeyLookup failsnothing: the cookie is kept
update()the new cookie; a second update() replaces that line
clear()a Max-Age=0 line, replacing any line written earlier
anything, on a header or token sessionnothing: the new token is on session.token

Other Set-Cookie lines in headers, such as a theme cookie, are kept.

#Read without a response

A Request on its own reads the session and writes nothing. It suits a check that never changes the session, such as a WebSocket upgrade or a server-rendered page that only shows the user's name:

const session = await appSession.use(req);
session.data.userId; // "user_1a2b"
await session.update({ role: "admin" }); // throws ERR_SESSION_READONLY_EVENT

clear() on such a session empties it for the rest of the request and resolves; the cookie stays with the client until a request with a response clears it. An expired or unreadable token still reaches its hooks, and rolling waits for the next request.

The read-only case is a cookie session's: it has a cookie to write and no response to write it to. A session header that holds the same token as the cookie still makes the request a cookie session, so update() throws there too. A request whose header holds another token, or that sends no cookie, is a header session, and update() puts the new token on session.token.

#Use a token you hold

Some clients keep the token themselves and send it inside a message, such as a desktop app talking JSON or a job in a queue. Hand that token to use():

handlers.ts
/** A desktop client keeps its token itself and sends it in each message. */
export async function renew(message: { session: string }) {
  const session = await appSession.use({ token: message.session });
  if (!session.id) return { session: null };
  await session.update();
  return { session: session.token ?? null };
}

The token goes through the same checks and hooks as a cookie, and session.source is "token". update() puts the new token on session.token and writes nothing; clear() leaves session.token undefined. rolling never reissues it. The config's cookie and sessionHeader play no part, and use({ token: undefined }) is an empty session.

#Issue and open tokens without a request

issue(data) mints a token with a fresh ID and the definition's maxAge, and open(token) reads one back with the same checks as a cookie. Neither needs a request, which makes them the pair for magic links, email confirmations and API tokens:

magic-link.ts
import { isJWTError } from "unjwt/error";
import { defineJWESession } from "unjwt/session";
import { appSession } from "./app-session.ts";

// const linkKey = a second "oct" JWK, loaded like SESSION_KEY

const magicLink = defineJWESession<{ email: string }, "15m">({
  key: linkKey,
  maxAge: "15m",
  cookie: false,
  sessionHeader: false,
});

/** The link to email; it signs in whoever opens it within 15 minutes. */
export async function magicLinkFor(email: string) {
  const url = new URL("https://app.example.com/auth/callback");
  url.searchParams.set("token", await magicLink.issue({ email }));
  return url;
}

/** `GET /auth/callback?token=…`: opens the link token, then starts the app session. */
export async function redeemMagicLink(req: Request) {
  const token = new URL(req.url).searchParams.get("token");
  if (!token) return new Response("Missing token", { status: 400 });

  let email: string;
  try {
    ({ email } = (await magicLink.open(token)).data);
  } catch (error) {
    if (isJWTError(error)) return new Response("This link is invalid or expired", { status: 401 });
    throw error;
  }

  const user = await findUserByEmail(email);
  const headers = new Headers({ location: "/" });
  const session = await appSession.use({ req, res: { headers } });
  await session.update({ userId: user.id, role: user.role });
  return new Response(null, { status: 303, headers });
}
  • A definition of its own: cookie: false and sessionHeader: false mean no request can carry this token by accident: use() on a request throws ERR_SESSION_CONFIG_INVALID, while use({ token }) works.
  • Its own key: the link token cannot be replayed as the app's session cookie, because the app session cannot open it.
  • Failures throw: open() has no hooks to report to, so an expired token throws ERR_JWT_EXPIRED, and a tampered or foreign one ERR_SESSION_TOKEN_INVALID. With onKeyLookup set, a lookup that fails throws ERR_SESSION_READ_FAILED. All are JWTErrors.
  • What open() returns: { id, createdAt, expiresAt, data, source }, with source always "token". issue() takes { maxAge } as a second argument, like update().

#Read the raw token

token(event) returns the token a request carries, unopened and unchecked, from the source that request runs on: a token in hand, the session header for a header session, else the cookie. What use() makes of it doesn't change it: a token that fails its checks, or whose read fails, is returned as it was sent. After update() it returns the new token, after clear() undefined. A header that holds no token, such as Basic …, gives undefined too.

#Two views of the token

token(event)session.token
Holdsthe token the request carries, or the new tokenthe token behind session.data
After a failed readthe token as it was sentundefined
After update()the new tokenthe new token
After clear()undefinedundefined
  • token(event): forward or log the token a request carried, or tell a request without a token, undefined, from one whose token could not be checked, a token while session.id is undefined.
  • session.token: hand a client its new token after update(), as Use a token you hold does.

#Tell what happened to the token

session.error is the JWTError the read ended with, the same object onExpire or onError received, so a handler can answer each outcome without a hook. This one runs on the appSession of Rotate with onKeyLookup, whose keys come from a secret manager, so a read can fail even with a good token:

read-outcome.ts
import { appSession } from "./key-lookup.ts";

/** `GET /dashboard`: the visitor's data, a guest view, or why there is neither. */
export async function dashboard(req: Request) {
  const headers = new Headers();
  const session = await appSession.use({ req, res: { headers } });
  if (session.id) return Response.json({ userId: session.data.userId }, { headers });

  switch (session.error?.code) {
    case undefined:
      return Response.json({ guest: true }, { headers });
    case "ERR_SESSION_READ_FAILED":
      headers.set("retry-after", "5");
      return new Response("Sign-in is unavailable, try again shortly", { status: 503, headers });
    case "ERR_JWT_EXPIRED":
      return new Response("Your session expired, sign in again", { status: 401, headers });
    default:
      return new Response("Sign in again", { status: 401, headers });
  }
}
session.idsession.errorThe request carriedA cookie session's cookie
setundefineda token that openedkept, or replaced by rolling
undefinedundefinedno tokennone to change
undefinedERR_JWT_EXPIREDan expired tokenexpired
undefinedERR_SESSION_TOKEN_INVALIDa token that failed its checks, the reason as causeexpired
undefinedERR_SESSION_READ_FAILEDa token the session could not check: onKeyLookup threw or returned a key that cannot be used, that error as causekept
  • 401 for a dead token: an expired token and one that fails its checks both end the session, and a cookie session's cookie is already expired, so the visitor signs in again.
  • 503 for a read failure: the token may be good and the cookie is kept, so the visitor is signed in again once the secret manager answers. session.error.cause is what the lookup threw, for your logs; rethrow it instead to let your own error handling answer.
  • A guest: no id and no error is a request without a token. It is also what a session cleared in onRead looks like.
  • Once per request: the token is read on the first use(), so a later use() in the same request sees the same error.
  • After update() or clear(): error is undefined. The oldSession that onUpdate and onClear receive carries it.

#When it fails

SituationWhat happens
The token is missingAn empty session; id is undefined.
The token is expired, tampered with, under another key or not a sessionAn empty session, a cookie session's cookie expired, and onExpire or onError fires with the error session.error then holds. use() does not throw. A failing header token never falls back to the cookie.
onKeyLookup throws, or returns a key that cannot be used for the tokenAn empty session, the cookie kept, and onError and session.error get ERR_SESSION_READ_FAILED with that error as cause. use() does not throw. The lookup's key is yours to fix, not the token.
A token whose algorithm the session doesn't accept, with onKeyLookup setThe token's failure, whatever key the lookup returns: onError and session.error get ERR_SESSION_TOKEN_INVALID, and a cookie session's cookie is expired.
update() on a cookie session without a response, also when the session header holds the same tokenThrows ERR_SESSION_READONLY_EVENT.
update() with something other than a plain object, or a __proto__ keyThrows ERR_INVALID_OPTION.
use() with an object that is neither a request nor { token }Throws ERR_SESSION_INVALID.
A configured key of the right kind that doesn't importThe first use(), issue() or open() throws ERR_SESSION_KEY_INVALID. Other config errors throw when the session is defined: see Configure a session.
A JWS and a JWE definition with the same name on one requestThe second use() throws ERR_SESSION_CONFIG_INVALID.
open() on an expired tokenThrows ERR_JWT_EXPIRED.
open() on any other bad tokenThrows ERR_SESSION_TOKEN_INVALID, the reason as its cause.
open() when onKeyLookup throws or returns a key that cannot be usedThrows ERR_SESSION_READ_FAILED, that error as its cause.

A failed update() leaves the session as it was before the call, and undoes what an update function changed in place.

Handle errors lists every code.

#Going further

  • React to reads, updates and sign-outs: Hooks.
  • Clients without cookies: Sessions without cookies covers the session header and tokens in links.
  • Your framework: Sessions points to the recipe for h3, Nitro, Nuxt and Hono, and to Write a driver for any other framework.
  • Tokens for other services: a signed session, as in Configure a session, can be verified with verify and the public key.