jwtly
v1.2.0
Published
Secure-by-default JWTs for Node, Bun, Deno, browsers and edge runtimes. Pinned algorithms, required expiry, refresh-token rotation with reuse detection, JWKS, typed claims. Zero dependencies.
Maintainers
Readme
jwtly
Secure JSON Web Tokens (JWTs) and refresh tokens for Node.js, Bun, Deno, browsers and edge runtimes.
A JWT (JSON Web Token) is a signed string that holds data, such as a user id. Your server creates it when a user logs in and checks it on every request. jwtly creates and checks JWTs with safe defaults, and it includes refresh tokens. It runs everywhere Web Crypto runs, so you can use it in place of jsonwebtoken, also on Cloudflare Workers and Vercel Edge.
Features
- Runs everywhere: Node.js, Bun, Deno, browsers, Cloudflare Workers and Vercel Edge. Built on Web Crypto.
- Safe defaults: the algorithm is pinned to your key,
alg: noneis always rejected, every token must expire, weak secrets and small RSA keys are refused, and key-confusion attacks are blocked. - Refresh tokens built in: rotation, reuse detection (a stolen refresh token logs out the whole session), logout and a maximum session lifetime.
- Verify tokens from Auth0, Cognito, Google, Clerk, Keycloak and others with a cached, auto-refreshing JWKS (the list of public keys a provider publishes).
- Key rotation with
kid(key id), and publish your own/.well-known/jwks.json. - Typed claims and clear error classes (
JwtExpiredError,JwtSignatureError, ...). - Readable lifetimes:
expiresIn: '15m','7d','1h 30m'. - Zero dependencies, ESM and CommonJS, TypeScript types included.
Installation
npm install jwtlypnpm add jwtly
yarn add jwtly
bun add jwtlyQuick start
An access token is a short-lived token (15 minutes by default) that the client sends with each request. A refresh token lives longer (7 days by default). The client uses it only to get a new access token.
import { createJwt, memoryStore } from 'jwtly'
const jwt = createJwt({
secret: process.env.JWT_SECRET, // at least 32 bytes; create one with generateSecret()
issuer: 'my-app',
refresh: { store: memoryStore() },
})
// Log in: get an access token and a refresh token
const { accessToken, refreshToken } = await jwt.issue({ sub: 'user-1', role: 'admin' })
// Check the access token on each request
const claims = await jwt.verify(accessToken)
claims.sub // => 'user-1'
claims.role // => 'admin'
// Get a new pair when the access token expires. The old refresh token stops working.
const next = await jwt.rotate(refreshToken)With CommonJS, use const { createJwt, memoryStore } = require('jwtly').
Key terms
| Term | Meaning |
|---|---|
| JWT | A string with three parts: header, payload and signature. Anyone can read the payload. Only someone with the key can make a valid signature. |
| Claims | The fields in the payload. Standard ones: sub (subject, usually the user id), iss (issuer, who made the token), aud (audience, who the token is for), exp (expiry time), nbf (not valid before), iat (issued at), jti (token id). |
| Access token | Short-lived proof of login. The client sends it in the Authorization: Bearer <token> header. |
| Refresh token | Long-lived token that is used only to get a new access token. |
| Session | One login. All tokens from one login share a session id (sid). |
| Secret (HMAC) | One shared secret signs and checks tokens. Algorithms HS256, HS384, HS512. |
| Key pair | A private key signs tokens. A public key only checks them, so you can share it with other services. Algorithms RS*, PS*, ES* and EdDSA. See Choose an algorithm. |
| kid | Key id. Written to the token header, so the verifier knows which key to use. |
| JWKS | JSON Web Key Set: a JSON list of public keys, usually served at /.well-known/jwks.json. |
Table of contents
Usage
Sign and verify a token
import { sign, verify } from 'jwtly'
const secret = process.env.JWT_SECRET
const token = await sign({ sub: '42', role: 'admin' }, secret, { expiresIn: '15m' })
const payload = await verify(token, secret)
payload.sub // => '42'
payload.role // => 'admin'verify()checks the signature, the expiry and every option you pass. If anything is wrong, it throws. See Handle errors.verify()accepts"Bearer <token>"directly, so you can pass theAuthorizationheader as it is.- Every token must expire.
sign()withoutexpiresIn(or anexpclaim) throwsERR_JWT_EXPIRY_REQUIRED.
Create a strong secret
A secret for HS256 must be at least 32 bytes. Shorter secrets are rejected. Create one with generateSecret() or OpenSSL, and keep it in an environment variable:
import { generateSecret } from 'jwtly'
generateSecret() // 64 random bytes as a base64url string (86 characters)openssl rand -base64 64Configure once with createJwt
createJwt() keeps your key and rules in one place. Every token it signs is checked with the same rules.
import { createJwt } from 'jwtly'
const jwt = createJwt<{ role: 'admin' | 'user' }>({
secret: process.env.JWT_SECRET, // or privateKey / publicKey / keys / jwks
issuer: 'my-app', // written to tokens and checked on verify
audience: 'api', // written to tokens and checked on verify
expiresIn: '15m', // access token lifetime (default '15m')
clockTolerance: '5s', // allowed clock difference between servers (default '5s')
})
const token = await jwt.sign({ sub: '42', role: 'user' })
const claims = await jwt.verify(token)
claims.role // => 'user'Lifetimes are seconds when you pass a number or a string with no unit (900 or '900', the same as jsonwebtoken). You can also use units: '30s', '15m', '1h 30m', '7d'.
Log users in with access and refresh tokens
Add refresh to the config. Then issue() creates a token pair, rotate() swaps a refresh token for a new pair, and revoke() logs out.
import { createJwt, memoryStore } from 'jwtly'
const jwt = createJwt({
secret: process.env.JWT_SECRET,
expiresIn: '15m',
refresh: { store: memoryStore(), expiresIn: '30d', maxLifetime: '90d' },
})
// Log in (after you have checked the password)
const pair = await jwt.issue({ sub: 'user-1', role: 'admin' })
// => { accessToken: 'eyJ...', refreshToken: 'eyJ...', tokenType: 'Bearer',
// expiresIn: 900, refreshExpiresIn: 2592000, sessionId: '...' }
// Refresh. Claims are carried over to the new pair.
const next = await jwt.rotate(pair.refreshToken)
// Or pass new claims, for example after a role change
const updated = await jwt.rotate(next.refreshToken, { sub: 'user-1', role: 'user' })
// Log out
await jwt.revoke(updated.refreshToken)
await jwt.revokeSession(pair.sessionId) // for example from an admin "log out this device" buttonexpiresIninrefreshis the refresh token lifetime (default'7d'). Each rotation starts it again.maxLifetimeis a hard limit for one login, no matter how often it is refreshed. After it,rotate()throwsJwtExpiredErrorand the user must log in again.
How it protects you:
- Each refresh token works once.
rotate()returns a new pair and the old token stops working. - If an old refresh token is used again (a sign that it was stolen), the whole session is revoked and
JwtReuseErroris thrown. Both the attacker and the user have to log in again. - Refresh tokens can't be used as access tokens. They have their own
typ(refresh+jwt) and audience, and no top-level user claims, soverify()here and any other JWT library that checks the audience reject them. Access tokens are rejected byrotate(). - Access tokens carry
sid(the session id), so you can look up or revoke sessions.
await jwt.rotate(pair.refreshToken) // used a second time: throws JwtReuseError, session is revokedThings to know:
- Logout is not instant for access tokens. After
revoke()or reuse detection, access tokens already issued stay valid until they expire. Keep them short (5-15 min), or checksidagainst your session store on sensitive routes. - Refresh once at a time. If two requests refresh with the same token at the same moment (two tabs, or a retry after a dropped response), the second counts as reuse and logs the session out. Make your client share one in-flight refresh (a single promise) and retry the original request with the result.
Refresh once at a time in the client
All callers wait for the same refresh request, so a refresh token is never sent twice:
let refreshing = null
function refreshTokens() {
refreshing ??= fetch('/auth/refresh', { method: 'POST', credentials: 'include' })
.then((res) => res.json())
.finally(() => { refreshing = null })
return refreshing
}Store refresh tokens on several servers
memoryStore() is fine for one server process. With several servers, implement RefreshStore on shared storage. rotate must be atomic (check the old value and write the new one in one step). Redis example:
const ROTATE = `
if redis.call('GET', KEYS[1]) == ARGV[1] then
redis.call('SET', KEYS[1], ARGV[2], 'EX', ARGV[3]) return 1
end
return 0`
const redisStore = {
create: (family, jti, ttl) => redis.set(`rt:${family}`, jti, 'EX', Math.ceil(ttl)),
rotate: async (family, expected, next, ttl) =>
(await redis.eval(ROTATE, 1, `rt:${family}`, expected, next, Math.ceil(ttl))) === 1,
revoke: (family) => redis.del(`rt:${family}`),
}
createJwt({ secret: process.env.JWT_SECRET, refresh: { store: redisStore } })SQL works too: UPDATE sessions SET jti = $next WHERE family = $family AND jti = $expected and check that one row changed.
A "family" is one login (the session id). jti is the id of the one refresh token that is valid for it right now.
Verify tokens in Express middleware
import express from 'express'
import { createJwt, JwtExpiredError, isJwtError } from 'jwtly'
const app = express()
const jwt = createJwt({ secret: process.env.JWT_SECRET, issuer: 'my-app' })
async function requireAuth(req, res, next) {
try {
req.user = await jwt.verify(req.headers.authorization) // "Bearer <token>" is fine
next()
} catch (err) {
if (err instanceof JwtExpiredError) return res.status(401).json({ error: 'token_expired' })
if (isJwtError(err)) return res.status(401).json({ error: err.code })
next(err)
}
}
app.get('/me', requireAuth, (req, res) => res.json({ id: req.user.sub }))A missing header also throws a JwtError (ERR_JWT_MALFORMED), so the user gets a 401.
Handle errors
Every error from jwtly is a JwtError with a stable code. Check the class with instanceof, or use isJwtError():
import { verify, JwtExpiredError, isJwtError } from 'jwtly'
try {
await verify(expiredToken, secret)
} catch (err) {
err instanceof JwtExpiredError // => true
isJwtError(err) // => true
isJwtError(err, 'ERR_JWT_EXPIRED') // => true
err.code // => 'ERR_JWT_EXPIRED'
err.expiredAt instanceof Date // => true
}In a web server, answer with 401 for any JwtError and rethrow other errors, as in the Express example. See Errors for all classes and codes.
Use public and private keys
With a key pair, only the auth service has the private key and can sign. Other services get the public key and can only verify.
import { createJwt, generateKeyPair } from 'jwtly'
const { privateKey, publicKey } = await generateKeyPair('EdDSA') // PEM strings
// Auth service: signs
const issuer = createJwt({ privateKey })
// Other services: verify only
const verifier = createJwt({ publicKey })
const token = await issuer.sign({ sub: '42' })
const claims = await verifier.verify(token)
claims.sub // => '42'Keys can be PEM strings (PKCS#8 / SPKI), JWK objects or CryptoKeys. The algorithm is inferred from the key, or set with algorithm. If you have an old BEGIN RSA PRIVATE KEY file, jwtly tells you the openssl command to convert it.
Pass key pairs as privateKey / publicKey, never as secret. See Security.
Choose an algorithm
The algorithm says how a token is signed. The number is the size of the hash (SHA-256, SHA-384 or SHA-512).
| Algorithm | Key | Notes |
|---|---|---|
| HS256, HS384, HS512 | Shared secret (HMAC) | Default for secret. The secret must be at least 32, 48 or 64 bytes. Both sides need the same secret. |
| RS256, RS384, RS512 | RSA key pair | Widely supported. Keys must be at least 2048 bits. |
| PS256, PS384, PS512 | RSA key pair (RSA-PSS signatures) | Same RSA keys, newer signature scheme. |
| ES256, ES384, ES512 | Elliptic curve key pair (P-256, P-384, P-521) | Small keys and signatures. |
| EdDSA | Ed25519 key pair | Small and fast. Default for generateKeyPair(). |
Use HS256 when one service signs and verifies. Use a key pair when other services must verify tokens but must not create them.
Rotate keys
List several keys, each with a kid. The first key with signing material signs new tokens. All keys verify, matched by the kid in the token header.
const jwt = createJwt({
keys: [
{ kid: '2026-11', privateKey: newKey }, // signs new tokens
{ kid: '2026-05', publicKey: oldPublic }, // still verifies old ones
],
})
app.get('/.well-known/jwks.json', async (req, res) => res.json(await jwt.jwks()))jwt.jwks() returns the public keys only. Remove an old key only after every token signed with it has expired. With refresh tokens, that is the refresh token lifetime, not only the access token lifetime.
Verify tokens from an identity provider
const jwt = createJwt({
jwks: 'https://YOUR_DOMAIN.auth0.com/.well-known/jwks.json',
issuer: 'https://YOUR_DOMAIN.auth0.com/',
audience: 'https://api.example.com',
})
const claims = await jwt.verify(req.headers.authorization)- The key set is cached for 10 minutes and refetched (rate-limited) when an unknown
kidappears. - If the provider is down, the last good key set is used for up to an hour (
jwksOptions: { staleIfError }). - HMAC tokens are never accepted against a JWKS.
- Set
issuerandaudience, so tokens made for other apps are rejected.
Lower-level: verify(token, remoteJwks(url), options). See remoteJwks.
Run on edge runtimes
jwtly uses only Web Crypto, so the same code runs in Cloudflare Workers, Vercel Edge, Deno and Bun. A Cloudflare Worker:
import { createJwt } from 'jwtly'
let jwt
export default {
async fetch(request, env) {
jwt ??= createJwt({ secret: env.JWT_SECRET, issuer: 'my-app' })
try {
const claims = await jwt.verify(request.headers.get('authorization'))
return Response.json({ user: claims.sub })
} catch {
return new Response('Unauthorized', { status: 401 })
}
},
}Use TypeScript types
Pass your claim types to verify() or createJwt():
const payload = await verify<{ role: 'admin' | 'user' }>(token, secret)
payload.role // type: 'admin' | 'user'
const jwt = createJwt<{ role: 'admin' | 'user' }>({ secret })
await jwt.sign({ sub: '42', role: 'owner' }) // compile error: 'owner' is not a roleAPI
createJwt(config)
function createJwt<Claims extends object = {}>(config: JwtConfig): Jwt<Claims>Creates a configured JWT helper. All tokens it signs are verified with the same rules. Throws JwtError (ERR_JWT_CONFIG) for an invalid config, for example when no key is given.
Pass exactly one key source: secret, privateKey and/or publicKey, keys, or jwks.
| Option | Type | Default | Description |
|---|---|---|---|
| secret | KeyInput | none | HMAC secret. At least 32 bytes for HS256. |
| privateKey | KeyInput | none | Private key (PEM, JWK or CryptoKey) for RS*, PS*, ES* or EdDSA. |
| publicKey | KeyInput | derived from privateKey | Public key to verify with. An instance with only a public key can verify but not sign. |
| keys | KeyEntry[] | none | Several keys for rotation: { kid, secret?, privateKey?, publicKey?, algorithm? }. The first one with signing material signs. All verify, matched by kid. |
| jwks | string \| URL \| JsonWebKeySet | none | Verify only: a JWKS URL (Auth0, Cognito, Google, ...) or a key set object. |
| jwksOptions | RemoteJwksOptions | see remoteJwks | Options for a remote jwks URL. |
| algorithm | Algorithm | inferred from the key | Signing algorithm. |
| algorithms | Algorithm[] | the key's algorithm | Allowed algorithms for jwks verification. |
| issuer | string | none | Written to tokens and required when verifying. |
| audience | string \| string[] | none | Written to tokens and required when verifying. |
| expiresIn | Duration | '15m' | Access token lifetime. |
| clockTolerance | Duration | '5s' | Allowed clock difference between servers. |
| refresh | object | none | Turns on issue(), rotate(), revoke() and revokeSession(). See below. |
refresh options:
| Option | Type | Default | Description |
|---|---|---|---|
| store | RefreshStore \| 'stateless' | required | Where refresh tokens are tracked for rotation and reuse detection: memoryStore() or your own store. 'stateless' turns off reuse detection and revocation (not recommended). |
| expiresIn | Duration | '7d' | Refresh token lifetime. Each rotation starts it again. |
| maxLifetime | Duration | none | Hard limit for one login, no matter how often it is refreshed. |
Jwt methods
| Method | Returns | Description |
|---|---|---|
| sign(payload, options?) | Promise<string> | Signs an access token with the configured key, issuer, audience and lifetime. options are sign options. |
| verify(token, options?) | Promise<JwtPayload & Claims> | Verifies an access token and returns its claims. Refresh tokens are rejected. options are verify options. |
| verifyComplete(token, options?) | Promise<DecodedJwt> | Like verify(), but returns { header, payload, signature }. |
| decode(token) | DecodedJwt | Reads a token without verifying it. Never use it for auth decisions. |
| issue(payload) | Promise<TokenPair> | Logs a user in: returns an access and refresh token pair. Needs refresh. |
| rotate(refreshToken, payload?) | Promise<TokenPair> | Swaps a refresh token for a new pair. The old refresh token stops working. If an old refresh token is used again, the whole session is revoked and JwtReuseError is thrown. Pass payload to set new claims; otherwise they are carried over. |
| revoke(refreshToken) | Promise<void> | Logs out the session that a refresh token belongs to. Expired refresh tokens work too. |
| revokeSession(sessionId) | Promise<void> | Logs out a session by its id (sessionId from issue(), or the sid claim). |
| jwks() | Promise<JsonWebKeySet> | Public keys as a JWKS, to serve at /.well-known/jwks.json. Asymmetric keys only; HMAC secrets are never included. |
revoke() and revokeSession() throw ERR_JWT_CONFIG with store: 'stateless'.
TokenPair, returned by issue() and rotate():
| Property | Type | Description |
|---|---|---|
| accessToken | string | The access token. Carries your claims and sid. |
| refreshToken | string | The refresh token. Send it only to your refresh endpoint. |
| tokenType | 'Bearer' | For OAuth-style responses. |
| expiresIn | number | Access token lifetime in seconds. |
| refreshExpiresIn | number | Refresh token lifetime in seconds. |
| sessionId | string | Identifies this login. Pass it to revokeSession(). |
sign(payload, key, options?)
function sign(payload: Record<string, unknown>, key: KeyInput, options?: SignOptions): Promise<string>Creates a signed JWT. payload must be a plain object. key is a secret (string or Uint8Array), a PEM string, a JWK or a CryptoKey. Setting a claim both in payload and in options (for example exp and expiresIn) throws.
Sign options
| Option | Type | Default | Description |
|---|---|---|---|
| algorithm | Algorithm | inferred from the key (HS256 for secrets) | Signing algorithm. |
| expiresIn | Duration | none (required) | Lifetime, for example '15m'. Required unless the payload has exp or allowNoExpiry is set. In createJwt, the configured expiresIn is the default. |
| notBefore | Duration | none | The token is not valid until this long from now. |
| issuer | string | none | Sets iss. |
| subject | string | none | Sets sub. |
| audience | string \| string[] | none | Sets aud. |
| jwtId | string \| true | none | Sets jti. true creates a random id. |
| keyId | string | none | kid in the header, for key rotation and JWKS. |
| type | string | 'JWT' | typ in the header. |
| header | Record<string, unknown> | none | Extra header fields. Cannot change alg. |
| allowNoExpiry | boolean | false | Allow tokens that never expire. You almost never want this. |
| timestamp | boolean | true | Add iat. |
| now | Date \| number | current time | Override the current time, for tests. |
verify(token, key, options?)
function verify<T extends object = {}>(
token: string,
key: KeyInput | KeyResolver,
options?: VerifyOptions,
): Promise<JwtPayload & T>Verifies a JWT and returns its payload. Throws a JwtError subclass on any problem. token may start with Bearer . key can also be a function (header) => key, such as remoteJwks() or localJwks().
Verify options
| Option | Type | Default | Description |
|---|---|---|---|
| algorithms | Algorithm[] | only the key's own algorithm | Allowed algorithms. none is never allowed. |
| issuer | string \| string[] | none | Required issuer (one of). |
| audience | string \| string[] | none | Required audience. The token must contain at least one. |
| subject | string | none | Required subject. |
| type | string | none | Required header typ, for example 'at+jwt'. |
| clockTolerance | Duration | '5s' | Allowed clock difference between servers. |
| maxAge | Duration | none | Reject tokens issued longer ago than this. Needs iat. |
| requireExpiry | boolean | true | Reject tokens without exp. |
| requiredClaims | string[] | none | Claims that must be present, for example ['sub', 'role']. |
| maxTokenLength | number | 16 KB | Reject larger tokens before doing any work. |
| now | Date \| number | current time | Override the current time, for tests. |
verifyComplete(token, key, options?)
function verifyComplete<T extends object = {}>(
token: string,
key: KeyInput | KeyResolver,
options?: VerifyOptions,
): Promise<DecodedJwt<T>>Like verify(), but returns { header, payload, signature }.
decode(token)
function decode<T extends object = {}>(token: string): DecodedJwt<T>Reads a token without verifying it. Never trust the result for auth decisions. Use it only to read the header (for example kid) or to show data in a UI.
remoteJwks(url, options?)
function remoteJwks(url: string | URL, options?: RemoteJwksOptions): KeyResolver & { reload(): Promise<JsonWebKeySet> }Loads public keys from a JWKS URL (Auth0, Cognito, Google, Clerk, Supabase, Keycloak, ...) for verify(). Caches the key set and refetches (rate-limited) when keys rotate. The URL must use https (except localhost). reload() fetches the key set now.
import { remoteJwks, verify } from 'jwtly'
const keys = remoteJwks('https://example.auth0.com/.well-known/jwks.json')
await verify(token, keys, { issuer: 'https://example.auth0.com/', audience: 'api' })| Option | Type | Default | Description |
|---|---|---|---|
| cacheTtl | Duration | '10m' | How long to cache the key set. |
| cooldown | Duration | '30s' | Minimum time between refetches when an unknown kid shows up. |
| timeout | Duration | '5s' | Request timeout. |
| staleIfError | Duration | '1h' | Keep using the last good key set this long after a refetch fails (provider outage). |
| fetch | typeof fetch | global fetch | Custom fetch, for proxies and tests. |
| headers | Record<string, string> | none | Extra request headers. |
localJwks(set)
function localJwks(set: JsonWebKeySet): KeyResolverVerifies tokens against a fixed key set, for example one loaded from a file. Pass the result to verify() as the key.
memoryStore()
function memoryStore(): RefreshStore & { readonly size: number; clear(): void }An in-memory refresh token store for development, tests and apps with one server process. Use a shared store (Redis, a database) when you run more than one server.
RefreshStore
interface RefreshStore {
create(family: string, jti: string, ttlSeconds: number): void | Promise<void>
rotate(family: string, expected: string, next: string, ttlSeconds: number): boolean | Promise<boolean>
revoke(family: string): void | Promise<void>
}Tracks the one valid refresh token per login ("family"). Implement it for Redis, a database, KV and so on. See Store refresh tokens on several servers.
| Method | Description |
|---|---|
| create | Start a new family whose current refresh token id is jti. |
| rotate | Atomically replace the current id expected with next. Return false if the family is unknown, revoked or expired, or its current id is not expected. |
| revoke | Remove a family (logout). |
generateSecret(bytes?)
function generateSecret(bytes?: number): stringCreates a strong random HMAC secret as a base64url string. The default is 64 bytes, enough for HS512.
generateKeyPair(alg?)
function generateKeyPair(
alg?: Exclude<Algorithm, 'HS256' | 'HS384' | 'HS512'>,
): Promise<{ privateKey: string; publicKey: string }>Creates a key pair as PEM strings for RS*, PS*, ES* or EdDSA. The default is 'EdDSA'. RSA keys are 2048 bits. For HS*, use generateSecret().
exportPublicJwk(key, alg, kid?)
function exportPublicJwk(key: KeyInput, alg: Algorithm, kid?: string): Promise<JsonWebKey & { kid?: string; alg: string; use: string }>Exports the public half of a key as a JWK, for example to publish at /.well-known/jwks.json. Throws for HMAC algorithms: secrets must never be published.
ALGORITHMS
A read-only object with details for each supported algorithm, for example ALGORITHMS.HS256 is { family: 'HMAC', hash: 'SHA-256', bytes: 32 }.
Errors
Every error is a JwtError with a stable code.
| Class | code | When |
|---|---|---|
| JwtMalformedError | ERR_JWT_MALFORMED | The token is not a well-formed JWT. |
| JwtAlgorithmError | ERR_JWT_ALG_NOT_ALLOWED | The token's alg is not allowed for this key (includes none). |
| JwtSignatureError | ERR_JWT_SIGNATURE_INVALID | The signature does not match: the token was changed or signed with another key. |
| JwtExpiredError (.expiredAt) | ERR_JWT_EXPIRED | The token has expired. |
| JwtNotActiveError (.activeAt) | ERR_JWT_NOT_ACTIVE | The token is not valid yet (nbf is in the future). |
| JwtClaimError (.claim) | ERR_JWT_CLAIM_INVALID | A claim (iss, aud, sub, iat, ...) is missing or wrong. |
| JwtReuseError | ERR_JWT_REUSED | A refresh token was used twice (likely stolen) or was revoked. Its whole session is now revoked. |
| JwtError | ERR_JWT_TYPE_INVALID, ERR_JWT_KEY_INVALID, ERR_JWT_KEY_NOT_FOUND, ERR_JWT_EXPIRY_REQUIRED, ERR_JWT_CONFIG, ERR_JWKS_FETCH | Wrong token type, bad key, no matching key, missing expiry, bad config, or a JWKS fetch failed. |
function isJwtError(error: unknown, code?: JwtErrorCode): error is JwtErrorisJwtError(err) is true if jwtly threw err. Pass a code to also check it, for example isJwtError(err, 'ERR_JWT_EXPIRED').
Durations
Duration is number | string. Numbers and strings with no unit are seconds (900, '900'). Strings with units work too: '30s', '15m', '1h 30m', '7d'.
Types
All types are exported:
Algorithm, DecodedJwt, Duration, JsonWebKeySet, Jwt, JwtConfig, JwtErrorCode, JwtHeader, JwtPayload, KeyEntry, KeyInput, KeyResolver, RefreshStore, RemoteJwksOptions, SignOptions, TokenPair, VerifyOptions.
Security
jwtly was reviewed before release. Every finding has a regression test in test/regressions.test.ts.
Safe defaults (you do not need to turn them on):
- The algorithm is pinned to your key.
alg: none(unsigned tokens) is always rejected.- Every token must expire.
sign()refuses tokens withoutexp, andverify()rejects them. - Secrets shorter than the hash size (32 bytes for
HS256) are rejected. RSA keys under 2048 bits are refused. - Public and private keys are never accepted as HMAC secrets. This blocks algorithm-confusion attacks.
- Refresh tokens are never accepted as access tokens.
- A reused refresh token revokes the whole session.
- HMAC tokens are never accepted against a JWKS.
What you should do:
- Use
generateSecret()(oropenssl rand -base64 64) for HMAC secrets. Secrets shorter than the hash size (32 bytes for HS256) are rejected. decode()does not verify. Never use it for authorization.- Pass asymmetric keys as
privateKey/publicKey, never assecret. jwtly refuses PEM, DER and JWK data used as an HMAC secret, which blocks algorithm-confusion attacks. - Keep access tokens short-lived (5-15 min) and use refresh tokens for long sessions.
- Logout is not instant for access tokens. After
revoke()or reuse detection, access tokens already issued stay valid until they expire. Keep them short (5-15 min), or checksidagainst your session store on sensitive routes. - Refresh once at a time in the client. A second refresh with the same token counts as reuse and logs the session out. See Refresh once at a time in the client.
- With several servers, use a shared
RefreshStorewhoserotateis atomic.memoryStore()is for one server process. - Do not use
store: 'stateless'unless you accept the cost: it turns off reuse detection and revocation. - Do not set
allowNoExpiryorrequireExpiry: falseunless you really need tokens that never expire.
Comparison
| | jsonwebtoken | jwtly |
|---|---|---|
| Edge runtimes, Bun, Deno, browser | No (needs Node crypto) | Yes |
| Async, non-blocking crypto | No (sync by default) | Yes |
| Algorithm pinned by default | No (you must pass algorithms) | Yes |
| Tokens must expire | No | Yes |
| Rejects short HMAC secrets | No | Yes |
| Refresh tokens and reuse detection | No | Yes |
| JWKS fetching | No (needs jwks-rsa) | Yes |
| TypeScript types | Separate @types package | Built in, generic claims |
| Dependencies | 10 | 0 |
Notes and limitations
- Logout is not instant for access tokens. They stay valid until they expire. See Security.
memoryStore()lives in one process. It is lost on restart and not shared between servers.- Encrypted tokens (JWE) are not supported, and neither are
critheader fields or unencoded payloads (b64: false). - Some key formats must be converted first: PKCS#1 (
BEGIN RSA PRIVATE KEY), SEC1 (BEGIN EC PRIVATE KEY), X.509 certificates and encrypted private keys. The error message gives you theopensslcommand. - Tokens over 16 KB are rejected by default. Change it with
maxTokenLength. - JWKS URLs must use
https(exceptlocalhost). - An RSA PEM key verifies
RS256by default. To acceptPS256tokens with the same key, setalgorithmincreateJwtor passalgorithmstoverify(). - Node.js 20 may print an
ExperimentalWarningwhen you useEdDSAkeys, because Ed25519 in Web Crypto was experimental in that version.
Requirements
- Node.js 20 or newer, or any runtime with Web Crypto: Bun, Deno, modern browsers, Cloudflare Workers and Vercel Edge.
- ESM and CommonJS.
- TypeScript types included.
- Zero dependencies.
License
MIT
