A minimal, secure, and production-ready JWT (JSON Web Token) library for Node.js with zero dependencies. Supports all standard signing algorithms (HMAC, RSA, ECDSA, EdDSA, RSASSA-PSS), automatic algorithm detection, first-class JWK/JWKS (verify straight against a local or remote key set), and full claim validation.
β¨ Why another JWT library? Most JWT libraries are bloated, have security pitfalls, or lack proper TypeScript support. This library is:
verify(); publish your own JWKS with one callnpm install @sourceregistry/node-jwt
Requires Node.js β₯ 16
import { randomBytes } from 'crypto';
import { sign, verify, decode } from '@sourceregistry/node-jwt';
// HS256 needs a secret of at least 32 bytes (RFC 7518 Β§3.2)
const secret = randomBytes(32);
// Sign (algorithm auto-detected)
const token = sign(
{ sub: '1234567890', name: 'John Doe', iat: Math.floor(Date.now() / 1000) },
secret
);
// Verify
const result = verify(token, secret, { algorithms: ['HS256'], issuer: 'https://example.com' });
if (result.valid) {
console.log('Payload:', result.payload);
} else {
console.error('JWT Error:', result.error.code, result.error.reason);
}
// Decode (unsafe)
const { header, payload, signature } = decode(token);
/promises)import { sign, verify, JWTError } from '@sourceregistry/node-jwt/promises';
const token = await sign({ sub: '1234567890', iat: Math.floor(Date.now() / 1000) }, secret);
try {
const { payload } = await verify(token, secret, {
issuer: 'https://example.com',
audience: 'my-app',
algorithms: ['HS256']
});
console.log('Payload:', payload);
} catch (error) {
if (error instanceof JWTError) console.error('JWT Error:', error.code, error.reason);
}
No glue code needed: every place that takes a key also takes a JWK, and verify() takes a whole JWKS.
import { JWKS } from '@sourceregistry/node-jwt';
import { verify } from '@sourceregistry/node-jwt/promises';
// Create once and reuse: keys are cached, refreshed after `ttl`
// and re-fetched (rate limited) when a token carries an unknown `kid`.
const issuerKeys = await JWKS.fromWeb('https://issuer.example'); // -> /.well-known/jwks.json
const { payload } = await verify(token, issuerKeys, {
algorithms: ['RS256'],
issuer: 'https://issuer.example',
audience: 'my-api'
});
import { verify } from '@sourceregistry/node-jwt';
verify(token, jwk, { algorithms: ['ES256'] }); // a single JWK
verify(token, { keys: [/* ... */] }, { algorithms: ['ES256'] }); // a JWKS: selected by kid + alg
verify(token, (header) => keyFor(header.kid)); // or resolve the key yourself
Key selection follows RFC 7517 and RFC 8725: a key is only used when its kid matches (if the token has one),
use is sig (or absent), key_ops includes verify (or is absent), its alg equals the token's alg
(or is absent) and its kty / crv fit the algorithm. Remote key sets never supply symmetric keys and are
only used as public keys.
import { generateKeyPairSync } from 'crypto';
import { JWK, JWKS, sign } from '@sourceregistry/node-jwt';
const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
const signingKey = JWK.export(privateKey, { kid: '2026-01', alg: 'ES256', use: 'sig' });
// kid and alg are taken from the JWK
const token = sign({ sub: 'user-1' }, signingKey);
// Serve this at /.well-known/jwks.json: private members are stripped,
// a missing kid becomes the RFC 7638 thumbprint and use defaults to "sig".
const jwks = JWKS.create([signingKey]);
| Function | Description |
|---|---|
JWK.export(key, params?) / exportJWK |
KeyObject β JWK, optionally with kid / alg / use / key_ops |
JWK.import(jwk) / importJWK |
JWK β KeyObject. Validates x5c / x5t / x5t#S256 against the key |
JWK.toPublic(keyOrJwk, params?) / toPublicJWK |
Public-only JWK (rejects symmetric keys) |
JWK.thumbprint(jwk, hash?) / getJWKThumbprint |
RFC 7638 thumbprint (sha256 default, sha384, sha512) |
JWK.computeX5T(jwk, hash?) / computeX5T |
x5t (SHA-1) or x5t#S256 from x5c |
JWK.isUsableFor(jwk, alg, op?) / isJWKUsableFor |
Whether use / key_ops / alg / kty allow the operation |
JWKS.create(keys) / createJWKS |
Build a publishable public JWKS |
JWKS.select(jwks, { alg, kid? }) / selectJWKs |
Keys that can verify a given alg / kid |
JWKS.normalize(jwks) / normalizeJWKS |
Drop unsupported keys (RFC 7517 Β§5), fill in kid / x5t |
JWKS.toKeyObject(jwks, kid?) |
KeyObject for a kid (or the only key) |
JWKS.fromWeb(url, options?) / fromWeb |
Cached remote JWKS resolver |
JWKS.fromWeb() optionsfetch β custom fetch implementation (for runtimes/framework adapters)ttl β cache TTL in ms (default 5 minutes; 0 disables automatic refresh, call refresh() instead)maxStaleMs β how long to keep serving cached keys after ttl when refreshing fails (default 5 minutes; 0 fails closed)timeoutMs β timeout for fetching and parsing the JWKS response in ms (default 5 seconds)cooldownMs β minimum time between re-fetches caused by an unknown kid (default 30 seconds)endpointOverride β custom endpoint (absolute or relative to url)overrideEndpointCheck β skip automatic /.well-known/jwks.json appendallowInsecureHttp β allow http: on non-loopback hosts. Otherwise endpoints must use https: (localhost, 127.0.0.1 and [::1] are allowed for development)cache β custom cache backend with { get(key), set(key, value) }; persist the fetchedAt timestamp included in values passed to set. Entries without a valid timestamp are fetched again when ttl > 0.Resolver methods:
resolve({ alg, kid }) β public keys that can verify a token (used by the promise verify())key(kid) β normalized key (or undefined) extended with toKeyObject()list() β all normalized keysfind(query) / findFirst(query) β keys whose members equal queryrefresh() β forces reload and returns the resolver instanceexport() β the current cached JWKS snapshot, or undefined after its maximum stale ageKeys with a kty the library does not understand (for example post-quantum AKP keys) or with missing
members are ignored instead of failing the whole set, as required by RFC 7517 Β§5.
| Algorithm | Type | Key |
|---|---|---|
| HS256 / HS384 / HS512 | HMAC | secret β₯ 32 / 48 / 64 bytes |
| RS256 / RS384 / RS512 | RSASSA-PKCS1-v1_5 | RSA β₯ 2048 bits |
| PS256 / PS384 / PS512 | RSASSA-PSS | RSA or RSA-PSS β₯ 2048 bits |
| ES256 / ES384 / ES512 | ECDSA | P-256 / P-384 / P-521 |
| ES256K | ECDSA (RFC 8812) | secp256k1 |
| EdDSA | EdDSA (RFC 8037) | Ed25519 or Ed448 |
| Ed25519 / Ed448 | EdDSA (RFC 9864) | Ed25519 / Ed448 |
Keys may be PEM, DER, JWK, or Node.js KeyObject.
When alg is omitted, sign() uses the JWK's alg if present, otherwise it picks one from the key:
| Key | Algorithm |
|---|---|
Symmetric (string / Buffer) |
HS256 |
| RSA | RS256 |
| RSA-PSS | PS256 / PS384 / PS512 (from the key's hash) |
| EC P-256 / P-384 / P-521 | ES256 / ES384 / ES512 |
| EC secp256k1 | ES256K |
| Ed25519 / Ed448 | EdDSA |
Unsupported keys (other EC curves, RSA-PSS with SHA-1, DSA, ...) throw.
alg: none and unknown algorithms are always rejected; algorithms allowlist supportedkid, use, key_ops, alg, kty and crvhttps: required, insecure redirects rejected, symmetric and private key material never usedr || s (RFC 7518 Β§3.4); DER is only accepted when explicitly requestedcrit)exp, nbf, iat) with clock skew, maxTokenAge, requiredClaimsx5c certificates must contain the JWK's key; x5t / x5t#S256 must matchsign() / verify() use private copies of the signature primitives, so mutating the exported SignatureAlgorithm map cannot weaken themconst result = verify(token, publicKeyOrJwks, {
algorithms: ['RS256'], // pin expected algorithm(s)
issuer: 'https://issuer.example',
audience: 'my-service',
requiredClaims: ['exp'], // reject tokens without an expiry
clockSkew: 30, // seconds
maxTokenAge: 3600 // seconds
});
algorithms in every verify call (RFC 8725 Β§3.1).issuer and audience for external tokens. RFC 7519 Β§4.1.3 requires a recipient to reject a token
whose aud does not identify it, so configure audience whenever tokens carry one.tokenTypes narrowly scoped when accepting specialized JWT profiles (default ['JWT']).exp with requiredClaims.JWKS.fromWeb() picks up new kids automatically.INVALID_SIGNATURE, KEY_ALGORITHM_MISMATCH, KEY_NOT_FOUND, INVALID_CLAIM).| Spec | Coverage |
|---|---|
| RFC 7515 (JWS) | Compact serialization, canonical base64url, UTF-8 JSON header, crit rejection, case-insensitive typ with implicit application/ |
| RFC 7517 (JWK) | use / key_ops / alg enforcement, x5c / x5t / x5t#S256 validation, unknown keys ignored in sets |
| RFC 7518 (JWA) | All JWS signature algorithms, minimum key sizes, PSS salt = hash length, r β s ECDSA signatures |
| RFC 7519 (JWT) | Claims object, registered claim types, exp / nbf / iat, iss / sub / aud / jti, cty for nested JWTs |
| RFC 7638 | JWK thumbprints (SHA-256 / 384 / 512) |
| RFC 8037 | EdDSA with Ed25519 and Ed448 |
| RFC 8725 (JWT BCP) | Algorithm allowlists, key/algorithm binding, explicit typing via tokenTypes |
| RFC 8812 | ES256K |
| RFC 9864 | Fully-specified Ed25519 / Ed448 algorithms |
JWS requires ECDSA signatures as the raw r || s concatenation ("JOSE" format, RFC 7518 Β§3.4), while
Node.js/OpenSSL natively use ASN.1 DER. sign() and verify() use JOSE by default.
For legacy systems that produce non-standard DER-encoded JWTs, opt in explicitly:
sign(payload, ecPrivateKey, { signatureFormat: 'der' });
verify(token, ecPublicKey, { signatureFormat: 'der' });
π‘ VAPID/Web Push uses
ES256with the default JOSE format.
sign(payload, key, options?)key β secret, PEM/DER, KeyObject or JWK (private or oct)alg β defaults to the JWK's alg, otherwise auto-detectedkid β defaults to the JWK's kidtyp β token type (default "JWT")cty β content type, e.g. "JWT" for nested tokenssignatureFormat β ECDSA only: "jose" (default) or "der"The payload must be a JSON object; registered claims (iss, sub, aud, exp, nbf, iat, jti, sid) are type-checked.
verify(token, key, options?)key may be a secret, PEM/DER, KeyObject, JWK, JWKS or (header) => key.
The promise version additionally accepts a JWKS.fromWeb() resolver and async functions, and rejects with a JWTError.
Options:
algorithms β allowlist (non-empty)tokenTypes β allowed typ values (default ['JWT']; a missing typ is valid). Compared case-insensitively, application/ optional.
For example, OpenID Connect Back-Channel Logout tokens use tokenTypes: ['logout+jwt'].issuer, subject, audience, jwtId β expected claim valuesrequiredClaims β claims that must be presentclockSkew β seconds of tolerance for exp, nbf, iat and maxTokenAgemaxTokenAge β maximum age in seconds (requires iat)ignoreExpiration β skip the exp checksignatureFormat β ECDSA only: "jose" (default) or "der"Error codes:
INVALID_OPTIONS, INVALID_TOKEN, INVALID_CLAIMINVALID_ALGORITHM, ALGORITHM_NOT_ALLOWED, INVALID_TYPE, UNSUPPORTED_CRITICAL_HEADERKEY_NOT_FOUND, KEY_ALGORITHM_MISMATCH, INVALID_SIGNATURETOKEN_EXPIRED, TOKEN_NOT_ACTIVE, TOKEN_FUTURE_ISSUED, TOKEN_TOO_OLDMISSING_CLAIM, MISSING_IAT, MISSING_ISSUER / INVALID_ISSUER, MISSING_SUBJECT / INVALID_SUBJECT,
MISSING_AUDIENCE / INVALID_AUDIENCE, MISSING_JTI / INVALID_JTIdecode(token)Decode a JWT without verification (unsafe).
These changes make the library spec compliant and may reject tokens or keys that were accepted before:
signatureFormat: 'der' for legacy tokens.INVALID_TOKEN).sign() rejects non-object payloads and registered claims with the wrong type.JWKS.fromWeb() requires https: (except loopback) unless allowInsecureHttp: true, and throws on invalid endpoint URLs.SignatureAlgorithm.ES* primitives produce and expect JOSE (r || s) signatures.verify() rejects with a JWTError (an Error with the same code and reason properties as before).SupportedAlgorithms is a frozen array and also contains Ed25519 and Ed448.maxTokenAge now honors clockSkew.| Import | Description |
|---|---|
@sourceregistry/node-jwt |
Sync API |
@sourceregistry/node-jwt/promises |
Promise API |
npm test
npm run test:coverage
PRs welcome! Please add tests and maintain full coverage.
π Security issues? Report responsibly: a.p.a.slaa@projectsource.nl
π GitHub: https://github.com/SourceRegistry/node-jwt π¦ npm: https://www.npmjs.com/package/@sourceregistry/node-jwt