Use a JWK Set

Hand verify() or decrypt() several keys at once, let each token's header pick the right one, and rotate keys without refusing a valid token.

A JWK Set (RFC 7517 §5) is a keyring: a JSON object with a keys array. Identity providers publish theirs at /.well-known/jwks.json so anyone can verify their tokens, and you keep one so an old key and a new key both work while you switch between them. Sets are for the receiving side: verify(), decrypt() and their multi variants take one, while sign() and encrypt() take a single key and write its kid into the header. A session takes a set as its key too: the first key issues, and every key opens.

#Before you start

  • A set is key material you chose to trust. Every entry that passes the filter below is tried, a secret (oct) entry included, so only put keys in a set whose tokens you'd accept.
  • A set you publish holds public keys only. A private key or a secret in a public set hands out the power to make your tokens.
  • Give every key a kid and every token gets one in its header; then exactly one key is tried, however large the set. Generated keys have one by default.
  • At most 8 keys are tried per token. Past that the token is refused before any key is tried.

#Verify tokens against a set

The issuer keeps the key pairs and publishes the public halves; a verifier needs only the set:

keyring.ts
/** Every key whose tokens you still accept; only `signing` signs new ones. */
export interface Keyring {
  signing: string;
  pairs: Array<{ privateKey: JWK_EC_Private<"ES256">; publicKey: JWK_EC_Public<"ES256"> }>;
}

/** What `/.well-known/jwks.json` serves: the public halves, never a private one. */
export function publishedSet(ring: Keyring): JWKSet {
  return { keys: ring.pairs.map((pair) => pair.publicKey) };
}

export function issueToken(ring: Keyring, userId: string) {
  const pair = ring.pairs.find((p) => p.privateKey.kid === ring.signing);
  if (!pair) throw new Error(`No key named "${ring.signing}" in the keyring`);
  return sign({ sub: userId }, pair.privateKey, { expiresIn: "1h" });
}

/** A verifier holds only the set; the token's `kid` picks the key. */
export async function readToken(set: JWKSet, token: string) {
  const { payload } = await verify(token, set, { algorithms: ["ES256"] });
  return payload;
}
  • publishedSet: what the issuer serves at /.well-known/jwks.json. It maps each pair to its publicKey, so no private key can slip in.
  • The kid picks: a token signed with 2026-10 is checked against the 2026-10 entry alone. A token whose kid is in no entry is refused before any signature check.
  • algorithms: ["ES256"]: the algorithms the set is for. Without it they're read from the set's keys; pinning them means an entry you didn't expect can't widen what's accepted.

#How a key is picked

For each token, an entry stays a candidate only when all of these hold:

It is a JWK. null, strings and other junk in keys are skipped, and so is an RSA, EC or OKP entry that carries a secret k member.
Its kid equals the token's kid. When the token names a kid, entries without one are skipped; when the token has none, every entry passes this step.
Its alg serves the token's alg, or it declares none. EdDSA and Ed25519 count as the same algorithm, and an oct entry whose alg is a content encryption algorithm such as A256GCM serves dir tokens.
Its use, when present, is "sig" for verify() or "enc" for decrypt().
Its key_ops, when present, allows the operation: verify, or for decrypting one of unwrapKey, decrypt, deriveBits, deriveKey.

The candidates are then tried in order, and the first that verifies or decrypts wins. A kid only narrows the set (RFC 7515 §4.1.4): it never vouches for a key, and the key it points to still has to check the signature. Before any of this, the token's alg has to be one the set's keys serve, or one of algorithms when you pass it.

#Rotate keys without downtime

Rotation is four steps, and the verifier runs the same readToken(set, token) through all of them:

keyring.ts
export async function createKeyring(kid: string): Promise<Keyring> {
  return { signing: kid, pairs: [await generateJWK("ES256", { kid })] };
}

/** Step 2: publish the next key before it signs anything. */
export async function addKey(ring: Keyring, kid: string): Promise<Keyring> {
  return { ...ring, pairs: [...ring.pairs, await generateJWK("ES256", { kid })] };
}

/** Step 3: sign with the next key; the old one stays so its tokens still verify. */
export function switchSigning(ring: Keyring, kid: string): Keyring {
  if (!ring.pairs.some((p) => p.publicKey.kid === kid)) throw new Error(`Add "${kid}" first`);
  return { ...ring, signing: kid };
}

/** Step 4: drop the old key once its last token has expired. */
export function retireKey(ring: Keyring, kid: string): Keyring {
  if (kid === ring.signing) throw new Error(`"${kid}" still signs new tokens`);
  return { ...ring, pairs: ring.pairs.filter((p) => p.publicKey.kid !== kid) };
}
Start: one key signs, and the set holds its public half.
Add the next key: publish its public half while the old key keeps signing. Wait until every verifier has fetched the new set; for one that caches the set for ten minutes, wait longer than that.
Switch signing: new tokens carry the new kid. The old public key stays in the set, so tokens issued before the switch still verify.
Retire the old key: once its last token has expired, drop it. A token it signed is then refused with ERR_JWK_KEY_NOT_FOUND.

#Verify tokens from an identity provider

