jsonwebtoken
JWT implementation for Node.js — sign, verify, and decode JSON Web Tokens for stateless authentication.
jsonwebtoken
Node.jsJWT implementation for Node.js — sign, verify, and decode JSON Web Tokens for stateless authentication.
Fit
Bundle (gzip)
16.1 kB
54.5 kB raw
Install size includes transitive dependencies. Bundle size is gzipped browser payload.
Freshness
The Problem
Stateless authentication requires creating tokens that encode user identity and can be cryptographically verified without a database lookup. Implementing JWT signing, expiry, and verification correctly from scratch is error-prone.
What It Does
jsonwebtoken signs payloads with HMAC or RSA, verifies tokens and returns the decoded payload (or throws if invalid/expired), and decodes tokens without verification for inspecting headers. It supports all standard JWT algorithms and claim verification (exp, iss, aud).
Installation
npm install jsonwebtoken
npm install -D @types/jsonwebtokenUsage Example
import jwt from 'jsonwebtoken';
const SECRET = process.env.JWT_SECRET!;
// Sign a token (e.g., at login)
const token = jwt.sign(
{ userId: user.id, role: user.role },
SECRET,
{ expiresIn: '7d' }
);
// Verify a token (e.g., in middleware)
function authenticate(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
try {
const payload = jwt.verify(token, SECRET) as { userId: string };
req.userId = payload.userId;
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
}Related packages
Role and attribute based access control (RBAC + ABAC) for Node.js with a fluent, readable API.
bcryptjsNode.jsPure JavaScript bcrypt password hashing — no native dependencies, same API as bcrypt, works anywhere Node.js runs.
bullmqNode.jsPremium message queue and job scheduler for Node.js backed by Redis — reliable background job processing with retries, priorities, and rate limiting.
casbinNode.jsA powerful authorization library that supports RBAC, ABAC, ACL and more via configurable policy models.
dotenvNode.jsLoad environment variables from a `.env` file into `process.env` — the standard way to manage configuration in Node.js apps.