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.
  • verify checks aud only when you pass audience, and a token without exp never 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:

verify-with-jwks.ts
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 kid picks the key, so the issuer can rotate keys and publish old and new ones side by side. A kid the 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.
  • null on failure: every refusal is a JWTError, so one check turns them all into a 401. Anything else is a bug in your code and keeps propagating.

#Pass the key

KeyWhen to use it
A public JWKOne issuer, one key pair.
An oct JWK or raw bytesHS* tokens you signed with the same secret. Bytes declare no algorithm: pass algorithms.
A CryptoKeyA 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 }) => keyKeys 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:

"none" and any name outside the supported list are refused with ERR_JWS_ALG_NOT_ALLOWED.
With algorithms, the header's alg must be in the list. The list is exact: ["Ed25519"] doesn't admit a token whose header says EdDSA.
Without it, a JWK that declares alg accepts that algorithm only (EdDSA and Ed25519 count as one).
Otherwise the allowed set is read from the key's shape: an EC key's curve, a 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"] }); // ok

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

OptionChecks
issueriss is present and equals one of the values.
audienceaud is present and contains one of the values. Without this option aud is not checked.
subjectsub is present and equals the value.
maxTokenAgeiat is present and not older than the duration.
requiredClaimsEach named claim is present.
clockToleranceSeconds, or a duration such as "30s", of skew allowed on exp, nbf and iat. Defaults to 0.
currentDateThe moment the time claims are checked against. Defaults to now.
typThe header's typ matches, case-insensitive and with or without application/. A header without typ fails.
recognizedHeaderscrit extensions your code understands. A crit entry outside this list (b64 aside) is refused.
validateClaimsfalse 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:

payloadYou getClaims checked
omitted or "json"the claims object, typed verify<MyClaims>()yes
"string"the payload as UTF-8 textno
"bytes"the payload as a Uint8Arrayno
const signed = await sign("amount=1200&currency=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&currency=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:

SituationWhat happens
An option is empty or malformedThrows ERR_INVALID_OPTION, before the token is read.
A claim option with a non-JSON payload or with validateClaims: falseThrows 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 algThrows ERR_JWS_INVALID.
The header's alg is "none" or unsupportedThrows ERR_JWS_ALG_NOT_ALLOWED.
typ doesn't match, or b64: false without "b64" in critThrows ERR_JWS_INVALID.
The lookup function returned undefinedThrows ERR_JWK_KEY_NOT_FOUND.
The lookup function threw an error that is not a JWTErrorThrows ERR_JWK_KEY_NOT_FOUND, with that error as cause.
The lookup function threw a JWTErrorThrows that error.
The alg is not in algorithms, or nothing can be inferred from the keyThrows ERR_JWS_ALG_NOT_ALLOWED.
The JWK Set has no entry for the kid, or more candidates than limits.keyCandidatesThrows ERR_JWK_KEY_NOT_FOUND.
The key is missing, a string, a private JWK, or can't serve the algThrows ERR_JWK_INVALID.
The signature doesn't matchThrows ERR_JWS_SIGNATURE_INVALID; for a JWK Set, cause lists each try.
crit names an extension you didn't list in recognizedHeadersThrows ERR_JWS_INVALID.
The payload doesn't fit the payload modeThrows ERR_JWS_INVALID.
A claim required by requiredClaims, issuer, audience, subject or maxTokenAge is missingThrows ERR_JWT_CLAIM_MISSING.
iss, sub or aud has the wrong value, or a time claim is not a non-negative numberThrows ERR_JWT_CLAIM_INVALID.
nbf is in the futureThrows ERR_JWT_NBF.
exp has passed, or iat is older than maxTokenAgeThrows ERR_JWT_EXPIRED.

Handle errors lists every code and what to do about it.

#Options

OptionDefaultNotes
algorithmsinferred from the keyThe 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.
validateClaimstrue under "json"false skips the claim checks.
audiencenoneExpected aud, one value or a list.
issuernoneExpected iss, one value or a list.
subjectnoneExpected sub.
maxTokenAgenoneOldest accepted iat, as a duration.
requiredClaimsnoneClaim names that must be present.
clockTolerance0Skew allowed on exp, nbf and iat, in seconds or a duration.
currentDatenowThe moment the time claims are checked against.
typnoneExpected header typ, compared as a media type.
recognizedHeadersnonecrit extensions your code handles.
limits.keyCandidates8Most JWK Set entries one token is tried against.

#Going further