
# 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 `JWTError` and `isJWTError` from `unjwt/error`. `unjwt`, `unjwt/jws`, `unjwt/jwe`, `unjwt/jwk` and `unjwt/dpop` export the same two; `unjwt/session` doesn't, so session code imports them from `unjwt/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](/sessions/hooks) and on `session.error`. The type guards return `false`. `verifyMultiAll` reports 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:

<!-- automd:region src="../../examples/safety/handle-errors.ts" -->

```ts [handle-errors.ts]
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}"` },
  });
}
```

<!-- /automd -->

The list is as wide as the input it guards:

- **Token codes**: everything in `TOKEN_CODES` comes from what the client sent: a malformed token, a bad signature, an algorithm you don't allow, a `kid` your 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_EXPIRED` gets its own answer, so a client can refresh its token instead of signing in again.
- **Rethrow the rest**: `ERR_INVALID_OPTION` or `ERR_JWK_INVALID` from 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:

<!-- automd:region src="../../examples/safety/handle-errors.ts" name="fallback" -->

```ts [handle-errors.ts]
/** 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 });
}
```

<!-- /automd -->

## 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:

```ts
import { isJWTError } from "unjwt/error";

if (isJWTError(error, "ERR_JWT_EXPIRED")) {
  error.cause; // { jti?: string; iat?: number; exp?: number }
}
```

