express-jwt, jose, jsonwebtoken, jwa, and passport-jwt are npm packages used for handling JSON Web Tokens (JWTs) in Node.js applications. They provide utilities for signing, verifying, and managing JWT-based authentication, but differ significantly in scope, standards compliance, and integration patterns. jsonwebtoken is a general-purpose JWT library, jose offers modern, spec-compliant JWT/JWS/JWE support, jwa provides low-level cryptographic primitives, while express-jwt and passport-jwt are framework-specific middleware layers built on top of other JWT libraries for Express and Passport.js respectively.
When building secure web applications with JSON Web Tokens (JWTs), choosing the right library is critical—not just for correctness, but for maintainability, standards compliance, and long-term security. The five packages under review—express-jwt, jose, jsonwebtoken, jwa, and passport-jwt—serve overlapping but distinct roles in the JWT ecosystem. Let’s unpack how they differ in practice.
Not all JWT libraries do the same thing. Some focus on signing/verifying tokens, others act as Express middleware, and one integrates tightly with Passport authentication.
jsonwebtoken: The Swiss Army KnifeThis is the most widely used general-purpose JWT library. It handles both signing and verifying tokens using symmetric (HMAC) or asymmetric (RSA/ECDSA) algorithms.
// Signing a token
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 123 }, 'secret', { expiresIn: '1h' });
// Verifying a token
const payload = jwt.verify(token, 'secret');
It supports standard claims (exp, nbf, aud, etc.) and custom options like clock tolerance.
jose: Modern, Standards-Compliant, and Flexiblejose implements current IETF standards (RFC 7515–7519, RFC 8037) and supports JWS, JWE, JWT, and JWK. It works in both Node.js and browsers, and offers fine-grained control over cryptographic operations.
// Signing with jose (v4+)
import { SignJWT } from 'jose';
const secret = new TextEncoder().encode('secret');
const token = await new SignJWT({ userId: 123 })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime('1h')
.sign(secret);
// Verifying
import { jwtVerify } from 'jose';
const { payload } = await jwtVerify(token, secret);
Unlike jsonwebtoken, jose requires explicit header declaration and uses modern WebCrypto-style APIs.
jwa: Low-Level Algorithm Wrapperjwa is a minimal utility that only computes JWA (JSON Web Algorithms) signatures. It doesn’t handle JWT structure, claims validation, or expiration—it just signs and verifies raw payloads.
const jwa = require('jwa');
const hmac = jwa('HS256');
const signature = hmac.sign('header.payload', 'secret');
const isValid = hmac.verify('header.payload', signature, 'secret');
You’d typically use this only if you’re building your own JWT implementation from scratch—which you probably shouldn’t.
express-jwt: Express Middleware for VerificationThis package is not a JWT signer. It’s an Express middleware that verifies incoming tokens and attaches the decoded payload to req.user.
const express = require('express');
const jwt = require('express-jwt');
const app = express();
app.use(jwt({ secret: 'secret', algorithms: ['HS256'] }));
app.get('/protected', (req, res) => {
// req.user contains decoded token
res.json({ user: req.user });
});
Note: As of 2023, express-jwt wraps jsonwebtoken internally for verification.
passport-jwt: Passport Strategy for JWTThis is a Passport.js strategy that extracts and verifies JWTs, integrating with Passport’s authentication flow.
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
passport.use(new JwtStrategy({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'secret'
}, (payload, done) => {
// payload is decoded token
User.findById(payload.userId, (err, user) => {
if (err) return done(err, false);
if (user) return done(null, user);
else return done(null, false);
});
}));
It delegates actual verification to jsonwebtoken.
jsonwebtoken: Supports HS256/384/512, RS256/384/512, ES256/384/512, PS256/384/512. Uses Node.js crypto module.jose: Full JWA support including EdDSA (Ed25519), and JWE encryption (which jsonwebtoken lacks entirely).jwa: Only signing/verification primitives—no high-level JWT logic.express-jwt / passport-jwt: Inherit algorithm support from jsonwebtoken.jose strictly follows latest IETF specs and avoids legacy or non-standard extensions.jsonwebtoken includes some non-standard features (e.g., jwt.decode(token, { complete: true }) returns header + payload + signature), which can be useful but may encourage anti-patterns.jwa is standards-compliant at the algorithm level but doesn’t enforce JWT structure rules.Older JWT libraries were vulnerable to the "alg": "none" attack. All current versions of these packages reject none by default unless explicitly allowed.
jsonwebtoken: Throws error if none is used without { algorithms: ['none'] }.jose: Requires explicit opt-in via { allowInsecureAlgorithm: true } in jwtVerify.express-jwt: Forces you to specify algorithms array—preventing accidental none acceptance.// express-jwt forces algorithm whitelist
app.use(jwt({ secret: 'secret', algorithms: ['HS256'] })); // ✅ safe
jose encourages use of Uint8Array secrets or KeyObject instances, aligning with modern crypto best practices.jsonwebtoken accepts strings or buffers, which can lead to encoding issues if not handled carefully.If you need to issue and verify tokens, you’ll likely combine tools:
jsonwebtoken or jose to sign tokens during login.express-jwt or passport-jwt to protect routes.Example with jsonwebtoken + express-jwt:
// Login route (issuing token)
app.post('/login', (req, res) => {
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '1d' });
res.json({ token });
});
// Protected route (verifying token)
app.use('/api', expressJwt({ secret: process.env.JWT_SECRET, algorithms: ['HS256'] }));
With jose, you’d write your own middleware since no official Express wrapper exists:
async function jwtMiddleware(req, res, next) {
const auth = req.headers.authorization;
if (!auth || !auth.startsWith('Bearer ')) return res.sendStatus(401);
try {
const token = auth.substring(7);
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
const { payload } = await jwtVerify(token, secret);
req.user = payload;
next();
} catch (err) {
res.sendStatus(401);
}
}
jwa alone for JWT handling—it’s too low-level and error-prone.express-jwt if you’re not using Express—it’s framework-specific.passport-jwt unless you’re already using Passport.js—it adds unnecessary complexity otherwise.jose is actively maintained, supports modern JavaScript (ESM, TypeScript), and aligns with web platform standards. It’s the best choice for new projects requiring strong standards compliance.jsonwebtoken remains stable and widely used, but development has slowed. Still safe for most use cases.express-jwt and passport-jwt are wrapper libraries—their health depends on jsonwebtoken. Both are maintained but offer no advantage if you don’t need their specific integration.jwa is stable but niche; unlikely to see major updates.| Package | Primary Role | Signs Tokens? | Verifies Tokens? | Framework Integration | Standards Compliance |
|---|---|---|---|---|---|
jsonwebtoken | General-purpose JWT utility | ✅ | ✅ | None | Good (with quirks) |
jose | Modern, spec-compliant JWT/JWS/JWE | ✅ | ✅ | None | Excellent |
jwa | Low-level JWA algorithm helper | ✅ (raw) | ✅ (raw) | None | Algorithm-level only |
express-jwt | Express middleware for JWT | ❌ | ✅ (via jsonwebtoken) | Express only | Inherits from jsonwebtoken |
passport-jwt | Passport strategy for JWT | ❌ | ✅ (via jsonwebtoken) | Passport.js only | Inherits from jsonwebtoken |
jose—it’s future-proof, secure by default, and works everywhere.jsonwebtoken + express-jwt is battle-tested and sufficient.passport-jwt integrates cleanly.jwa unless you’re implementing a custom JWT parser.Remember: JWT libraries are security-critical dependencies. Always pin versions, audit regularly, and prefer libraries that enforce safe defaults over those that offer “convenience” at the cost of correctness.
Choose jsonwebtoken if you need a battle-tested, straightforward library for signing and verifying basic JWTs with HMAC or RSA signatures. It’s widely adopted and integrates easily with many frameworks, but lacks support for JWE encryption and includes some non-standard features that can encourage anti-patterns. Still a solid choice for simple authentication flows in existing systems.
Choose express-jwt if you're building an Express application and need a simple, ready-made middleware to verify JWTs from incoming requests. It automatically decodes tokens and attaches payloads to req.user, but relies on jsonwebtoken under the hood—so you still need to manage secrets and algorithms carefully. Avoid it if you're not using Express or need advanced JWT features like encryption.
Choose jose for new projects where standards compliance, security, and future-proofing matter most. It fully implements current IETF JWT, JWS, and JWE specifications, supports modern cryptographic algorithms (including EdDSA), and works in both Node.js and browsers. Its API is more verbose but enforces safe practices. Ideal when you need encryption (JWE) or want to avoid legacy design choices found in older libraries.
Choose jwa only if you're implementing a custom JWT parser or need direct access to JWA signing/verification primitives without higher-level abstractions. It handles cryptographic operations but doesn't manage JWT structure, claims validation, or expiration logic. For almost all real-world applications, higher-level libraries like jsonwebtoken or jose are safer and more productive choices.
Choose passport-jwt if your application already uses Passport.js for authentication and you want to add JWT support within Passport's strategy-based architecture. It handles token extraction and verification (via jsonwebtoken) and integrates with Passport's user serialization flow. Don't use it if you're not committed to Passport.js—it adds unnecessary complexity otherwise.
| Build | Dependency |
|---|---|
An implementation of JSON Web Tokens.
This was developed against draft-ietf-oauth-json-web-token-08. It makes use of node-jws
$ npm install jsonwebtoken
(Asynchronous) If a callback is supplied, the callback is called with the err or the JWT.
(Synchronous) Returns the JsonWebToken as string
payload could be an object literal, buffer or string representing valid JSON.
Please note that
expor any other claim is only set if the payload is an object literal. Buffer or string payloads are not checked for JSON validity.
If
payloadis not a buffer or a string, it will be coerced into a string usingJSON.stringify.
secretOrPrivateKey is a string (utf-8 encoded), buffer, object, or KeyObject containing either the secret for HMAC algorithms or the PEM
encoded private key for RSA and ECDSA. In case of a private key with passphrase an object { key, passphrase } can be used (based on crypto documentation), in this case be sure you pass the algorithm option.
When signing with RSA algorithms the minimum modulus length is 2048 except when the allowInsecureKeySizes option is set to true. Private keys below this size will be rejected with an error.
options:
algorithm (default: HS256)expiresIn: expressed in seconds or a string describing a time span vercel/ms.
Eg:
60,"2 days","10h","7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120"is equal to"120ms").
notBefore: expressed in seconds or a string describing a time span vercel/ms.
Eg:
60,"2 days","10h","7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120"is equal to"120ms").
audienceissuerjwtidsubjectnoTimestampheaderkeyidmutatePayload: if true, the sign function will modify the payload object directly. This is useful if you need a raw reference to the payload after claims have been applied to it but before it has been encoded into a token.allowInsecureKeySizes: if true allows private keys with a modulus below 2048 to be used for RSAallowInvalidAsymmetricKeyTypes: if true, allows asymmetric keys which do not match the specified algorithm. This option is intended only for backwards compatability and should be avoided.There are no default values for
expiresIn,notBefore,audience,subject,issuer. These claims can also be provided in the payload directly withexp,nbf,aud,subandissrespectively, but you can't include in both places.
Remember that exp, nbf and iat are NumericDate, see related Token Expiration (exp claim)
The header can be customized via the options.header object.
Generated jwts will include an iat (issued at) claim by default unless noTimestamp is specified. If iat is inserted in the payload, it will be used instead of the real timestamp for calculating other things like exp given a timespan in options.expiresIn.
Synchronous Sign with default (HMAC SHA256)
var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, 'shhhhh');
Synchronous Sign with RSA SHA256
// sign with RSA SHA256
var privateKey = fs.readFileSync('private.key');
var token = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' });
Sign asynchronously
jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' }, function(err, token) {
console.log(token);
});
Backdate a jwt 30 seconds
var older_token = jwt.sign({ foo: 'bar', iat: Math.floor(Date.now() / 1000) - 30 }, 'shhhhh');
The standard for JWT defines an exp claim for expiration. The expiration is represented as a NumericDate:
A JSON numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds. This is equivalent to the IEEE Std 1003.1, 2013 Edition [POSIX.1] definition "Seconds Since the Epoch", in which each day is accounted for by exactly 86400 seconds, other than that non-integer values can be represented. See RFC 3339 [RFC3339] for details regarding date/times in general and UTC in particular.
This means that the exp field should contain the number of seconds since the epoch.
Signing a token with 1 hour of expiration:
jwt.sign({
exp: Math.floor(Date.now() / 1000) + (60 * 60),
data: 'foobar'
}, 'secret');
Another way to generate a token like this with this library is:
jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: 60 * 60 });
//or even better:
jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: '1h' });
(Asynchronous) If a callback is supplied, function acts asynchronously. The callback is called with the decoded payload if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will be called with the error.
(Synchronous) If a callback is not supplied, function acts synchronously. Returns the payload decoded if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will throw the error.
Warning: When the token comes from an untrusted source (e.g. user input or external requests), the returned decoded payload should be treated like any other user input; please make sure to sanitize and only work with properties that are expected
token is the JsonWebToken string
secretOrPublicKey is a string (utf-8 encoded), buffer, or KeyObject containing either the secret for HMAC algorithms, or the PEM
encoded public key for RSA and ECDSA.
If jwt.verify is called asynchronous, secretOrPublicKey can be a function that should fetch the secret or public key. See below for a detailed example
As mentioned in this comment, there are other libraries that expect base64 encoded secrets (random bytes encoded using base64), if that is your case you can pass Buffer.from(secret, 'base64'), by doing this the secret will be decoded using base64 and the token verification will use the original random bytes.
options
algorithms: List of strings with the names of the allowed algorithms. For instance, ["HS256", "HS384"].
If not specified a defaults will be used based on the type of key provided
- secret - ['HS256', 'HS384', 'HS512']
- rsa - ['RS256', 'RS384', 'RS512']
- ec - ['ES256', 'ES384', 'ES512']
- default - ['RS256', 'RS384', 'RS512']
audience: if you want to check audience (aud), provide a value here. The audience can be checked against a string, a regular expression or a list of strings and/or regular expressions.
Eg:
"urn:foo",/urn:f[o]{2}/,[/urn:f[o]{2}/, "urn:bar"]
complete: return an object with the decoded { payload, header, signature } instead of only the usual content of the payload.issuer (optional): string or array of strings of valid values for the iss field.jwtid (optional): if you want to check JWT ID (jti), provide a string value here.ignoreExpiration: if true do not validate the expiration of the token.ignoreNotBefore...subject: if you want to check subject (sub), provide a value hereclockTolerance: number of seconds to tolerate when checking the nbf and exp claims, to deal with small clock differences among different serversmaxAge: the maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span vercel/ms.
Eg:
1000,"2 days","10h","7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120"is equal to"120ms").
clockTimestamp: the time in seconds that should be used as the current time for all necessary comparisons.nonce: if you want to check nonce claim, provide a string value here. It is used on Open ID for the ID Tokens. (Open ID implementation notes)allowInvalidAsymmetricKeyTypes: if true, allows asymmetric keys which do not match the specified algorithm. This option is intended only for backwards compatability and should be avoided.// verify a token symmetric - synchronous
var decoded = jwt.verify(token, 'shhhhh');
console.log(decoded.foo) // bar
// verify a token symmetric
jwt.verify(token, 'shhhhh', function(err, decoded) {
console.log(decoded.foo) // bar
});
// invalid token - synchronous
try {
var decoded = jwt.verify(token, 'wrong-secret');
} catch(err) {
// err
}
// invalid token
jwt.verify(token, 'wrong-secret', function(err, decoded) {
// err
// decoded undefined
});
// verify a token asymmetric
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, function(err, decoded) {
console.log(decoded.foo) // bar
});
// verify audience
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) {
// if audience mismatch, err == invalid audience
});
// verify issuer
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) {
// if issuer mismatch, err == invalid issuer
});
// verify jwt id
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid' }, function(err, decoded) {
// if jwt id mismatch, err == invalid jwt id
});
// verify subject
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid', subject: 'subject' }, function(err, decoded) {
// if subject mismatch, err == invalid subject
});
// alg mismatch
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { algorithms: ['RS256'] }, function (err, payload) {
// if token alg != RS256, err == invalid signature
});
// Verify using getKey callback
// Example uses https://github.com/auth0/node-jwks-rsa as a way to fetch the keys.
var jwksClient = require('jwks-rsa');
var client = jwksClient({
jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json'
});
function getKey(header, callback){
client.getSigningKey(header.kid, function(err, key) {
var signingKey = key.publicKey || key.rsaPublicKey;
callback(null, signingKey);
});
}
jwt.verify(token, getKey, options, function(err, decoded) {
console.log(decoded.foo) // bar
});
(Synchronous) Returns the decoded payload without verifying if the signature is valid.
Warning: This will not verify whether the signature is valid. You should not use this for untrusted messages. You most likely want to use
jwt.verifyinstead.
Warning: When the token comes from an untrusted source (e.g. user input or external request), the returned decoded payload should be treated like any other user input; please make sure to sanitize and only work with properties that are expected
token is the JsonWebToken string
options:
json: force JSON.parse on the payload even if the header doesn't contain "typ":"JWT".complete: return an object with the decoded payload and header.Example
// get the decoded payload ignoring signature, no secretOrPrivateKey needed
var decoded = jwt.decode(token);
// get the decoded payload and header
var decoded = jwt.decode(token, {complete: true});
console.log(decoded.header);
console.log(decoded.payload)
Possible thrown errors during verification. Error is the first argument of the verification callback.
Thrown error if the token is expired.
Error object:
jwt.verify(token, 'shhhhh', function(err, decoded) {
if (err) {
/*
err = {
name: 'TokenExpiredError',
message: 'jwt expired',
expiredAt: 1408621000
}
*/
}
});
Error object:
.)jwt.verify(token, 'shhhhh', function(err, decoded) {
if (err) {
/*
err = {
name: 'JsonWebTokenError',
message: 'jwt malformed'
}
*/
}
});
Thrown if current time is before the nbf claim.
Error object:
jwt.verify(token, 'shhhhh', function(err, decoded) {
if (err) {
/*
err = {
name: 'NotBeforeError',
message: 'jwt not active',
date: 2018-10-04T16:10:44.000Z
}
*/
}
});
Array of supported algorithms. The following algorithms are currently supported.
| alg Parameter Value | Digital Signature or MAC Algorithm |
|---|---|
| HS256 | HMAC using SHA-256 hash algorithm |
| HS384 | HMAC using SHA-384 hash algorithm |
| HS512 | HMAC using SHA-512 hash algorithm |
| RS256 | RSASSA-PKCS1-v1_5 using SHA-256 hash algorithm |
| RS384 | RSASSA-PKCS1-v1_5 using SHA-384 hash algorithm |
| RS512 | RSASSA-PKCS1-v1_5 using SHA-512 hash algorithm |
| PS256 | RSASSA-PSS using SHA-256 hash algorithm (only node ^6.12.0 OR >=8.0.0) |
| PS384 | RSASSA-PSS using SHA-384 hash algorithm (only node ^6.12.0 OR >=8.0.0) |
| PS512 | RSASSA-PSS using SHA-512 hash algorithm (only node ^6.12.0 OR >=8.0.0) |
| ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm |
| ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm |
| ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm |
| none | No digital signature or MAC value included |
First of all, we recommend you to think carefully if auto-refreshing a JWT will not introduce any vulnerability in your system.
We are not comfortable including this as part of the library, however, you can take a look at this example to show how this could be accomplished. Apart from that example there are an issue and a pull request to get more knowledge about this topic.
If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
This project is licensed under the MIT license. See the LICENSE file for more info.