jwt-lib
A minimal, production-minded JSON Web Token (JWT) implementation in Node.js supporting HS256 and RS256 algorithms. Built with the native crypto module, no external dependencies.
Features
- Sign and verify tokens using HMAC (HS256) or RSA (RS256)
- Constant-time signature comparison
- Standard claims validation (exp, nbf, iat, iss, aud, sub)
- Configurable clock tolerance and required claims
- Typed errors for fine-grained error handling
Learn more about HS256 and RS256 algorithms here: https://auth0.com/blog/rs256-vs-hs256-whats-the-difference/
Usage
HS256 Example
const { sign, verify } = require("./jwt");
const secret = "supersecret";
const payload = { userId: 123 };
const token = sign(payload, secret, { algorithm: "HS256", expiresIn: 60 });
console.log("Token:", token);
const decoded = verify(token, secret, { algorithms: ["HS256"] });
console.log("Decoded:", decoded);RS256 Example
const fs = require("fs");
const { sign, verify } = require("./jwt");
const privateKey = fs.readFileSync("./test/private.pem");
const publicKey = fs.readFileSync("./test/public.pem");
const payload = { userId: 456 };
const token = sign(payload, { privateKey }, { algorithm: "RS256", expiresIn: 60 });
console.log("Token:", token);
const decoded = verify(token, { publicKey }, { algorithms: ["RS256"] });
console.log("Decoded:", decoded);Security Note
DO NOT use the test/private.pem and test/public.pem keys in production. Always keep real private keys secure and out of source.