Verify a token
Check a compact JWS against a key, a JWK Set or a lookup function, then validate its header and claims and get the payload back.
verify(token, key, options) answers three questions before it hands you the claims: was this signed by a key you trust, with an algorithm you accept, and are the claims current and meant for you? Any "no" throws a JWTError with a code, so a bad token never reaches your handler looking like a good one. The token's header names its own algorithm and key, and whoever made the token wrote that header, so verify decides what to accept from your options and your key, never from the header alone.
#Before you start
- The verification key: the public half of the issuer's key pair, the issuer's JWK Set, or the shared secret for
HS*tokens. A private JWK is refused here, so a signing key can't end up in a verifier by accident. - What you expect: the issuer (
iss), your own audience (aud), and the token type (typ) when one key signs several kinds of token. verifychecksaudonly when you passaudience, and a token withoutexpnever expires unless you require it. Set both on every verifier.
#Verify a bearer token
A service reads the token from the Authorization header and checks it against the issuer's JWK Set:
import { verify } from "unjwt/jws";
import type { JWKSet } from "unjwt/jwk";
import { isJWTError } from "unjwt/error";
import { isJWKSet } from "unjwt/utils";
const raw = process.env.ISSUER_JWKS;
if (!raw) throw new Error("ISSUER_JWKS is not set");
const issuerKeys: JWKSet = JSON.parse(raw);
if (!isJWKSet(issuerKeys)) throw new Error("ISSUER_JWKS must be a JWK Set");
export interface AccessClaims {
sub: string;
scope: string;
}
/** The caller's claims from `Authorization: Bearer …`, or `null` when the token is missing or refused. */
export async function authenticate(request: Request) {
const header = request.headers.get("authorization");
if (!header?.startsWith("Bearer ")) return null;
try {
const { payload } = await verify<AccessClaims>(header.slice(7), issuerKeys, {
algorithms: ["ES256"],
issuer: "https://auth.example.com",
audience: "https://api.example.com",
typ: "at+jwt",
requiredClaims: ["sub", "exp"],
});
return payload;
} catch (error) {
if (isJWTError(error)) return null;
throw error;
}
}- A JWK Set: the token's
kidpicks the key, so the issuer can rotate keys and publish old and new ones side by side. Akidthe set doesn't hold is refused before any signature check. algorithms: ["ES256"]: the only algorithm this service accepts, whatever the header says.issuer,audience,typ: a token from another issuer, for another API, or of another kind is refused.requiredClaims: ["sub", "exp"]: a token without an expiry or a subject is refused instead of living forever.nullon failure: every refusal is aJWTError, so one check turns them all into a 401. Anything else is a bug in your code and keeps propagating.
#Pass the key
| Key | When to use it |
|---|---|
| A public JWK | One issuer, one key pair. |
An oct JWK or raw bytes | HS* tokens you signed with the same secret. Bytes declare no algorithm: pass algorithms. |
A CryptoKey | A key you already imported. The allowed algorithm comes from its type, hash and curve. |
A JWK Set ({ keys: [...] }) | Several keys, rotation, a published jwks_uri. See Use a JWK Set. |
A lookup function ({ header, token }) => key | Keys that live in a database or a key store. It receives the token's protected header and the token, and may return any of the above, a JWK Set included. |
With a JWK Set, the header's kid narrows the candidates to the matching entry. A token without kid is tried against every entry whose alg, use and key_ops fit, up to limits.keyCandidates (8 by default); more candidates than that throws ERR_JWK_KEY_NOT_FOUND before any signature check. A lookup function returns the key, a JWK Set, or undefined when it has none for the token, which throws ERR_JWK_KEY_NOT_FOUND. Throw when the lookup can't answer, such as when your key store is down: a JWTError it throws reaches you as it is, and any other error is ERR_JWK_KEY_NOT_FOUND, with your error as cause. A string is never a key, and verify without a key throws ERR_JWK_INVALID.
await verify(token, { keys: [previous.publicKey, current.publicKey] }); // picks the entry by kid
await verify(token, { keys: [previous.publicKey] });
// JWTError ERR_JWK_KEY_NOT_FOUND: No key found in JWK Set with kid "2026-10".#Restrict the algorithms
verify settles which alg it accepts before touching the key:
algorithms, the header's alg must be in the list. The list is exact: ["Ed25519"] doesn't admit a token whose header says EdDSA.alg accepts that algorithm only (EdDSA and Ed25519 count as one).CryptoKey's algorithm and hash, every entry of a JWK Set. Raw bytes, and RSA or oct JWKs without alg, declare nothing: verify refuses rather than guess, with ERR_JWS_ALG_NOT_ALLOWED ("Cannot infer allowed algorithms from this key, pass "algorithms"").await verify(hsToken, secretBytes);
// JWTError ERR_JWS_ALG_NOT_ALLOWED: Cannot infer allowed algorithms from this key, pass "algorithms".
await verify(hsToken, secretBytes, { algorithms: ["HS256"] }); // okPass algorithms whenever you know what your issuer uses. It costs one line and survives a key that loses its alg member on the way.
#Check the claims
When the payload is a JSON object, verify checks the claims after the signature. Without options it checks only what the token carries: exp in the past is ERR_JWT_EXPIRED, nbf in the future is ERR_JWT_NBF, and a time claim that isn't a non-negative number is ERR_JWT_CLAIM_INVALID. The options add expectations:
| Option | Checks |
|---|---|
issuer | iss is present and equals one of the values. |
audience | aud is present and contains one of the values. Without this option aud is not checked. |
subject | sub is present and equals the value. |
maxTokenAge | iat is present and not older than the duration. |
requiredClaims | Each named claim is present. |
clockTolerance | Seconds, or a duration such as "30s", of skew allowed on exp, nbf and iat. Defaults to 0. |
currentDate | The moment the time claims are checked against. Defaults to now. |
typ | The header's typ matches, case-insensitive and with or without application/. A header without typ fails. |
recognizedHeaders | crit extensions your code understands. A crit entry outside this list (b64 aside) is refused. |
validateClaims | false skips the claim checks above, typ and crit excepted; with issuer, audience, subject, maxTokenAge or requiredClaims it throws ERR_INVALID_OPTION. |
Every option is checked before the token is read: an empty audience, issuer, subject or typ, a maxTokenAge of 0, or a list that isn't an array of strings throws ERR_INVALID_OPTION, so a typo can't switch a check off. An empty list such as audience: [] accepts no token. Validate claims goes through each check in detail.
#Read a payload that is not JSON
You declare what the payload is with payload; the token never decides. The default "json" requires a JSON object and is the only mode that checks claims:
payload | You get | Claims checked |
|---|---|---|
omitted or "json" | the claims object, typed verify<MyClaims>() | yes |
"string" | the payload as UTF-8 text | no |
"bytes" | the payload as a Uint8Array | no |
const signed = await sign("amount=1200¤cy=EUR", key);
await verify(signed, key);
// JWTError ERR_JWS_INVALID: Invalid JWS: Payload is not a JSON object.
(await verify(signed, key, { payload: "string" })).payload; // "amount=1200¤cy=EUR"validateClaims: true, issuer, audience, subject, maxTokenAge or requiredClaims together with "string" or "bytes" throws ERR_INVALID_OPTION rather than checking nothing. clockTolerance and currentDate are accepted in every mode.
#What you get back
const { payload, protectedHeader } = await verify<AccessClaims>(token, issuerKeys, options);
// payload: { iss: "https://auth.example.com", aud: "https://api.example.com",
// sub: "user_1a2b", scope: "invoices:read", iat: 1793005200, exp: 1793006100 }
// protectedHeader: { kid: "2026-10", typ: "at+jwt", alg: "ES256" }protectedHeader is the header exactly as it was signed, and always carries alg. The claims type you pass is a promise you make about the payload's shape, not a check: validate fields your code depends on.
#When it fails
In the order verify checks:
| Situation | What happens |
|---|---|
| An option is empty or malformed | Throws ERR_INVALID_OPTION, before the token is read. |
A claim option with a non-JSON payload or with validateClaims: false | Throws ERR_INVALID_OPTION, before the token is read. |
The token is not a string, not three segments, or its header is not a JSON object with alg | Throws ERR_JWS_INVALID. |
The header's alg is "none" or unsupported | Throws ERR_JWS_ALG_NOT_ALLOWED. |
typ doesn't match, or b64: false without "b64" in crit | Throws ERR_JWS_INVALID. |
The lookup function returned undefined | Throws ERR_JWK_KEY_NOT_FOUND. |
The lookup function threw an error that is not a JWTError | Throws ERR_JWK_KEY_NOT_FOUND, with that error as cause. |
The lookup function threw a JWTError | Throws that error. |
The alg is not in algorithms, or nothing can be inferred from the key | Throws ERR_JWS_ALG_NOT_ALLOWED. |
The JWK Set has no entry for the kid, or more candidates than limits.keyCandidates | Throws ERR_JWK_KEY_NOT_FOUND. |
The key is missing, a string, a private JWK, or can't serve the alg | Throws ERR_JWK_INVALID. |
| The signature doesn't match | Throws ERR_JWS_SIGNATURE_INVALID; for a JWK Set, cause lists each try. |
crit names an extension you didn't list in recognizedHeaders | Throws ERR_JWS_INVALID. |
The payload doesn't fit the payload mode | Throws ERR_JWS_INVALID. |
A claim required by requiredClaims, issuer, audience, subject or maxTokenAge is missing | Throws ERR_JWT_CLAIM_MISSING. |
iss, sub or aud has the wrong value, or a time claim is not a non-negative number | Throws ERR_JWT_CLAIM_INVALID. |
nbf is in the future | Throws ERR_JWT_NBF. |
exp has passed, or iat is older than maxTokenAge | Throws ERR_JWT_EXPIRED. |
Handle errors lists every code and what to do about it.
#Options
| Option | Default | Notes |
|---|---|---|
algorithms | inferred from the key | The alg values to accept. Required for raw bytes and alg-less RSA or oct keys. |
payload | "json" | "json", "string" or "bytes". Sets the return type. |
validateClaims | true under "json" | false skips the claim checks. |
audience | none | Expected aud, one value or a list. |
issuer | none | Expected iss, one value or a list. |
subject | none | Expected sub. |
maxTokenAge | none | Oldest accepted iat, as a duration. |
requiredClaims | none | Claim names that must be present. |
clockTolerance | 0 | Skew allowed on exp, nbf and iat, in seconds or a duration. |
currentDate | now | The moment the time claims are checked against. |
typ | none | Expected header typ, compared as a media type. |
recognizedHeaders | none | crit extensions your code handles. |
limits.keyCandidates | 8 | Most JWK Set entries one token is tried against. |
#Going further
- Fetching a
jwks_uriand rotating keys: Use a JWK Set. - Every claim check in detail: Validate claims.
- Tokens with several signatures: Sign for several verifiers.
- The producing side: Sign a token.