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:
- Tiny
- Secure by default
- TypeScript-first with full JSDoc
- Zero external dependencies
- 100% test coverage (Trying😉)
- Dual API: Sync and Promise-based
- Automatic algorithm detection based on key type
- Full JWK/JWKS support: pass a JWK, a JWKS or a remote JWKS resolver directly to
verify(); publish your own JWKS with one call - Spec compliant: RFC 7515, 7517, 7518, 7519, 7638, 8037, 8725, 8812 and 9864 (see Spec compliance)
npm install @sourceregistry/node-jwtRequires 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);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 yourselfKey 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 |
fetch— custom fetch implementation (for runtimes/framework adapters)ttl— cache TTL in ms (default 5 minutes;0disables automatic refresh, callrefresh()instead)maxStaleMs— how long to keep serving cached keys afterttlwhen refreshing fails (default 5 minutes;0fails closed)timeoutMs— timeout for fetching and parsing the JWKS response in ms (default 5 seconds)cooldownMs— minimum time between re-fetches caused by an unknownkid(default 30 seconds)endpointOverride— custom endpoint (absolute or relative tourl)overrideEndpointCheck— skip automatic/.well-known/jwks.jsonappendallowInsecureHttp— allowhttp:on non-loopback hosts. Otherwise endpoints must usehttps:(localhost,127.0.0.1and[::1]are allowed for development)cache— custom cache backend with{ get(key), set(key, value) }; persist thefetchedAttimestamp included in values passed toset. Entries without a valid timestamp are fetched again whenttl > 0.
Resolver methods:
resolve({ alg, kid })— public keys that can verify a token (used by the promiseverify())key(kid)— normalized key (orundefined) extended withtoKeyObject()list()— all normalized keysfind(query)/findFirst(query)— keys whose members equalqueryrefresh()— forces reload and returns the resolver instanceexport()— the current cached JWKS snapshot, orundefinedafter its maximum stale age
Keys 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.
- Algorithm/key binding: each algorithm only accepts its key type and curve; HMAC never accepts asymmetric keys (RFC 8725 §2.1)
- Minimum key sizes enforced on sign and verify: HMAC secret ≥ hash size, RSA ≥ 2048 bits (RFC 7518 §3.2, §3.3)
alg: noneand unknown algorithms are always rejected;algorithmsallowlist supported- JWKS key selection honors
kid,use,key_ops,alg,ktyandcrv - Remote JWKS:
https:required, insecure redirects rejected, symmetric and private key material never used - ECDSA signatures must be exactly
r || s(RFC 7518 §3.4); DER is only accepted when explicitly requested - Strict, canonical base64url and UTF-8 decoding: every token has exactly one valid serialization
- Rejects unsupported critical headers (
crit) - Time claim validation (
exp,nbf,iat) with clock skew,maxTokenAge,requiredClaims x5ccertificates must contain the JWK's key;x5t/x5t#S256must match- Timing-safe HMAC comparison
sign()/verify()use private copies of the signature primitives, so mutating the exportedSignatureAlgorithmmap cannot weaken them
const 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
});- Pin
algorithmsin every verify call (RFC 8725 §3.1). - Always validate
issuerandaudiencefor external tokens. RFC 7519 §4.1.3 requires a recipient to reject a token whoseauddoes not identify it, so configureaudiencewhenever tokens carry one. - Keep
tokenTypesnarrowly scoped when accepting specialized JWT profiles (default['JWT']). - Use short token lifetimes and require
expwithrequiredClaims. - Rotate keys regularly;
JWKS.fromWeb()picks up newkids automatically. - Monitor verification failures (
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.
key— secret, PEM/DER,KeyObjector JWK (private oroct)alg— defaults to the JWK'salg, otherwise auto-detectedkid— defaults to the JWK'skidtyp— 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.
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— allowedtypvalues (default['JWT']; a missingtypis valid). Compared case-insensitively,application/optional. For example, OpenID Connect Back-Channel Logout tokens usetokenTypes: ['logout+jwt'].issuer,subject,audience,jwtId— expected claim valuesrequiredClaims— claims that must be presentclockSkew— seconds of tolerance forexp,nbf,iatandmaxTokenAgemaxTokenAge— maximum age in seconds (requiresiat)ignoreExpiration— skip theexpchecksignatureFormat— 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_JTI
Decode a JWT without verification (unsafe).
These changes make the library spec compliant and may reject tokens or keys that were accepted before:
- HMAC secrets must be at least as long as the hash output: 32 bytes for HS256, 48 for HS384, 64 for HS512 (RFC 7518 §3.2).
- RSA keys must be at least 2048 bits (RFC 7518 §3.3).
- ECDSA verification no longer falls back to DER signatures. Pass
signatureFormat: 'der'for legacy tokens. - Non-canonical base64url and invalid UTF-8 in tokens are rejected (
INVALID_TOKEN). sign()rejects non-object payloads and registered claims with the wrong type.JWKS.fromWeb()requireshttps:(except loopback) unlessallowInsecureHttp: true, and throws on invalid endpoint URLs.SignatureAlgorithm.ES*primitives produce and expect JOSE (r || s) signatures.- The promise
verify()rejects with aJWTError(anErrorwith the samecodeandreasonproperties as before). SupportedAlgorithmsis a frozen array and also containsEd25519andEd448.maxTokenAgenow honorsclockSkew.
| Import | Description |
|---|---|
@sourceregistry/node-jwt |
Sync API |
@sourceregistry/node-jwt/promises |
Promise API |
- High branch coverage
- All algorithms + autodetection paths
- All failure modes
- Sync + Promise APIs
- Full JWK/JWKS coverage (import/export, x5c/x5t, thumbprint, kid selection, remote rotation)
- RFC test vectors (RFC 7515 A.1, RFC 7638 §3.1, RFC 8037 A.3)
npm test
npm run test:coveragePRs 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