JSON Web Token (JWT) Implementation

9.0.3 · active · verified Sat Apr 18

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.

Common errors

Warnings

Install

Imports

Quickstart

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);
}

view raw JSON →