Handle errors
Catch the one error class unjwt throws, tell a bad token from a bug on your side by its code, and answer each with the right response.
When a token, a key, a session or an option is wrong, unjwt throws a JWTError. Its code is a short label, like ERR_JWT_EXPIRED, that says what kind of thing went wrong, and that's what your code branches on. The message is written for whoever reads the logs, and its wording can change in any release. When the failure started somewhere else, cause holds what failed underneath.
#Before you start
- Import
JWTErrorandisJWTErrorfromunjwt/error.unjwt,unjwt/jws,unjwt/jwe,unjwt/jwkandunjwt/dpopexport the same two;unjwt/sessiondoesn't, so session code imports them fromunjwt/error. - Some calls answer bad input without throwing. A session read with a bad or expired token gives you an empty session and reports the error to its hooks and on
session.error. The type guards returnfalse.verifyMultiAllreports each signature's error next to it. - Who caused an error depends on where the value came from, not on the code alone. A token from a request that fails to verify is the client's problem; an option your code passes that throws is yours.
#Catch what a token can cause
Put the try around the call that reads the token, answer the codes a token can cause by itself, and rethrow everything else:
import { isJWTError, type KnownJWTErrorCode } from "unjwt/error";
import type { JWKSet } from "unjwt/jwk";
import { verify } from "unjwt/jws";
/** Codes a bearer token can cause by itself: the client gets a 401, and nothing is logged as a bug. */
const TOKEN_CODES: ReadonlySet<string> = new Set([
"ERR_JWS_INVALID",
"ERR_JWS_SIGNATURE_INVALID",
"ERR_JWS_ALG_NOT_ALLOWED",
"ERR_JWK_KEY_NOT_FOUND",
"ERR_JWT_NBF",
"ERR_JWT_CLAIM_INVALID",
"ERR_JWT_CLAIM_MISSING",
] satisfies KnownJWTErrorCode[]);
/** `GET /account`, for a request that carries `Authorization: Bearer <token>`. */
export function accountHandler(keys: JWKSet): (request: Request) => Promise<Response> {
return async (request) => {
const header = request.headers.get("authorization") ?? "";
const token = header.startsWith("Bearer ") ? header.slice(7) : "";
if (!token) return unauthorized("invalid_request", "A bearer token is required.");
try {
const { payload } = await verify(token, keys, {
algorithms: ["ES256"],
issuer: "https://auth.example.com",
audience: "https://api.example.com",
});
return Response.json({ sub: payload.sub });
} catch (error) {
if (isJWTError(error, "ERR_JWT_EXPIRED")) {
return unauthorized("invalid_token", "The token expired.");
}
if (isJWTError(error) && TOKEN_CODES.has(error.code)) {
return unauthorized("invalid_token", "The token is not valid.");
}
// Anything else, such as ERR_INVALID_OPTION, is a bug on the server,
// so it goes on to the fallback handler.
throw error;
}
};
}
function unauthorized(code: string, description: string): Response {
return new Response(null, {
status: 401,
headers: { "www-authenticate": `Bearer error="${code}", error_description="${description}"` },
});
}The list is as wide as the input it guards:
- Token codes: everything in
TOKEN_CODEScomes from what the client sent: a malformed token, a bad signature, an algorithm you don't allow, akidyour key set doesn't hold, or a claim that doesn't match. The client gets a 401 and nothing lands in your error log. - Expired apart:
ERR_JWT_EXPIREDgets its own answer, so a client can refresh its token instead of signing in again. - Rethrow the rest:
ERR_INVALID_OPTIONorERR_JWK_INVALIDfrom this call means your options or your keys are wrong. Turn them into a 401 and every request fails quietly while the bug hides. - Typed list:
satisfies KnownJWTErrorCode[]makes a misspelled code a type error instead of a check that never matches.
#Answer everything else
An error no route handled came from your code, your configuration or the runtime, so one fallback handler logs it, cause included, and answers with a 500:
/** The last stop for an error no route handled. */
export function errorResponse(error: unknown, log: (entry: object) => void) {
if (isJWTError(error)) {
// `cause` holds what failed underneath: the runtime's error, or one
// error per key a JWK Set tried.
log({ code: error.code, message: error.message, cause: error.cause });
} else {
log({ error });
}
return Response.json({ error: "Internal error." }, { status: 500 });
}#Read an error
isJWTError(error) tells you the value is a JWTError. isJWTError(error, "ERR_JWT_EXPIRED") also checks the code and narrows its type, and the code argument only accepts codes unjwt knows, so a typo fails to compile:
import { isJWTError } from "unjwt/error";
if (isJWTError(error, "ERR_JWT_EXPIRED")) {
error.cause; // { jti?: string; iat?: number; exp?: number }
}ERR_JWT_EXPIREDcarries the token's times: itscauseholds thejti,iatandexpread from the token, eachundefinedwhen the token has none, so you can log which token expired and when.- Codes for TypeScript:
KnownJWTErrorCodeis the closed list this release throws.JWTErrorCode, the type oferror.code, also admits any other string, so a later release can add a code without breaking your types. Keep a fallback branch for codes you don't handle. causeon a JWK Set: when no key in a set verifies a signature or opens a token, theERR_JWS_SIGNATURE_INVALIDorERR_JWE_DECRYPTION_FAILEDyou get carries an array ascause, oneJWTErrorper key tried. A key that could not be used at all shows up there asERR_JWK_INVALID.causeon a JSON token: when none of the signatures of a multi-signature token verifies, or none of the recipients of a multi-recipient one opens, the same two codes carry oneJWTErrorper signature or recipient, in order, so each entry tells why it failed. A JSON token with a single signature or recipient throws that entry's own error instead, the same codeverifyordecryptgives for that failure.causeelsewhere: a token segment that isn't canonical base64url givesERR_JWS_INVALIDorERR_JWE_INVALIDwith anUnsecureErrorascause. A key the runtime refused carries the runtime's own error. A key lookup function that threw givesERR_JWK_KEY_NOT_FOUNDwith your error ascause, unless it threw aJWTError, which reaches you as it is. A session token that failed to open givesERR_SESSION_TOKEN_INVALIDwith theverifyordecrypterror ascause. A session'sonKeyLookupthat threw givesERR_SESSION_READ_FAILEDwith what it threw ascause, and one that returned a key that cannot be used the same code with anERR_JWK_INVALIDascause.
#The second error class
The base64url and base64 functions, secureRandomBytes and the JSON sanitizers in unjwt/utils throw an UnsecureError instead, with codes such as MALFORMED (text that isn't the canonical encoding), INVALID_TYPE (a value of the wrong type) and OUT_OF_RANGE (a length out of bounds). Check it with isUnsecureError(error, "MALFORMED"), exported from unjwt/error, unjwt/utils and unjwt. An UnsecureError class from any other package is a different class, and instanceof against it never matches what unjwt throws. Utilities shows one in use.
#Every code
Each table lists a family of codes, when each one fires, and what usually fixes it. Codes in the JWT, JWS and JWE families that come from an incoming token are the client's to fix: answer them with a 401.
#JWT claims
The claim checks run in verify, decrypt, the multi variants, validateJwtClaims and a session's open(). Validate claims describes the options behind them.
| Code | When | What to do |
|---|---|---|
ERR_JWT_EXPIRED | exp has passed, the token is older than maxTokenAge, or a session is past its maxAge. cause holds { jti, iat, exp }. | Let the client refresh its token or sign in again. |
ERR_JWT_NBF | nbf is still in the future. | Reject it. If the issuer's clock runs ahead of yours, set clockTolerance. |
ERR_JWT_CLAIM_INVALID | iss, sub or aud doesn't match, exp, nbf or iat isn't a non-negative number, or iat is in the future under maxTokenAge. When signing: both expiresIn and expiresAt, both notBeforeIn and notBeforeAt, or a cnf.jwk that isn't a public key. | Reject an incoming token. When signing, fix the options or the payload. |
ERR_JWT_CLAIM_MISSING | A claim that issuer, audience, subject, maxTokenAge or requiredClaims asks for isn't there. | Reject the token. |
#JWS
From sign, verify and the multi-signature functions.
| Code | When | What to do |
|---|---|---|
ERR_JWS_INVALID | The token is malformed: not three parts, a segment that isn't canonical base64url, a header that isn't a JSON object, a typ that doesn't match, a crit parameter you didn't recognize, a payload that doesn't fit the payload mode, or more signatures than limits.signatures. | Reject an incoming token. |
ERR_JWS_INVALID_SERIALIZATION | A JSON JWS that is neither the General nor the Flattened shape. | Reject it. |
ERR_JWS_SIGNATURE_INVALID | The signature doesn't verify under the key, or under any key of a JWK Set (cause lists each try), or none of two or more signatures of a JSON JWS verifies (cause lists each signature). | Reject the token. If every token fails, check you verify with the right key. |
ERR_JWS_ALG_NOT_ALLOWED | The token's alg is none, unknown or outside algorithms, or no allowlist can be inferred from the key. | Reject an incoming token. For a raw secret or a key without alg, pass algorithms. |
ERR_JWS_ALG_MISSING | sign can't tell which algorithm to use: none was passed, and the key names none, such as a CryptoKey, raw bytes, or an RSA or oct JWK without alg. | Pass alg. |
ERR_JWS_SIGNER_ALG_INFERENCE | A signer given to signMulti has no usable alg, such as an RSA or oct JWK without alg. | Set alg on that signer. |
ERR_JWS_NO_MATCHING_SIGNER | strictSignerMatch found no signature the key could have made. In the cause of an ERR_JWS_SIGNATURE_INVALID, a signature it skipped. | Reject the token, or check which key you pass. |
ERR_JWS_HEADER_PARAMS_NOT_DISJOINT | One name sits in both the protected and the unprotected header of a signature. | Reject an incoming token; when signing, keep each name in one header. |
ERR_JWS_B64_INCONSISTENT | Signers disagree on b64 (RFC 7797 §3). | Give every signer the same b64. |
#JWE
From encrypt, decrypt and the multi-recipient functions.
| Code | When | What to do |
|---|---|---|
ERR_JWE_INVALID | The token or a header is malformed, enc is unsupported, a crit rule fails, or a limit is exceeded: too many recipients, a password-based token whose iteration count is out of bounds or past the call's budget, apu/apv longer than 1024 bytes. | Reject an incoming token. |
ERR_JWE_INVALID_SERIALIZATION | A JSON JWE that is neither the General nor the Flattened shape. | Reject it. |
ERR_JWE_DECRYPTION_FAILED | The key didn't unwrap or the content didn't decrypt. One code for every cause, so a token can't probe which step failed (RFC 7516 §11.5). Over a JWK Set, cause lists each try; for a JSON JWE with two or more recipients, each recipient. | Reject the token. If every token fails, check the key. |
ERR_JWE_ALG_NOT_ALLOWED | alg or enc is unknown or outside algorithms / encryptionAlgorithms. | Reject an incoming token; widen the allowlist only for algorithms you mean to accept. |
ERR_JWE_ALG_MISSING | encrypt can't tell which key management algorithm to use. | Pass alg. |
ERR_JWE_ENC_MISSING | alg: "dir" without an enc, and the key names none. | Pass enc. |
ERR_JWE_ALG_FORBIDDEN_IN_MULTI | dir or bare ECDH-ES given to encryptMulti: both allow only one recipient. | Use encrypt, or a key wrapping algorithm per recipient. |
ERR_JWE_RECIPIENT_ALG_INFERENCE | A recipient key given to encryptMulti isn't a JWK, or has no alg. | Set alg on that recipient. |
ERR_JWE_NO_MATCHING_RECIPIENT | strictRecipientMatch found no recipient the key could open. In the cause of an ERR_JWE_DECRYPTION_FAILED, a recipient it skipped. | Reject the token, or check which key you pass. |
ERR_JWE_HEADER_PARAMS_NOT_DISJOINT | One name sits in more than one header. | Reject an incoming token; when encrypting, keep each name in one header. |
#JWK
From the key functions and every call that takes a key.
| Code | When | What to do |
|---|---|---|
ERR_JWK_INVALID | No key was passed, or key material is malformed, doesn't fit the algorithm, or is the wrong half: a private key where a public one is expected, a string where a key is expected, an oct key imported for ES256, two keys on different curves in a key agreement. | Fix the key you load or pass. |
ERR_JWK_KEY_NOT_FOUND | No key in a JWK Set matches the token's kid, more keys match than limits.keyCandidates, the call spent limits.keyAttempts, a key lookup function returned undefined, or it threw an error that is not a JWTError. | Without a cause, reject the token. With a cause, your lookup function failed: log it and answer with a 5xx. |
ERR_JWK_UNSUPPORTED | An algorithm, curve or PEM format unjwt doesn't implement. | Pick a supported one: see Generate keys. |
#Options
| Code | When | What to do |
|---|---|---|
ERR_INVALID_OPTION | An option is malformed or out of range: an empty audience, a duration like "7d", a limit that isn't a positive integer, a header that isn't a plain object. An option the call can't honour: validateClaims: true or a claim option such as audience with a non-JSON payload, a claim option with validateClaims: false, a time option such as expiresIn with a string or bytes payload. | Fix the call. It's never the client's fault, so never answer it with a 4xx. |
#Sessions
From unjwt/session, whatever driver it runs on. A read that ends with ERR_JWT_EXPIRED, ERR_SESSION_TOKEN_INVALID or ERR_SESSION_READ_FAILED leaves that error on session.error, the same object its hook received: Tell what happened to the token answers each.
| Code | When | What to do |
|---|---|---|
ERR_SESSION_INVALID | A session token needs more than 16 cookie chunks: update() throws it, use() when a roll issues the token, and the transport's assertFits and write. Or use() got an event it can't read: neither a request nor { token }, a request event with neither req nor headers, or a req that isn't a Web Request. | Keep session data small. Pass use() an event its driver accepts: for the Web driver, a Web Request, { req, res }, { headers } or { token }. |
ERR_SESSION_TOKEN_INVALID | An incoming session token failed the session's checks: it doesn't verify or decrypt, its typ or claims are wrong, its algorithm is one the session doesn't accept, or onKeyLookup returned undefined for it. A read hands it to onError, gives you an empty session and expires a cookie session's cookie; open() throws it. cause is the token error. | Treat the visitor as signed out. |
ERR_SESSION_READ_FAILED | onKeyLookup threw, a JWTError or not, or returned a key that cannot be used for the token. cause is what the lookup threw, or the ERR_JWK_INVALID of its key. The token may be good: a read hands it to onError, gives you an empty session for this request and keeps the cookie; open() throws it. With a lookup set, a problem with the key it returns is yours and lands here, while a token whose algorithm the session doesn't accept is still ERR_SESSION_TOKEN_INVALID. | Your lookup or its key store failed: log it and fix the lookup. The visitor is signed in again once it answers. |
ERR_SESSION_READONLY_EVENT | update() on a cookie session whose event can't take a cookie, such as a request without a response, also when the session header holds the same token as the cookie; or update() / clear() on a cookie session once the response was sent. | Pass the response headers to use(), and update before the response goes out: see Read, update and clear. |
ERR_SESSION_KEY_INVALID | The session key is missing, a password string, the wrong kind of key, an empty JWK Set or one holding a key of the wrong kind, can't serve the pinned algorithm or, for a key pair half that names none, the one its other half names, is a key pair whose publicKey can't verify the algorithm it issues with, or doesn't import. All but the last throw when the session is defined; a key that doesn't import throws from the first use(), issue() or open(). | Fix the key: see Configure a session. |
ERR_SESSION_CONFIG_INVALID | A config that can't work: a bad cookie name or session header, rolling without a shorter maxAge, a key that names no algorithm, or a key pair neither half of which names one, with no pin, an algorithms list that is empty or names one no key serves, or a JWK Set key without kid whose tokens would be tried against more keys than limits.keyCandidates, all thrown when the session is defined; no token source, or two sessions sharing one name on a request, thrown by the call that meets them. | Fix the config: see Configure a session. |
A session past its maxAge reports ERR_JWT_EXPIRED, from the claims family above.
#DPoP
From verifyDPoPProof. The last column names the error RFC 9449 has you send back.
| Code | When | What to do |
|---|---|---|
ERR_DPOP_INVALID | The proof's form, header, embedded key, algorithm or signature is rejected. cause holds the core error. | Answer invalid_dpop_proof. |
ERR_DPOP_CLAIM_INVALID | A proof claim fails: method or URL, age, exp/nbf, the access token hash or key binding, a malformed nonce. | Answer invalid_dpop_proof. |
ERR_DPOP_NONCE_INVALID | The proof is valid but carries no nonce, or a different one from the one you expect. | Answer use_dpop_nonce with a fresh DPoP-Nonce header. |
ERR_DPOP_REPLAY | Your replay callback returned anything but true, or threw (then cause holds what it threw). | Without a cause, answer invalid_dpop_proof. With one, your replay store failed: answer with a 5xx. |
#Going further
- Two copies of unjwt: if another dependency installed its own copy, errors from that copy fail
instanceof JWTErrorandisJWTError. Code that has to work across copies can checkerror.name === "JWTError"and then readcode. - Libraries built on unjwt: throw
new JWTError(message, code, cause)with one of these codes, so your callers deal with one class and one set of codes.