Registry / auth-security / jsonwebtoken

jsonwebtoken

JSON →
library1.0.0jsnpmunverified

jsonwebtoken is a robust implementation of JSON Web Tokens (JWT) for Node.js, supporting both symmetric and asymmetric algorithms. The current stable version is 9.0.3. Maintained by Auth0, the library receives regular updates, as indicated by migration notes for recent major versions.

npm install jsonwebtoken
INSTALL
IMPORT
SIG · JSONWEBTOKEN
J
jsonwebtoken
auth-securityjavascriptv1.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

sign
import { sign } from 'jsonwebtoken';
const sign = require('jsonwebtoken').sign;
The `jsonwebtoken` package is a CommonJS module, but its exported functions like `sign` can be imported as named exports in an ESM context.

This quickstart demonstrates how to sign a JSON Web Token synchronously and asynchronously using a simple payload and a secret key, with an expiration time of one hour. It also shows basic error handling.

import { sign } from 'jsonwebtoken'; const payload = { userId: 'user123', email: 'test@example.com' }; const secret = process.env.JWT_SECRET ?? 'your-very-strong-secret'; // Use a strong, secure secret in production try { // Synchronous signing example const token = sign(payload, secret, { expiresIn: '1h' }); console.log('Signed JWT:', token); // Asynchronous signing example sign(payload, secret, { expiresIn: '1h' }, (err, asyncToken) => { if (err) { console.error('Async signing error:', err); return; } console.log('Signed JWT (async):', asyncToken); }); } catch (error) { console.error('Error signing token:', error); }
Debug
Known issues
gotchaClaims like `exp` (expiration time) are only set by the `sign` function if the `payload` parameter is an object literal. If you pass a buffer or string, these claims will not be added or validated.
fix
Always use an object literal as the `payload` when you expect claims like `exp`, `nbf`, `aud`, `iss`, or `sub` to be automatically managed.
affects: >=1.0.0
breakingWhen signing with RSA algorithms, private keys with a modulus length shorter than 2048 bits will be rejected by default, resulting in an error.
fix
Use RSA private keys with a modulus length of 2048 bits or greater. If absolutely necessary for backward compatibility in non-production environments, set the `allowInsecureKeySizes: true` option (not recommended).
affects: >=9.0.0
gotchaWhen `expiresIn` or `notBefore` options are provided as a string without a time unit (e.g., `'120'`), the value is interpreted as milliseconds, not seconds, leading to unexpectedly short token lifespans.
fix
Always provide explicit time units for string-based `expiresIn` and `notBefore` values (e.g., `'120s'`, `'2h'`, `'7d'`) or use numeric values in seconds.
affects: >=1.0.0
gotchaThere are no default values for common JWT claims such as `expiresIn`, `notBefore`, `audience`, `subject`, and `issuer`. If these are not explicitly provided, they will be omitted from the token.
fix
Always explicitly define desired claims (e.g., `expiresIn: '1h'`) either in the `options` object or directly within the `payload` object.
affects: >=1.0.0
gotchaThe `mutatePayload: true` option directly modifies the original `payload` object passed to `jwt.sign` by adding or overwriting claims (like `iat`, `exp`). This can cause unexpected side effects if the original payload object is reused.
fix
Avoid `mutatePayload: true` unless you explicitly intend for the payload object to be modified. If you need to inspect the payload after claims are added, consider making a copy of the payload before signing or using the returned token's decoded payload.
affects: >=1.0.0
Errors
Common errors & fixes
TokenExpiredError: jwt expired
The JWT has exceeded its 'exp' (expiration time) claim.
fix
Issue a new token with an updated expiration time, or refresh the token if using a refresh token mechanism.
JsonWebTokenError: invalid signature
The token's signature does not match the computed signature, likely due to a tampered token or an incorrect secret/public key used for verification.
fix
Ensure the same secret or public key (for asymmetric algorithms) that was used to sign the token is used to verify it. Check for any encoding issues with the key.
JsonWebTokenError: jwt malformed
The provided string is not a valid JWT format (e.g., missing segments, incorrect base64 encoding).
fix
Verify that the token string is complete, correctly encoded, and matches the 'header.payload.signature' structure of a JWT.
NotBeforeError: jwt not active
The token's 'nbf' (not before) claim indicates it should not be accepted yet.
fix
Wait until the 'nbf' time has passed before attempting to use or verify the token. Ensure the system clocks of the issuing and verifying servers are synchronized.
JsonWebTokenError: secret or public key must be provided
The `secretOrPrivateKey` parameter was omitted or was an empty/invalid value during signing or verification.
fix
Provide a valid string, buffer, or KeyObject for `secretOrPrivateKey` during both signing and verification operations. For private keys with passphrases, use `{ key, passphrase }`.
Upgrade
Version history
1.0.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
9 hits · last 30 days
node
8
OpenAI (training)
1
Resources
jsonwebtoken — npm install jsonwebtoken · libregistry