← Back to archive

Repo of the Day

auth0/node-jsonwebtoken

Published: Dec 30, 2024

Open repository ↗

JsonWebToken implementation for node.js http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html

Summary

node-jsonwebtoken is a JavaScript library for creating, signing, and verifying JSON Web Tokens (JWTs) in Node.js, published by Auth0 under the MIT license. It implements the JWT specification (RFC 7519) and uses node-jws for the underlying signing primitives. The library exposes three core functions: sign, verify, and decode.

What it is useful for

Engineers reach for this library when they need to issue or validate compact, signed tokens between services, such as authenticating API requests, transmitting short-lived claims between client and server, or implementing OAuth-style access and ID tokens. Because the same library handles both sides, it works on the issuing tier (a login service producing tokens with HMAC or RSA/ECDSA signatures) and on the consuming tier (an Express middleware checking an incoming bearer token). The async form of verify also accepts a getKey callback, which fits a JWKS-based setup where public keys are fetched from a remote endpoint.

How engineers can use it

Installation is documented as a single npm command:

npm install jsonwebtoken

Signing with a shared secret is one line:

var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, 'shhhhh');

For asymmetric keys, the README shows reading a PEM private key from disk and signing with RS256:

var privateKey = fs.readFileSync('private.key');
var token = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' });

Expiration can be set as an exp NumericDate in the payload, or through the expiresIn option, which accepts seconds or a vercel/ms string like "1h" or "7d". Other claim options include audience, issuer, subject, jwtid, and notBefore.

Verification is jwt.verify(token, secretOrPublicKey, [options], [callback]). Without options, a default algorithms list is inferred from the key type. Engineers can tighten this with algorithms: ['RS256'] to prevent algorithm confusion, and validate aud, iss, sub, and jti against expected values. The async form accepts a getKey(header, callback) function for fetching keys from a JWKS endpoint.

Two helpers are worth knowing. jwt.decode(token) returns the parsed payload without signature checks and is only safe for trusted tokens. jwt.verify can throw or surface a TokenExpiredError, NotBeforeError, or JsonWebTokenError with messages like "jwt expired", "jwt not active", "invalid signature", and "jwt malformed", so error handling can branch on err.name.

The README notes a limitation in its TODO list: X.509 certificate chain validation is not performed during verification, so engineers relying on X.509 trust paths will need to handle that separately.