Node.js JWT invalid signature: JWKS Rotation and Clock Skew
One message covers three bugs: the wrong key type for RS256 or ES256, a JWKS cache that never refreshes after a kid rotation, and a clock that drifted.

Introduction & Quick Summary
Symptom. jsonwebtoken throws JsonWebTokenError: invalid signature on tokens that the identity provider itself reports as valid, and it starts suddenly on a Friday with no deploy. Or TokenExpiredError: jwt expired appears for a token whose exp is two minutes in the future. Or verification works for HS256 in development and fails for every RS256 token from the real issuer.
Cause. Three separate mistakes produce the same message. The verification key is wrong for the algorithm — a shared secret for an RS256/ES256 token, a PEM string where a JWKS key object is needed, or a PKCS#1 key where PKCS#8 is expected. The key is stale — providers rotate signing keys, kid changes, and a process that fetched the JWKS once at startup keeps verifying against a key that no longer signs. Or the clock differs — exp and nbf are compared against local time, and a container a few minutes ahead rejects fresh tokens.
Fix. Verify with a remote JWKS that refreshes on an unknown kid instead of caching forever, pin algorithms to exactly what the issuer uses, pass clockTolerance for real-world clock drift, and make sure the key material's format matches the algorithm.
Core Mechanics, Signatures & Reproducible Setup
A JWT carries the key id in its header, and verification must select the key by that id rather than by position.
// decoded header of a token that fails with "invalid signature"
{ alg: "RS256", kid: "d2VpcmQ6a2V5OjE", typ: "JWT" }import { createRemoteJWKSet, jwtVerify } from "jose";
const JWKS = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json"));
export async function verify(token) {
const { payload, protectedHeader } = await jwtVerify(token, JWKS, {
issuer: "https://auth.example.com/",
audience: "https://api.example.com",
algorithms: ["RS256"], // pin it; never accept what the header claims
clockTolerance: 60, // seconds of allowed skew
});
return payload;
}createRemoteJWKSet caches keys, refetches when it sees a kid it does not hold, and applies a cooldown so a burst of unknown tokens triggers one fetch rather than thousands. That is the behaviour that makes rotation invisible; a hand-rolled fetch at boot has none of it.
Reproduce the signature failure with a mismatched key pair:
import jwt from "jsonwebtoken";
const token = jwt.sign({ sub: "u1" }, "secret-a", { algorithm: "HS256" });
jwt.verify(token, "secret-b"); // JsonWebTokenError: invalid signature
jwt.verify(token, "secret-a", { algorithms: ["HS256"] }); // okSame code, one character in the key. The message never says which of the two inputs was wrong, which is why the algorithm and key format have to be checked together.
Key Comparison Table
| Algorithm | Key material | Common wrong input | Library support |
|---|---|---|---|
HS256 | shared secret, ≥ 32 bytes | a public key pasted as a secret | jsonwebtoken, jose |
RS256 | RSA public key, PEM SPKI | PKCS#1 BEGIN RSA PUBLIC KEY | both |
PS256 | RSA public key | verified as RS256 | both |
ES256 | EC P-256 public key | DER signature instead of raw R||S | both |
EdDSA | Ed25519 public key | Node's crypto key object misuse | jose, jsonwebtoken 9+ |
| Symptom | Likely cause | Check |
|---|---|---|
invalid signature on every token | wrong algorithm family | header alg vs key type |
invalid signature after weeks | JWKS cache never refreshed | kid in header vs keys held |
invalid signature on one issuer only | wrong audience/issuer | iss and aud claims |
jwt expired on a fresh token | clock skew | date -u in the container |
invalid algorithm | algorithms pinned too narrow | allow exactly the issuer's set |
secretOrPublicKey must be provided | env var empty in that pod | config, not code |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Rotation with jsonwebtoken and jwks-rsa
If you keep jsonwebtoken, the JWKS client is a separate package, and its cache options are where rotation goes wrong:
import jwksClient from "jwks-rsa";
import jwt from "jsonwebtoken";
const client = jwksClient({
jwksUri: "https://auth.example.com/.well-known/jwks.json",
cache: true,
cacheMaxAge: 10 * 60 * 1000, // 10 minutes, not "forever"
rateLimit: true,
jwksRequestsPerMinute: 10,
});
async function getKey(header) {
const key = await client.getSigningKey(header.kid); // throws if kid unknown
return key.getPublicKey();
}
export async function verify(token) {
const decoded = jwt.decode(token, { complete: true });
const key = await getKey(decoded.header); // refresh happens here
return jwt.verify(token, key, { algorithms: ["RS256"], clockTolerance: 60 });
}A cache that never expires is the classic cause of "it worked for a month". cacheMaxAge must be finite, and getSigningKey with an unknown kid must be allowed to reach the network.
2. jwt expired from clock skew
exp and nbf are integers of seconds since the epoch, compared with the verifier's clock. A container whose clock drifted 90 seconds ahead rejects every token for 90 seconds after issuance; a token with nbf set by a server behind by a minute is not yet valid anywhere.
jwt.verify(token, key, { clockTolerance: 60 }); // jsonwebtoken: seconds
// jose: same name, same unitclockTolerance widens the window in both directions and does not weaken the signature. Verify the skew itself with docker run --rm node:22 date -u against the host, and enable chrony or the platform's time sync — a tolerance is a buffer, not a fix.
3. ES256 signatures are not DER
ECDSA signatures in JOSE are the raw concatenation of R and S as fixed-width big-endian integers (64 bytes for P-256). Most non-JOSE libraries expect DER-encoded SEQUENCE { r, s }. Passing one into the other yields invalid signature with a mathematically valid signature.
// correct: let the JWT library do the conversion
await jwtVerify(token, publicKey, { algorithms: ["ES256"] });
// wrong: hand-rolling with crypto.verify and DER assumptions
crypto.verify("sha256", data, publicKey, signature); // returns false for JOSE sigsThe reverse migration — moving from jsonwebtoken to jose with the same key — also needs the key imported correctly: jose accepts a KeyObject, a PEM string, or a JWK, and silently treats a JWK for the wrong curve as a different key.
4. Rejecting alg: none and algorithm confusion
A verifier that trusts the header's alg can be told to use HS256 with the RSA public key as the HMAC secret — a public value — and forge tokens. algorithms is not optional.
jwt.verify(token, publicKey, { algorithms: ["RS256"] }); // reject everything elseThe same applies in jose, where passing an array is required for symmetric and asymmetric keys to be distinguished safely. Never jwt.decode for authorisation: it parses without verifying.
5. aud and iss mismatches that read as signature failures
Two environments sharing one signing key but different audiences produce tokens that verify cryptographically and fail authorisation. Pin both, and include the trailing slash precisely.
jwt.verify(token, key, {
algorithms: ["RS256"],
issuer: "https://auth.example.com/", // trailing slash matters
audience: "https://api.example.com",
});A token minted for aud: "https://app.example.com" will throw jwt audience invalid. expected: https://api.example.com, not a signature error — but a missing audience option means no check at all, and cross-service token reuse becomes an unnoticed hole.
6. Where to cache and where not to
Verifying a JWT on every request should cost microseconds, which means the JWKS lookup must not be a network call per request. Keep one JWKS client per process, refresh on unknown kid, and cap the cooldown. In serverless, module scope survives between invocations often enough to help, and a cold start pays one fetch.
Common Compilation/Runtime Mistakes & Version Gotchas
jsonwebtokenv9 removed implicit algorithm acceptance. A v8 call withoutalgorithmsstart failing after the upgrade.jwt.decodeused for authorisation. It performs no verification and returnspayloadfor anything.secretfromprocess.envthat isundefinedin one deployment.jsonwebtokenthrowssecretOrPublicKey must be provided; a spread of the same bug passes an empty string, which is worse.- A JWKS cache with no TTL. Rotation appears as a total auth outage on the next deploy.
- PEM with literal
\nfrom an environment variable. The key parses to garbage and verification fails with the sameinvalid signature. - HS256 secret shorter than the hash output.
joserejects it;jsonwebtokenaccepts it, which is a silent weakness. clockToleranceset in milliseconds. The option is seconds in both libraries;60000means sixteen hours of tolerance.
Related tools. Paste a failing token into the JWT decoder to read header.kid, alg, exp, and aud without verifying it, compare the JWKS document before and after a rotation with the JSON formatter, and convert the numeric exp to a readable date with the timestamp converter.
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesERR_REQUIRE_ESM and __dirname Is Not Defined in ESM Projects
require of an ESM-only package has nothing to load, and ESM creates none of the CommonJS wrapper globals. Dynamic import, createRequire, and the path replacements.
Node.js fetch ETIMEDOUT and SELF_SIGNED_CERT_IN_CHAIN Debugging
fetch failed hides everything in error.cause. Read the aggregate, trust the private CA the way curl does, route the proxy, and set the connect timeout undici does not.
Node.js JavaScript heap out of memory: Snapshots and Real Leaks
Distinguish needs more from leaks before raising the flag: external memory and heap tell different stories, and a heap ceiling at three quarters of the container limit keeps V8 able to report.
Node.js EventEmitter: once, error Events, and Listener Memory Leaks
emit is synchronous, so a throwing listener aborts the rest. An error event with no listener crashes the process, and a listener per request is the classic leak.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.