When the set lives at someone else's URL, pass a lookup function. It receives one object, { header, token }, the token's protected header and the token itself, and returns a key, a whole set, or undefined when it has none for the token. The rules above apply to the key or set it returns:

remote-jwks.ts
import type { JWKSet } from "unjwt/jwk";
import { verify, type JWSKeyLookup } from "unjwt/jws";

const JWKS_URL = "https://auth.example.com/.well-known/jwks.json";
const MAX_AGE_MS = 10 * 60 * 1000;

let cached: { set: JWKSet; fetchedAt: number } | undefined;

const issuerKeys: JWSKeyLookup = async () => {
  if (!cached || Date.now() - cached.fetchedAt > MAX_AGE_MS) {
    const response = await fetch(JWKS_URL);
    if (!response.ok) throw new Error(`JWK Set fetch failed with ${response.status}`);
    cached = { set: await response.json(), fetchedAt: Date.now() };
  }
  return cached.set;
};

export async function readIssuerToken(token: string) {
  const { payload } = await verify(token, issuerKeys, {
    algorithms: ["RS256"],
    issuer: "https://auth.example.com",
    audience: "api.example.com",
  });
  return payload;
}
  • Fetched once per ten minutes: every token in between is checked against the cached set, with no request to the provider.
  • algorithms: ["RS256"]: pin what the provider signs with. A secret that ends up in their published set, by mistake or by an attacker, can't then be used to sign an HS256 token you'd accept.
  • A failed fetch: a lookup throws when it can't answer. The Error it throws on a failed fetch makes verify() throw ERR_JWK_KEY_NOT_FOUND, with that error as cause; a JWTError it throws reaches you as it is. A lookup that has no key for a token returns undefined instead, and verify() throws ERR_JWK_KEY_NOT_FOUND without a cause.
  • issuer and audience: a valid signature only says who signed the token; Validate claims checks it was meant for you.

#Secrets and content keys in a set

An oct entry is a candidate like any other, so a set you keep for yourself can hold HS256 secrets, or AES keys for decrypt(), and the kid picks among them. A content encryption key for dir, a secret whose alg is A256GCM or another enc value, matches a dir token whose enc equals that alg:

const cek = await generateJWK("A256GCM", { kid: "cek-2026-10" });
const token = await encrypt({ sub: "user_1a2b" }, cek); // header: { kid: "cek-2026-10", alg: "dir", enc: "A256GCM", typ: "JWT" }
await decrypt(token, { keys: [cek] }); // found by kid

#Pick keys out of a set

getJWKsFromSet(set, filter) returns the set's JWKs, junk entries dropped, narrowed by your filter when you pass one. Use it to choose recipients for several-recipient encryption, or to find the key a stored set should sign with:

import { getJWKsFromSet } from "unjwt/jwk";

getJWKsFromSet({ keys: [null, "x", { kty: "nope" }, publicKey] }); // [publicKey]
getJWKsFromSet(set, (key) => key.use === "enc"); // the encryption keys only

#When it fails

SituationWhat happens
No entry passes the filterThrows ERR_JWK_KEY_NOT_FOUND: No key found in JWK Set with kid "2026-11".
More candidates than limits.keyCandidates passThrows ERR_JWK_KEY_NOT_FOUND: 9 candidate keys exceed the limit of 8, narrow them with a "kid".
Candidates exist but none verifies or decryptsThrows ERR_JWS_SIGNATURE_INVALID or ERR_JWE_DECRYPTION_FAILED, each attempt in cause.
The token's alg isn't served by any key in the set, or not in algorithmsThrows ERR_JWS_ALG_NOT_ALLOWED or ERR_JWE_ALG_NOT_ALLOWED.
No key in the set declares an algorithm, and you passed no algorithmsThrows ERR_JWS_ALG_NOT_ALLOWED or ERR_JWE_ALG_NOT_ALLOWED: pass algorithms.
A lookup function returns undefinedThrows ERR_JWK_KEY_NOT_FOUND.
A lookup function throws an error that is not a JWTErrorThrows ERR_JWK_KEY_NOT_FOUND, with that error as cause.
A lookup function throws a JWTErrorThrows that error.
getJWKsFromSet gets something that isn't a setThrows ERR_JWK_INVALID.

A private key in a set passed to verify() is never used: it fails as a candidate. Handle errors lists every code.

#Options

OptionDefaultNotes
limits.keyCandidates8verify(), decrypt() and the multi variants. Most keys tried per token after the filter.
algorithmsread from the set's keysverify() and decrypt(). The algorithms a token may use; required when no key declares one.

The multi variants also hold a whole call to limits.keyAttempts (16 by default); Limits covers both.

#Going further

  • Types: JWKSet is { keys: JWK[] } plus any other members. JWKSet<[JWK_EC_Public<"ES256">, JWK_RSA_Public<"RS256">]> keeps the exact entries when you build one in code.
  • Lookup function types: JWSKeyLookup from unjwt/jws and JWEKeyLookup from unjwt/jwe type the header your function receives.
  • Signatures from several keys: Sign for several verifiers matches each signature to a key from the set.
  • Sessions rotate too: Rotate keys passes a JWK Set as the session key, newest key first: it issues session tokens, and every key in the set opens them.