{"id":10397,"library":"jsonwebtoken","title":"JSON Web Token (JWT) Implementation","description":"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.","status":"active","version":"9.0.3","language":"javascript","source_language":"en","source_url":"https://github.com/auth0/node-jsonwebtoken","tags":["javascript","jwt"],"install":[{"cmd":"npm install jsonwebtoken","lang":"bash","label":"npm"},{"cmd":"yarn add jsonwebtoken","lang":"bash","label":"yarn"},{"cmd":"pnpm add jsonwebtoken","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The `jsonwebtoken` package is a CommonJS module, but its exported functions like `sign` can be imported as named exports in an ESM context.","wrong":"const sign = require('jsonwebtoken').sign;","symbol":"sign","correct":"import { sign } from 'jsonwebtoken';"}],"quickstart":{"code":"import { sign } from 'jsonwebtoken';\n\nconst payload = {\n  userId: 'user123',\n  email: 'test@example.com'\n};\n\nconst secret = process.env.JWT_SECRET ?? 'your-very-strong-secret'; // Use a strong, secure secret in production\n\ntry {\n  // Synchronous signing example\n  const token = sign(payload, secret, { expiresIn: '1h' });\n  console.log('Signed JWT:', token);\n\n  // Asynchronous signing example\n  sign(payload, secret, { expiresIn: '1h' }, (err, asyncToken) => {\n    if (err) {\n      console.error('Async signing error:', err);\n      return;\n    }\n    console.log('Signed JWT (async):', asyncToken);\n  });\n} catch (error) {\n  console.error('Error signing token:', error);\n}","lang":"typescript","description":"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."},"warnings":[{"fix":"Always use an object literal as the `payload` when you expect claims like `exp`, `nbf`, `aud`, `iss`, or `sub` to be automatically managed.","message":"Claims 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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).","message":"When signing with RSA algorithms, private keys with a modulus length shorter than 2048 bits will be rejected by default, resulting in an error.","severity":"breaking","affected_versions":">=9.0.0"},{"fix":"Always provide explicit time units for string-based `expiresIn` and `notBefore` values (e.g., `'120s'`, `'2h'`, `'7d'`) or use numeric values in seconds.","message":"When `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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always explicitly define desired claims (e.g., `expiresIn: '1h'`) either in the `options` object or directly within the `payload` object.","message":"There 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"The `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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-18T00:00:00.000Z","next_check":"2026-07-17T00:00:00.000Z","problems":[{"fix":"Issue a new token with an updated expiration time, or refresh the token if using a refresh token mechanism.","cause":"The JWT has exceeded its 'exp' (expiration time) claim.","error":"TokenExpiredError: jwt expired"},{"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.","cause":"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.","error":"JsonWebTokenError: invalid signature"},{"fix":"Verify that the token string is complete, correctly encoded, and matches the 'header.payload.signature' structure of a JWT.","cause":"The provided string is not a valid JWT format (e.g., missing segments, incorrect base64 encoding).","error":"JsonWebTokenError: jwt malformed"},{"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.","cause":"The token's 'nbf' (not before) claim indicates it should not be accepted yet.","error":"NotBeforeError: jwt not active"},{"fix":"Provide a valid string, buffer, or KeyObject for `secretOrPrivateKey` during both signing and verification operations. For private keys with passphrases, use `{ key, passphrase }`.","cause":"The `secretOrPrivateKey` parameter was omitted or was an empty/invalid value during signing or verification.","error":"JsonWebTokenError: secret or public key must be provided"}],"ecosystem":"npm"}