Hooks

Run your own code when a session is read, issued, cleared, expires or fails, and choose the key an incoming token is checked with.

Hooks are functions in the session config that the session calls at fixed moments: when it reads a token, issues one, clears itself, finds a token expired, finds one it cannot open or fails to issue or write a token. One more picks the key a token is checked with, for keys you fetch as tokens arrive. onRead gets the live session, and the hooks of the other moments a copy of the session that moment is about. A hook can log the session, refuse it or change it: onRead clears or updates it directly, a throw in onUpdate cancels the update, and the other hooks reach the live session through use(event). Each hook may return a promise, and the session waits for it.

#Before you start

  • Hooks go in hooks of the config you pass to defineJWSSession or defineJWESession, described in Configure a session.
  • Every hook receives one object with config, the session's config, and event, what you passed to use(). config is the frozen copy the session took when it was defined: read it or destructure it, and an assignment to it or to any plain object inside it throws a TypeError.
  • A hook that throws makes the call that ran it reject. What a throw does lists each case.

#When each hook fires

HookFiresReceivesCan change the outcome
onReadOnce per request, when a valid token is read.session (the live session), rollYes: session.clear() or session.update() in the hook, and roll.skip() holds back a due roll.
onUpdateAfter update() or rolling issued a token, before anything is written.session (a copy of the new session), oldSession, triggerYes: a throw cancels the update.
onClearAfter clear() emptied the session and, on a cookie session, expired the cookie.oldSession (undefined without a session or a failed read)No.
onExpireWhen the incoming session token is past its expiry, after a cookie session's cookie was expired.session (the old id, createdAt, expiresAt, token and source), errorNo, the session is already empty.
onErrorWhen an incoming token cannot be opened, and when issuing or writing a token fails.session (a copy of the session the failure is about), oldSession, trigger, errorNo.
onKeyLookupBefore a session token is verified or decrypted, in use() and open().header (the token's protected header)It picks the key that opens the token: a JWK, a CryptoKey or a JWK Set.
  • One of three: a read ends in exactly one of onRead, onExpire and onError. onError also runs later in the request when an update() or a roll fails to issue or write its token.
  • oldSession: a copy of the session before the change, with its id, createdAt, expiresAt, data, token, source and error, the error its read ended with. On a first sign-in its id is undefined. After a failed read onClear receives one too, with that error. onError receives the session that is current again after a failed update or roll, and undefined after a failed read. The session of onUpdate and of onError is the same kind of copy, of the session just issued or the one the failure is about. Each copy is the hook's own: it never changes afterwards and changing it changes nothing else, so a hook may keep it, such as for logging later.
  • source: every session and oldSession a hook receives carries source, "cookie", "header" or "token", the place this request's token came from. Read, update and clear says what update() and clear() reach for each.
  • trigger: in onUpdate, "update" for a call to update(), "rolling" for a reissue by rolling. In onError, the operation that failed: "read" for the request's token, "update" or "rolling" for an update that could not issue or write its token. oldSession is undefined on a read, so check trigger first: TypeScript then narrows oldSession to a session.
  • Stop or log: a throw in onUpdate cancels the update. Throw to stop a token, such as when its audit record cannot be saved. Catch inside the hook when a failure must not stop the token.
  • roll: roll.due is true when rolling reissues this session right after onRead: a session read from its cookie, with rolling: true or a token at least that old, on a response that can still be written. roll.skip() keeps that reissue from running on this request, and does nothing when due is false. update() and clear() in the hook act the same whether or not it was called. Refresh data when the session rolls uses due, and Keep the session when the data cannot be fetched uses skip().
  • onExpire error: an ERR_JWT_EXPIRED JWTError, the same object session.error holds afterwards. Only a token that is otherwise a valid session reaches onExpire; an expired token with a bad signature or another type goes to onError.
  • onError error on a read: a JWTError whose code says whether the token is dead, the same object session.error holds afterwards, so a handler can answer it too. ERR_SESSION_TOKEN_INVALID means the token failed the session's checks, its cause the reason, such as ERR_JWS_SIGNATURE_INVALID, and a cookie session's cookie is expired. ERR_SESSION_READ_FAILED means onKeyLookup could not answer, its cause what failed, and the cookie is kept. Either way the session is empty for this request.
  • onError error on an update(): whatever issuing or writing the token threw, such as ERR_SESSION_INVALID for a token too long for its cookies, which fails before onUpdate runs, or ERR_SESSION_READONLY_EVENT for a response sent while onUpdate ran.
  • Not hooks: a configured key the session cannot use is a configuration error and reaches no hook. Defining the session throws ERR_SESSION_KEY_INVALID, or, for a key of the right kind that doesn't import, the first use() does.

#Refuse a revoked session

Tokens carry their own expiry, so a session you want to end early has to be refused when it is read. onRead is the place, and session.clear() in it ends the session for this request. On a cookie session it also expires the cookie; a client that sent the token in the header or in hand keeps it and may send it again, so this hook records those:

revocation.ts
import { type SessionSource, defineJWESession } from "unjwt/session";

// const key = the "oct" JWK from SESSION_KEY (see Configure a session)

const THIRTY_DAYS = 30 * 24 * 60 * 60 * 1000;

export interface AppSession {
  userId: string;
  /** Set at sign-in and kept by every later update. */
  signedInAt: number;
}

export const appSession = defineJWESession<AppSession, "7D">({
  key,
  maxAge: "7D",
  rolling: "1D",
  sessionHeader: true,
  hooks: {
    async onRead({ session }) {
      const { userId, signedInAt } = session.data;
      const signedOut = await signedOutEverywhereAt(userId);
      const tooOld = Date.now() - signedInAt > THIRTY_DAYS;
      if ((signedOut === undefined || signedInAt > signedOut) && !tooOld) return;
      if (session.source !== "cookie") await reportRevokedToken(userId, session.source);
      await session.clear();
    },
  },
});

/** "Sign out of all devices": every session signed in until now stops opening. */
export async function signOutEverywhere(userId: string) {
  await saveSignedOutEverywhereAt(userId, Date.now());
}
  • Sign-in time in the data: every update() issues a token with a new id and createdAt, so neither identifies a sign-in. signedInAt is written once and kept through every update, so it does.
  • Sign out everywhere: one timestamp per user refuses every session signed in before it, on every device, at its next request.
  • An absolute limit: rolling keeps an active cookie session alive forever. The 30-day check signs people out however active they are.
  • The handler sees the result: after a clear() in onRead, the handler gets an empty session, as if the request had carried no token, whatever its source.
  • sessionHeader: true: apps may also send the token in x-unjwt-jwe-session, so a token can arrive from the cookie, the header or your hand.
  • Branch on source: clear() refuses the session on every source, but only a cookie can be taken back. A token from the header or in hand stays with its client until it expires, so the hook reports it, for a client to follow up or a stolen token to trace.

Sign-in writes the timestamp along with the user:

revocation.ts
export async function signIn(req: Request, userId: string) {
  const headers = new Headers();
  const session = await appSession.use({ req, res: { headers } });
  await session.update({ userId, signedInAt: Date.now() });
  return new Response(null, { status: 204, headers });
}

#Refresh data when the session rolls

Data computed at sign-in, such as a user's grants, goes stale while rolling keeps the session alive. The roll is the moment to compute it again. This hook looks the user up on every read, refuses a blocked user, and refreshes the grants when roll.due is true. Most reads ask a replica, a copy of the database that is fast to reach and may lag a moment behind. A roll asks the primary, because the grants it reads stay in the token until the next roll:

refresh-on-roll.ts
import { defineJWESession } from "unjwt/session";

// const key = the "oct" JWK from SESSION_KEY (see Configure a session)

export interface AppSession {
  userId: string;
  /** Computed at sign-in and again at every roll. */
  grants: string[];
}

export const appSession = defineJWESession<AppSession, "7D">({
  key,
  maxAge: "7D",
  rolling: "1D",
  hooks: {
    async onRead({ session, roll }) {
      // The primary on a roll, a replica otherwise
      const user = await findUser(session.data.userId, { primary: roll.due });
      if (!user || user.blocked) {
        await session.clear();
        return;
      }
      if (roll.due) await session.update({ grants: user.grants });
    },
  },
});
  • One lookup: the record that answers the check also holds the fresh grants, so each read reaches storage once, whether it rolls or not.
  • The update is the roll: an update() in onRead issues the one token of the read, and onUpdate runs once with trigger: "update". When the hook leaves the session alone, rolling reissues it with the same data, and onUpdate gets trigger: "rolling".
  • Where roll.due is false: a token younger than rolling, a session read from the header or from a token in hand, and a request without a response or with one already sent. The data then stays as issued until an update() replaces it.
  • What a read checks between rolls: your choice. Here it is a replica; a cache, or no lookup at all, is the same choice. Whatever the hook doesn't check is trusted until the next roll, and a session read from the header or from a token in hand never rolls.
  • await the update: an update() still running when the hook returns doesn't stop the roll, and the read issues two tokens.

#Keep the session when the data cannot be fetched

A roll can come due while the data it refreshes cannot be fetched, such as when the database is down. The session itself is still valid, and roll.skip() keeps it as issued for this request. This hook asks the database for the grants only when a roll is due. It skips the roll when the database is unavailable, and rethrows any other error:

skip-roll.ts
import { defineJWESession } from "unjwt/session";

// const key = the "oct" JWK from SESSION_KEY (see Configure a session)

export interface AppSession {
  userId: string;
  /** Computed at sign-in and again at every roll. */
  grants: string[];
}

export const appSession = defineJWESession<AppSession, "7D">({
  key,
  maxAge: "7D",
  rolling: "1D",
  hooks: {
    async onRead({ session, roll }) {
      if (!roll.due) return;
      let grants: string[];
      try {
        grants = await loadGrants(session.data.userId);
      } catch (error) {
        if (!isUnavailable(error)) throw error;
        // Keep the session as issued, the next request tries again
        roll.skip();
        return;
      }
      await session.update({ grants });
    },
  },
});
  • Between rolls: the hook returns at once, so only a request whose roll is due reaches the database.
  • What a skip keeps: the session keeps its token, id, times and data, no cookie is written, and onUpdate does not run.
  • No extension: the token keeps its own expiry, so a skip never extends the session. A session whose every roll is skipped ends at that expiry.
  • The next request: it finds the roll due again, and the hook asks the database again.
  • await the lookup: roll.skip() counts only when it is called before the hook returns. Called later, such as from a lookup the hook did not await, it does nothing, and the roll has already run.
  • Without skip(): a hook that returns without updating the session lets rolling reissue it with its current data, for a new rolling period.
  • A throw: use() rejects with the error, the request has no session, and the cookie is kept.

#Record what happens

The other hooks suit an audit trail. Each one fires once for what it reports:

audit-hooks.ts
import { defineJWSSession } from "unjwt/session";

// const key = an HS256 JWK loaded at start-up (see Configure a session)

export const appSession = defineJWSSession<{ userId: string }, "1h">({
  key,
  maxAge: "1h",
  hooks: {
    onRead: ({ session }) => audit("read", session.id),
    onUpdate: ({ session, oldSession, trigger }) =>
      audit(trigger === "rolling" ? "rolled" : "issued", session.id, oldSession.id),
    onClear: ({ oldSession }) => audit("signed out", oldSession?.id),
    onExpire: ({ session }) => audit("expired", session.id),
    onError: ({ error }) => audit("refused", undefined, error.code),
  },
});

With audit appending each call to auditLog, a sign-in, then a request that calls use() twice, updates the session and signs out, records this:

auditLog;
// [
//   ["issued", "0d6ffa5e-…", "-"],           sign-in: no session before
//   ["read", "0d6ffa5e-…"],                  the next request, however often it calls use()
//   ["issued", "8c41e2b7-…", "0d6ffa5e-…"],  update(): a new id, the old one from oldSession
//   ["signed out", "8c41e2b7-…"],            clear()
// ]
  • Read once: the token is read on the first use() of a request, and later calls get that session back, so onRead fires once.
  • Read first: getting the session is a read, so onRead comes before any onUpdate or onClear in the same request.
  • Then rolling: a reissue by rolling runs after onRead, on a cookie session alone, and only when onRead left the session as it found it and did not call roll.skip(). onRead knows beforehand through roll.due.
  • Settled state: every hook runs after the session state is settled. A hook may call use(event) on the same event, such as onExpire opening another session to issue a new one, and gets the same session back without firing onRead again.
  • No update inside onUpdate: updating or clearing a session from its own onUpdate, through use(event), is not supported. The outer update writes its token afterwards, over the inner one.

#Remove the record of a failed update

An update can fail after onUpdate recorded it, such as when the response was sent before its cookie was written. onError then receives the same session, so the record can come out again. Here ledger is your store of issued session ids:

hooks: {
  onUpdate: ({ session }) => ledger.add(session.id),
  onError: async ({ session, trigger }) => {
    if (trigger !== "read") await ledger.remove(session.id);
  },
},
  • Which id is which: session.id is the id of the failed update, the one onUpdate recorded. oldSession.id is the session that is current again, so its record stays.
  • Whether onUpdate ran: session.token is set when it did, and the failure came after it. It is undefined when the token could not be issued or did not fit its cookies, and then onUpdate never ran.
  • The live session: session and oldSession have no update() or clear(). await appSession.use(event) returns the live session inside the hook, and after a failed read its clear() expires the cookie.

#Rotate keys

Give every key a kid and pass them to key as one JWK Set, newest key first. The first key issues every token and writes its kid into the header; every key in the set opens tokens, and the token's kid picks the one to try:

key-rotation.ts
import { type JWKSet, type JWK_oct, defineJWESession, defineJWSSession } from "unjwt/session";

// A JWK Set as JSON, newest key first: { "keys": [{ "kid": "2026-10", … }, { "kid": "2026-09", … }] }
const sealing = process.env.SESSION_KEYS;
if (!sealing) throw new Error("SESSION_KEYS is not set");
const sessionKeys: JWKSet<JWK_oct<"A256KW">[]> = JSON.parse(sealing);

export const appSession = defineJWESession<{ userId: string }, "7D">({
  key: sessionKeys,
  maxAge: "7D",
});
  • Rotating: add the new key at the front of the set and deploy. New tokens carry the new kid; tokens of the older keys still open.
  • Retiring: once maxAge has passed since the deploy, drop the oldest key. A token whose kid names no key in the set fails like a tampered one: onError gets ERR_SESSION_TOKEN_INVALID with ERR_JWK_KEY_NOT_FOUND as cause, and the session is empty.
  • Checked at start-up: each key in the set is checked as a lone key would be. An empty set, or an entry that isn't an oct JWK, a CryptoKey included, makes defining the session throw ERR_SESSION_KEY_INVALID. A pinned algorithm applies to the first key alone, and must be one it serves.
  • Keys without kid: a token without kid is tried against every key of its algorithm and every key without alg, in order. The tokens of a key without kid carry none, so defining the session throws ERR_SESSION_CONFIG_INVALID when they would be tried against more keys than limits.keyCandidates in jwe.decryptOptions or jws.verifyOptions, 8 by default. Give every key a kid and the limit never applies.

#Rotate with onKeyLookup

Some keys can't sit in a set you load at start-up, such as keys you fetch from a secret manager as tokens arrive, so that a key added or removed there takes effect without a restart. onKeyLookup receives the token's protected header and returns the key that opens it, in the shapes key takes: a JWK, a CryptoKey or a JWK Set. key still issues every token:

key-lookup.ts
import { type JWESessionOctJWK, defineJWESession } from "unjwt/session";

// const secrets = your secret manager: get(name) resolves the secret stored under that name

// The kid of the key that issues, set at deploy. Every session key stays in the secret manager under its kid
const currentKid = process.env.SESSION_KEY_ID;
if (!currentKid) throw new Error("SESSION_KEY_ID is not set");
const current = await sessionKey(currentKid);
if (!current) throw new Error(`No session key "${currentKid}" in the secret manager`);

export const appSession = defineJWESession<{ userId: string }, "7D">({
  key: current,
  maxAge: "7D",
  hooks: {
    async onKeyLookup({ header }) {
      return header.kid ? sessionKey(header.kid) : undefined;
    },
  },
});

async function sessionKey(kid: string): Promise<JWESessionOctJWK | undefined> {
  const json = await secrets.get(`session-keys/${kid}`);
  return json ? JSON.parse(json) : undefined;
}

Warning

Return the key that issues tokens too. With onKeyLookup set, what it returns alone opens tokens, so a lookup that misses key refuses every fresh token and signs each visitor out at their next request.

  • A key, a set or undefined: onKeyLookup returns a JWK, a CryptoKey, a JWK Set, or undefined when it has no key for the token. Throw when you can't tell, such as when the secret manager is down.
  • An unknown kid: undefined fails the token like a tampered one, with ERR_JWK_KEY_NOT_FOUND as cause, and a cookie session's cookie is expired.
  • A secret manager that fails: a lookup that throws, whatever it throws, is a read failure. onError gets ERR_SESSION_READ_FAILED with your error as cause, the session is empty for this request, and the cookie is kept, so the visitor is signed in again once the secret manager answers.
  • A key that cannot be used: a key the lookup returns that doesn't fit the token, such as an EC key for an HMAC token or a JWK whose k doesn't decode, is a read failure too, with ERR_JWK_INVALID as cause. The key is yours to fix, so the cookie is kept.
  • A returned set: the token's kid picks its keys, and a token without kid is tried against each key of its algorithm in order, up to limits.keyCandidates. Past that the token is refused, with ERR_JWK_KEY_NOT_FOUND as cause.
  • Algorithms: a token opens only under an algorithm key serves or algorithms lists. With onKeyLookup set, algorithms may list ones that only the keys it returns serve. A token of any other algorithm is the token's failure, ERR_SESSION_TOKEN_INVALID, and its cookie is expired, whatever key the lookup returns.
  • A CryptoKey in a rotation: export it to a JWK with exportJWK and put it in the JWK Set you pass to key, as in Rotate keys, so the session checks it when it is defined.
  • A CryptoKey from your own lookup: nothing checks what onKeyLookup returns when the session is defined, and a CryptoKey names no algorithm, so list the ones it serves in algorithms. Without them its tokens fail with ERR_JWS_ALG_NOT_ALLOWED or ERR_JWE_ALG_NOT_ALLOWED as cause.
  • Lookups and open(): onKeyLookup also runs for open(), which has no request, so event is optional there.
  • Types: unjwt/session exports the hook's type as JWSSessionKeyLookup and JWESessionKeyLookup, to type a lookup you write outside the config.

#Change the algorithm

A signed session with HMAC keys rotates with a set too, and the newest key may use another algorithm, such as HS512 after HS256:

key-rotation.ts
// The same layout for HMAC keys, here while moving from HS256 to HS512: the newest key signs HS512
const signing = process.env.SIGNING_KEYS;
if (!signing) throw new Error("SIGNING_KEYS is not set");
const signingKeys: JWKSet<JWK_oct<"HS256" | "HS512">[]> = JSON.parse(signing);

export const signedSession = defineJWSSession<{ userId: string }, "1h">({
  key: signingKeys,
  maxAge: "1h",
});
  • Each key serves its own alg: the HS512 key signs, and the HS256 keys behind it still verify their tokens, with no algorithms list. Once the last HS256 key is dropped, HS256 tokens are refused.
  • A key without alg: it serves only what its material carries among the algorithms jws.verifyOptions.algorithms or jwe.decryptOptions.algorithms lists, or, for the first key, the pin. Defining the session throws ERR_SESSION_CONFIG_INVALID when neither names one. Keep alg on every key and you need no list.
  • Encrypted sessions: an older A128KW key opens its tokens under a newest A256KW one. The content encryption, enc, needs nothing either: a key-wrapping key opens tokens of every enc, a dir key only its own.

#Rotate a key pair

A key pair rotates through publicKey, which takes a list or a JWK Set. Sign with the new private key, and verify with its public half and the public halves of the keys before it:

key-pair-rotation.ts
import {
  type JWKSet,
  type JWK_EC_Private,
  type JWK_EC_Public,
  defineJWSSession,
  toPublicJWK,
} from "unjwt/session";

// The private ES256 JWK that signs from now on, as JSON
const json = process.env.SESSION_SIGNING_KEY;
if (!json) throw new Error("SESSION_SIGNING_KEY is not set");
const privateKey: JWK_EC_Private<"ES256"> = JSON.parse(json);

// The public halves of the keys that signed before it, as a JWK Set: { "keys": [{ "kid": "2026-09", … }] }
const earlier: JWKSet<JWK_EC_Public<"ES256" | "ES384" | "ES512">[]> = JSON.parse(
  process.env.SESSION_EARLIER_KEYS ?? '{ "keys": [] }',
);

export const signedSession = defineJWSSession<{ userId: string }, "1h">({
  key: { privateKey, publicKey: [toPublicJWK(privateKey), ...earlier.keys] },
  maxAge: "1h",
});
  • The new public half stays in the list: it verifies every token the new key signs. A list or JWK Set with no key that serves the private key's algorithm makes defining the session throw ERR_SESSION_KEY_INVALID; keys of former algorithms may fill the rest of it.
  • Older algorithms: each public JWK in the list serves its own alg, so an earlier ES384 key verifies its tokens without algorithms. A JWK without alg, other than an EC or Ed25519 key whose curve names its algorithm, serves the private key's algorithm when its material carries it; list any other algorithm it verifies in jws.verifyOptions.algorithms. One that serves neither makes defining the session throw ERR_SESSION_CONFIG_INVALID.
  • Retiring: drop a public half from SESSION_EARLIER_KEYS once its last token has expired. Its tokens then fail with ERR_JWK_KEY_NOT_FOUND as cause.

#What a throw does

Hook throwsResult
onReaduse() rejects with your error.
onExpire, onError on a readuse() rejects with your error. The session is already empty, and a cookie session's cookie expired unless the read failed with ERR_SESSION_READ_FAILED.
onUpdateupdate() rejects with your error. Nothing is written, the session is as it was before the call, and onError does not run.
onClearclear() rejects with your error. The session is already empty and a cookie session's cookie expired.
onError after a failed issue or writeupdate() rejects with your error. The session was put back as it was before onError ran, and nothing is written.
a key lookupThe read fails: onError gets ERR_SESSION_READ_FAILED with your error as cause, the session is empty and the cookie is kept. open() throws the same. A JWTError you throw is a read failure too.

A roll fails the same ways as update(), but use() rejects. The session is empty for the rest of the request, and the request's cookie is kept.

A cookie is expired only when its token is dead: it failed the session's checks or expired, onKeyLookup returned undefined for it, or your code called clear(). A key lookup that throws says nothing about the token, and dropping cookies then would sign everyone out when a key store is down, so the cookie stays and the next request tries again. Return undefined for a token you know has no key. To expire the cookie of a read failure yourself, call clear() in onError on the session use(event) returns.

Warning

When onRead throws, use() rejects and the session is left empty for the rest of the request: a later use() in the same request returns that empty session and does not run onRead again. The cookie stays where it is, because a hook that fails says nothing about the token. Let a revocation check that cannot answer end the request with an error instead of catching it and carrying on.

#Going further