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
hooksof the config you pass todefineJWSSessionordefineJWESession, described in Configure a session. - Every hook receives one object with
config, the session's config, andevent, what you passed touse().configis 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 aTypeError. - A hook that throws makes the call that ran it reject. What a throw does lists each case.
#When each hook fires
| Hook | Fires | Receives | Can change the outcome |
|---|---|---|---|
onRead | Once per request, when a valid token is read. | session (the live session), roll | Yes: session.clear() or session.update() in the hook, and roll.skip() holds back a due roll. |
onUpdate | After update() or rolling issued a token, before anything is written. | session (a copy of the new session), oldSession, trigger | Yes: a throw cancels the update. |
onClear | After clear() emptied the session and, on a cookie session, expired the cookie. | oldSession (undefined without a session or a failed read) | No. |
onExpire | When 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), error | No, the session is already empty. |
onError | When 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, error | No. |
onKeyLookup | Before 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,onExpireandonError.onErroralso runs later in the request when anupdate()or a roll fails to issue or write its token. oldSession: a copy of the session before the change, with itsid,createdAt,expiresAt,data,token,sourceanderror, the error its read ended with. On a first sign-in itsidisundefined. After a failed readonClearreceives one too, with thaterror.onErrorreceives the session that is current again after a failed update or roll, andundefinedafter a failed read. ThesessionofonUpdateand ofonErroris 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: everysessionandoldSessiona hook receives carriessource,"cookie","header"or"token", the place this request's token came from. Read, update and clear says whatupdate()andclear()reach for each.trigger: inonUpdate,"update"for a call toupdate(),"rolling"for a reissue byrolling. InonError, the operation that failed:"read"for the request's token,"update"or"rolling"for an update that could not issue or write its token.oldSessionisundefinedon a read, so checktriggerfirst: TypeScript then narrowsoldSessionto a session.- Stop or log: a throw in
onUpdatecancels 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.dueistruewhenrollingreissues this session right afteronRead: a session read from its cookie, withrolling: trueor 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 whendueisfalse.update()andclear()in the hook act the same whether or not it was called. Refresh data when the session rolls usesdue, and Keep the session when the data cannot be fetched usesskip().onExpireerror: anERR_JWT_EXPIREDJWTError, the same objectsession.errorholds afterwards. Only a token that is otherwise a valid session reachesonExpire; an expired token with a bad signature or another type goes toonError.onErrorerror on a read: aJWTErrorwhosecodesays whether the token is dead, the same objectsession.errorholds afterwards, so a handler can answer it too.ERR_SESSION_TOKEN_INVALIDmeans the token failed the session's checks, itscausethe reason, such asERR_JWS_SIGNATURE_INVALID, and a cookie session's cookie is expired.ERR_SESSION_READ_FAILEDmeansonKeyLookupcould not answer, itscausewhat failed, and the cookie is kept. Either way the session is empty for this request.onErrorerror on anupdate(): whatever issuing or writing the token threw, such asERR_SESSION_INVALIDfor a token too long for its cookies, which fails beforeonUpdateruns, orERR_SESSION_READONLY_EVENTfor a response sent whileonUpdateran.- Not hooks: a configured
keythe session cannot use is a configuration error and reaches no hook. Defining the session throwsERR_SESSION_KEY_INVALID, or, for a key of the right kind that doesn't import, the firstuse()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:
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 newidandcreatedAt, so neither identifies a sign-in.signedInAtis 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:
rollingkeeps 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()inonRead, 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 inx-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:
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:
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()inonReadissues the one token of the read, andonUpdateruns once withtrigger: "update". When the hook leaves the session alone,rollingreissues it with the same data, andonUpdategetstrigger: "rolling". - Where
roll.dueisfalse: a token younger thanrolling, 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 anupdate()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.
awaitthe update: anupdate()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:
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
onUpdatedoes 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.
awaitthe 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 letsrollingreissue it with its current data, for a newrollingperiod. - 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:
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, soonReadfires once. - Read first: getting the session is a read, so
onReadcomes before anyonUpdateoronClearin the same request. - Then rolling: a reissue by
rollingruns afteronRead, on a cookie session alone, and only whenonReadleft the session as it found it and did not callroll.skip().onReadknows beforehand throughroll.due. - Settled state: every hook runs after the session state is settled. A hook may call
use(event)on the same event, such asonExpireopening another session to issue a new one, and gets the same session back without firingonReadagain. - No update inside
onUpdate: updating or clearing a session from its ownonUpdate, throughuse(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.idis the id of the failed update, the oneonUpdaterecorded.oldSession.idis the session that is current again, so its record stays. - Whether
onUpdateran:session.tokenis set when it did, and the failure came after it. It isundefinedwhen the token could not be issued or did not fit its cookies, and thenonUpdatenever ran. - The live session:
sessionandoldSessionhave noupdate()orclear().await appSession.use(event)returns the live session inside the hook, and after a failed read itsclear()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:
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
maxAgehas passed since the deploy, drop the oldest key. A token whosekidnames no key in the set fails like a tampered one:onErrorgetsERR_SESSION_TOKEN_INVALIDwithERR_JWK_KEY_NOT_FOUNDascause, and the session is empty. - Checked at start-up: each key in the set is checked as a lone
keywould be. An empty set, or an entry that isn't anoctJWK, aCryptoKeyincluded, makes defining the session throwERR_SESSION_KEY_INVALID. A pinned algorithm applies to the first key alone, and must be one it serves. - Keys without
kid: a token withoutkidis tried against every key of its algorithm and every key withoutalg, in order. The tokens of a key withoutkidcarry none, so defining the session throwsERR_SESSION_CONFIG_INVALIDwhen they would be tried against more keys thanlimits.keyCandidatesinjwe.decryptOptionsorjws.verifyOptions, 8 by default. Give every key akidand 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:
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:onKeyLookupreturns a JWK, aCryptoKey, a JWK Set, orundefinedwhen it has no key for the token. Throw when you can't tell, such as when the secret manager is down. - An unknown
kid:undefinedfails the token like a tampered one, withERR_JWK_KEY_NOT_FOUNDascause, and a cookie session's cookie is expired. - A secret manager that fails: a lookup that throws, whatever it throws, is a read failure.
onErrorgetsERR_SESSION_READ_FAILEDwith your error ascause, 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
kdoesn't decode, is a read failure too, withERR_JWK_INVALIDascause. The key is yours to fix, so the cookie is kept. - A returned set: the token's
kidpicks its keys, and a token withoutkidis tried against each key of its algorithm in order, up tolimits.keyCandidates. Past that the token is refused, withERR_JWK_KEY_NOT_FOUNDascause. - Algorithms: a token opens only under an algorithm
keyserves oralgorithmslists. WithonKeyLookupset,algorithmsmay 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
CryptoKeyin a rotation: export it to a JWK withexportJWKand put it in the JWK Set you pass tokey, as in Rotate keys, so the session checks it when it is defined. - A
CryptoKeyfrom your own lookup: nothing checks whatonKeyLookupreturns when the session is defined, and aCryptoKeynames no algorithm, so list the ones it serves inalgorithms. Without them its tokens fail withERR_JWS_ALG_NOT_ALLOWEDorERR_JWE_ALG_NOT_ALLOWEDascause. - Lookups and
open():onKeyLookupalso runs foropen(), which has no request, soeventis optional there. - Types:
unjwt/sessionexports the hook's type asJWSSessionKeyLookupandJWESessionKeyLookup, 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:
// 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 noalgorithmslist. Once the last HS256 key is dropped, HS256 tokens are refused. - A key without
alg: it serves only what its material carries among the algorithmsjws.verifyOptions.algorithmsorjwe.decryptOptions.algorithmslists, or, for the first key, the pin. Defining the session throwsERR_SESSION_CONFIG_INVALIDwhen neither names one. Keepalgon every key and you need no list. - Encrypted sessions: an older
A128KWkey opens its tokens under a newestA256KWone. The content encryption,enc, needs nothing either: a key-wrapping key opens tokens of everyenc, adirkey 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:
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 withoutalgorithms. A JWK withoutalg, 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 injws.verifyOptions.algorithms. One that serves neither makes defining the session throwERR_SESSION_CONFIG_INVALID. - Retiring: drop a public half from
SESSION_EARLIER_KEYSonce its last token has expired. Its tokens then fail withERR_JWK_KEY_NOT_FOUNDascause.
#What a throw does
| Hook throws | Result |
|---|---|
onRead | use() rejects with your error. |
onExpire, onError on a read | use() 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. |
onUpdate | update() rejects with your error. Nothing is written, the session is as it was before the call, and onError does not run. |
onClear | clear() rejects with your error. The session is already empty and a cookie session's cookie expired. |
onError after a failed issue or write | update() rejects with your error. The session was put back as it was before onError ran, and nothing is written. |
| a key lookup | The 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
- Settings the hooks depend on:
maxAgeandrollingin Configure a session. - Errors by code: Handle errors.
- Key sets in general: Use a JWK Set.