The key cache

Know when an imported key is reused across calls, keep that working in a long-running process, and reset it between tests.

Before an RSA, EC or OKP JWK can sign or verify, it has to be imported into Web Crypto, and that takes a moment each time. unjwt remembers the result per JWK object: pass the same object to sign(), verify(), encrypt(), decrypt() or importKey() again and the imported key is reused. Most apps never think about it. It matters when your process holds many keys for a long time, when keys arrive as fresh JSON on every request, and in tests.

#Before you start

  • Reuse follows the object, not its contents. A copy ({ ...jwk }) or the same key parsed again from JSON is imported afresh.
  • Treat a JWK object as fixed once you've used it. Changing its members in place keeps serving the key it held before; replace the object instead.
  • These are never cached: oct secrets (they import as bytes), CryptoKey and Uint8Array keys (they're already usable), and an importKey call that passes extractable or asCryptoKey.
  • An entry goes away once nothing references its JWK object any more, so the default needs no size limit or eviction.

#Keep one object per key

Load each key once and pass that same object around:

import { importKey } from "unjwt/jwk";

(await importKey(publicKey)) === (await importKey(publicKey)); // true: reused
(await importKey(publicKey)) === (await importKey({ ...publicKey })); // false: a copy is imported again

To rotate, put a new object where the old one was: config.verifyKey = nextPublicKey. Writing the new key's members into the old object, with Object.assign or field by field, keeps verifying with the old key and refuses the new key's tokens with ERR_JWS_SIGNATURE_INVALID.

#Share imported keys across JSON copies

When keys come in as JSON each time, say from a database row or a cache shared by several workers, key the cache on the key itself. configureJWKCache installs any object with get and set:

shared-cache.ts
import { configureJWKCache, thumbprint, type JWK, type JWKAlgorithm } from "unjwt/jwk";

const MAX_ENTRIES = 500;
const entries: Map<string, CryptoKey> = new Map();

/** The key material, the half of the pair, and the algorithm: never the `kid`. */
async function entryName(jwk: JWK, alg: JWKAlgorithm): Promise<string> {
  const half = "d" in jwk ? "private" : "public";
  return `${await thumbprint(jwk)}:${half}:${alg}`;
}

configureJWKCache({
  async get(jwk, alg) {
    return entries.get(await entryName(jwk, alg));
  },
  async set(jwk, alg, key) {
    if (entries.size >= MAX_ENTRIES) {
      const [oldest] = entries.keys();
      if (oldest !== undefined) entries.delete(oldest);
    }
    entries.set(await entryName(jwk, alg), key);
  },
});
  • Name an entry by the thumbprint, the half and the algorithm: the thumbprint covers only the public members (RFC 7638 §3.2), so a private key and its public half share one. Without the half, verify() would be served the private key sign() cached.
  • Never by kid: a kid is a label its publisher chooses, and two different keys can carry the same one, during a rotation or across merged sets. An entry named by kid serves the wrong key.
  • Your own eviction: a custom cache keeps whatever you store; this one holds 500 entries and drops the oldest.
  • Async is fine: get and set may return promises.

A get that throws makes the call that triggered it fail: importKey() throws your error as is, and sign() or verify() throw ERR_JWK_INVALID with your error as cause. Return undefined on a store outage instead, and the key is imported without the cache.

#Reset the cache in tests

clearJWKCache() puts back a fresh default cache, so no imported key carries over from one test to the next:

import { beforeEach } from "vitest";
import { clearJWKCache } from "unjwt/jwk";

beforeEach(() => clearJWKCache());

It also removes a custom cache you installed; call configureJWKCache again afterwards if you need yours. configureJWKCache(false) turns caching off, so every call imports its key again.

#When it fails

SituationWhat happens
A JWK object was changed in place after it was usedThe old key keeps being used: tokens of the new key fail to verify.
A custom cache's get or set throws, during importKey()Your error, unchanged.
The same, during sign() or verify()Throws ERR_JWK_INVALID, your error as cause.
The same, during decrypt()Throws ERR_JWE_DECRYPTION_FAILED, your error as cause.
A custom cache named by kid or by thumbprint aloneNothing throws, and the wrong key can be used. Name entries as above.

The cache functions throw nothing of their own. Handle errors lists every code.

#Options

FunctionWhat it does
configureJWKCache(cache)Installs cache, any object with get(jwk, alg) and set(jwk, alg, key) (JWKCacheAdapter). false turns caching off.
clearJWKCache()Puts back a fresh default cache.
WeakMapJWKCacheThe default cache, as a class: configureJWKCache(new WeakMapJWKCache()).

The setting is global: it applies to every call in the process, not to one key or request.

#Going further