- **`ERR_JWT_EXPIRED` carries the token's times**: its `cause` holds the `jti`, `iat` and `exp` read from the token, each `undefined` when the token has none, so you can log which token expired and when.
- **Codes for TypeScript**: `KnownJWTErrorCode` is the closed list this release throws. `JWTErrorCode`, the type of `error.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.
- **`cause` on a JWK Set**: when no key in a set verifies a signature or opens a token, the `ERR_JWS_SIGNATURE_INVALID` or `ERR_JWE_DECRYPTION_FAILED` you get carries an array as `cause`, one `JWTError` per key tried. A key that could not be used at all shows up there as `ERR_JWK_INVALID`.
- **`cause` on a JSON token**: when none of the signatures of a [multi-signature](/jws/multi) token verifies, or none of the recipients of a [multi-recipient](/jwe/multi) one opens, the same two codes carry one `JWTError` per 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 code `verify` or `decrypt` gives for that failure.
- **`cause` elsewhere**: a token segment that isn't canonical base64url gives `ERR_JWS_INVALID` or `ERR_JWE_INVALID` with an `UnsecureError` as `cause`. A key the runtime refused carries the runtime's own error. A key lookup function that threw gives `ERR_JWK_KEY_NOT_FOUND` with your error as `cause`, unless it threw a `JWTError`, which reaches you as it is. A session token that failed to open gives `ERR_SESSION_TOKEN_INVALID` with the `verify` or `decrypt` error as `cause`. A session's `onKeyLookup` that threw gives `ERR_SESSION_READ_FAILED` with what it threw as `cause`, and one that returned a key that cannot be used the same code with an `ERR_JWK_INVALID` as `cause`.

### 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](/safety/utils) 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](/safety/claims) describes the options behind them.

| Code                                                            | When                                                                                                                                                                                                                                                                 | What to do                                                                  |
| --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| <span id="err_jwt_expired"></span>`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.                          |
| <span id="err_jwt_nbf"></span>`ERR_JWT_NBF`                     | `nbf` is still in the future.                                                                                                                                                                                                                                        | Reject it. If the issuer's clock runs ahead of yours, set `clockTolerance`. |
| <span id="err_jwt_claim_invalid"></span>`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.     |
| <span id="err_jwt_claim_missing"></span>`ERR_JWT_CLAIM_MISSING` | A claim that `issuer`, `audience`, `subject`, `maxTokenAge` or `requiredClaims` asks for isn't there.                                                                                                                                                                | Reject the token.                                                           |

### JWS

From [`sign`](/jws/sign), [`verify`](/jws/verify) and the [multi-signature](/jws/multi) functions.

| Code                                                                                      | When                                                                                                                                                                                                                                                                                   | What to do                                                                            |
| ----------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| <span id="err_jws_invalid"></span>`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.                                                             |
| <span id="err_jws_invalid_serialization"></span>`ERR_JWS_INVALID_SERIALIZATION`           | A JSON JWS that is neither the General nor the Flattened shape.                                                                                                                                                                                                                        | Reject it.                                                                            |
| <span id="err_jws_signature_invalid"></span>`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.          |
| <span id="err_jws_alg_not_allowed"></span>`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`. |
| <span id="err_jws_alg_missing"></span>`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`.                                                                           |
| <span id="err_jws_signer_alg_inference"></span>`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.                                                             |
| <span id="err_jws_no_matching_signer"></span>`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.                                        |
| <span id="err_jws_header_params_not_disjoint"></span>`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.                 |
| <span id="err_jws_b64_inconsistent"></span>`ERR_JWS_B64_INCONSISTENT`                     | Signers disagree on `b64` ([RFC 7797 §3](https://www.rfc-editor.org/rfc/rfc7797#section-3)).                                                                                                                                                                                           | Give every signer the same `b64`.                                                     |

### JWE

From [`encrypt`](/jwe/encrypt), [`decrypt`](/jwe/decrypt) and the [multi-recipient](/jwe/multi) functions.

| Code                                                                                      | When                                                                                                                                                                                                                                                                                                 | What to do                                                                            |
| ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| <span id="err_jwe_invalid"></span>`ERR_JWE_INVALID`                                       | The token or a header is malformed, `enc` is unsupported, a `crit` rule fails, or a [limit](/safety/limits) 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.                                                             |
| <span id="err_jwe_invalid_serialization"></span>`ERR_JWE_INVALID_SERIALIZATION`           | A JSON JWE that is neither the General nor the Flattened shape.                                                                                                                                                                                                                                      | Reject it.                                                                            |
| <span id="err_jwe_decryption_failed"></span>`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](https://www.rfc-editor.org/rfc/rfc7516#section-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.                                |
| <span id="err_jwe_alg_not_allowed"></span>`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. |
| <span id="err_jwe_alg_missing"></span>`ERR_JWE_ALG_MISSING`                               | `encrypt` can't tell which key management algorithm to use.                                                                                                                                                                                                                                          | Pass `alg`.                                                                           |
| <span id="err_jwe_enc_missing"></span>`ERR_JWE_ENC_MISSING`                               | `alg: "dir"` without an `enc`, and the key names none.                                                                                                                                                                                                                                               | Pass `enc`.                                                                           |
| <span id="err_jwe_alg_forbidden_in_multi"></span>`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.                             |
| <span id="err_jwe_recipient_alg_inference"></span>`ERR_JWE_RECIPIENT_ALG_INFERENCE`       | A recipient key given to `encryptMulti` isn't a JWK, or has no `alg`.                                                                                                                                                                                                                                | Set `alg` on that recipient.                                                          |
| <span id="err_jwe_no_matching_recipient"></span>`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.                                        |
| <span id="err_jwe_header_params_not_disjoint"></span>`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](/jwk) and every call that takes a key.

| Code                                                            | When                                                                                                                                                                                                                                                                  | What to do                                                                                                      |
| --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| <span id="err_jwk_invalid"></span>`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.                                                                                   |
| <span id="err_jwk_key_not_found"></span>`ERR_JWK_KEY_NOT_FOUND` | No key in a [JWK Set](/jwk/sets) 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. |
| <span id="err_jwk_unsupported"></span>`ERR_JWK_UNSUPPORTED`     | An algorithm, curve or PEM format unjwt doesn't implement.                                                                                                                                                                                                            | Pick a supported one: see [Generate keys](/jwk/generate).                                                       |

### Options

| Code                                                      | When                                                                                                                                                                                                                                                                                                                                                                                                   | What to do                                                                  |
| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------- |
| <span id="err_invalid_option"></span>`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`](/sessions), 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](/sessions/use#tell-what-happened-to-the-token) answers each.

| Code                                                                      | When                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | What to do                                                                                                                                            |
| ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| <span id="err_session_invalid"></span>`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 }`. |
| <span id="err_session_token_invalid"></span>`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.                                                                                                                      |
| <span id="err_session_read_failed"></span>`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.                                       |
| <span id="err_session_readonly_event"></span>`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](/sessions/use).                           |
| <span id="err_session_key_invalid"></span>`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](/sessions/configure).                                                                                          |
| <span id="err_session_config_invalid"></span>`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](/sessions/configure).                                                                                       |

A session past its `maxAge` reports `ERR_JWT_EXPIRED`, from the claims family above.

### DPoP

From [`verifyDPoPProof`](/dpop). The last column names the error RFC 9449 has you send back.

| Code                                                              | When                                                                                                             | What to do                                                                                             |
| ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| <span id="err_dpop_invalid"></span>`ERR_DPOP_INVALID`             | The proof's form, header, embedded key, algorithm or signature is rejected. `cause` holds the core error.        | Answer `invalid_dpop_proof`.                                                                           |
| <span id="err_dpop_claim_invalid"></span>`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`.                                                                           |
| <span id="err_dpop_nonce_invalid"></span>`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.                                              |
| <span id="err_dpop_replay"></span>`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 JWTError` and `isJWTError`. Code that has to work across copies can check `error.name === "JWTError"` and then read `code`.
- **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.
