jsonwebtoken vs passport vs auth0-js vs oidc-client
JavaScript Authentication Libraries for Frontend and Backend
jsonwebtokenpassportauth0-jsoidc-clientSimilar Packages:
JavaScript Authentication Libraries for Frontend and Backend

auth0-js, jsonwebtoken, oidc-client, and passport are all related to authentication in JavaScript applications, but they operate in fundamentally different layers and contexts. auth0-js is a deprecated frontend SDK specifically for Auth0's authentication service. jsonwebtoken is a Node.js utility for signing and verifying JSON Web Tokens, intended for server-side use only. oidc-client is a deprecated generic OpenID Connect client for browsers, designed to work with any OIDC-compliant identity provider. passport is an actively maintained authentication middleware for Node.js applications, commonly used with Express to handle various authentication strategies like local credentials, JWT, or OAuth providers. Understanding where each package fits — frontend vs backend, generic vs provider-specific, and current vs deprecated status — is crucial for secure and maintainable architecture.

Npm Package Weekly Downloads Trend
3 Years
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
jsonwebtoken32,738,37618,14343.4 kB1852 months agoMIT
passport5,866,78623,511157 kB3932 years agoMIT
auth0-js223,6631,0418.46 MB18 days agoMIT
oidc-client156,7282,436-1165 years agoApache-2.0

Authentication and Authorization in JavaScript: auth0-js vs jsonwebtoken vs oidc-client vs passport

When building modern web applications, handling user identity securely is non-negotiable. The four packages — auth0-js, jsonwebtoken, oidc-client, and passport — all relate to authentication but serve very different roles in the stack. Confusing them leads to architectural mistakes, like using a low-level JWT utility for frontend login flows or trying to run a server-side strategy on the client. Let’s clarify where each belongs.

🧩 Core Responsibilities: What Each Package Actually Does

auth0-js: Frontend SDK for Auth0

auth0-js is a browser-only library provided by Auth0 to handle authentication flows with their platform. It wraps OAuth 2.0 and OpenID Connect (OIDC) protocols specifically for Auth0’s implementation. You use it to log users in via redirects or popups, get ID/access tokens, and manage sessions — but only if you’re using Auth0 as your identity provider.

// auth0-js: Login and get user info
import Auth0 from 'auth0-js';

const webAuth = new Auth0.WebAuth({
  domain: 'your-tenant.auth0.com',
  clientID: 'your-client-id',
  redirectUri: 'https://your-app.com/callback',
  responseType: 'token id_token'
});

webAuth.authorize(); // Redirects to Auth0 login

// Later, in callback handler:
webAuth.parseHash((err, authResult) => {
  if (!err) {
    const { idTokenPayload } = authResult;
    console.log('User:', idTokenPayload);
  }
});

⚠️ Important: This package is deprecated as of 2021. Auth0 recommends migrating to @auth0/auth0-spa-js for new projects. Avoid auth0-js in greenfield development.

jsonwebtoken: Low-Level JWT Encoding/Decoding

jsonwebtoken is a server-side (Node.js) utility for creating and verifying JSON Web Tokens. It has no knowledge of OAuth, OIDC, or browser flows. You use it when you need to mint tokens after validating credentials (e.g., in a custom login API) or validate tokens sent by clients.

// jsonwebtoken: Sign and verify tokens (Node.js only)
import jwt from 'jsonwebtoken';

// After validating username/password
const token = jwt.sign({ userId: 123 }, 'secret-key', { expiresIn: '1h' });

// Later, verify an incoming token
const decoded = jwt.verify(token, 'secret-key');
console.log(decoded.userId); // 123

❗ This package should never run in the browser. It requires access to secret keys, which would be exposed to users. Use it only in trusted backend environments.

oidc-client: Generic OIDC Client for Browsers

oidc-client is a frontend library that implements the OpenID Connect protocol generically — not tied to any specific provider like Auth0. It handles token storage, silent renewals, and PKCE flow, making it suitable for apps that need to integrate with any OIDC-compliant identity server (e.g., IdentityServer, Okta, Keycloak).

// oidc-client: Generic OIDC login
import { UserManager } from 'oidc-client';

const userManager = new UserManager({
  authority: 'https://your-oidc-server.com',
  client_id: 'your-client-id',
  redirect_uri: 'https://your-app.com/callback',
  response_type: 'code',
  scope: 'openid profile'
});

userManager.signinRedirect(); // Starts OIDC flow

// In callback page:
userManager.signinRedirectCallback().then(user => {
  console.log('Access token:', user.access_token);
});

⚠️ Important: As of 2023, oidc-client is deprecated. The maintainers recommend migrating to oidc-client-ts, a TypeScript rewrite with active support. Do not start new projects with oidc-client.

passport: Authentication Middleware for Node.js

passport is a server-side framework for authenticating requests in Express (or other Node.js web servers). It uses “strategies” (e.g., passport-local, passport-jwt, passport-google-oauth20) to handle different auth methods. It never runs in the browser — it processes credentials sent by frontend clients.

// passport: Local username/password strategy (Express.js)
import passport from 'passport';
import { Strategy as LocalStrategy } from 'passport-local';

passport.use(new LocalStrategy(
  async (username, password, done) => {
    const user = await db.findUser(username);
    if (!user || !verifyPassword(password, user.password)) {
      return done(null, false);
    }
    return done(null, user);
  }
));

// In route handler:
app.post('/login', 
  passport.authenticate('local', { session: false }),
  (req, res) => {
    // req.user is available here
    const token = jwt.sign({ id: req.user.id }, 'secret');
    res.json({ token });
  }
);

passport is actively maintained and widely used in Node.js backends. It’s not deprecated.

🖥️ Runtime Environment: Where Each Package Runs

PackageEnvironmentCan Run in Browser?Can Run in Node.js?
auth0-jsFrontend only✅ Yes❌ No
jsonwebtokenBackend only❌ No (unsafe)✅ Yes
oidc-clientFrontend only✅ Yes❌ No
passportBackend only❌ No✅ Yes

Mixing these up causes critical errors:

  • Putting jsonwebtoken in frontend code leaks secrets.
  • Trying to use passport in a React app does nothing — it needs an HTTP server.
  • Using auth0-js with a non-Auth0 provider won’t work.

🔐 Token Handling: Creation vs Consumption

  • Creating tokens: Only jsonwebtoken (on the server) should generate JWTs. Frontend libraries like auth0-js or oidc-client receive tokens from identity providers — they don’t create them.

  • Consuming tokens: Frontend apps use auth0-js or oidc-client to store tokens (in memory or secure cookies) and attach them to API requests. Backend APIs use passport (with passport-jwt) or direct jsonwebtoken.verify() calls to validate tokens.

// Backend: Verify token sent by frontend (using jsonwebtoken directly)
app.get('/protected', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  try {
    const decoded = jwt.verify(token, 'secret-key');
    res.json({ message: 'OK', user: decoded });
  } catch (err) {
    res.status(401).json({ error: 'Invalid token' });
  }
});
// Backend: Same thing, but with passport-jwt strategy
import { Strategy as JwtStrategy } from 'passport-jwt';

passport.use(new JwtStrategy({ secretOrKey: 'secret-key', jwtFromRequest: ... }, 
  (payload, done) => done(null, payload)
));

app.get('/protected', passport.authenticate('jwt', { session: false }), (req, res) => {
  res.json({ user: req.user });
});

🔄 Flow Integration: How They Fit Together

In a typical full-stack app:

  1. Frontend uses oidc-client-ts (successor to oidc-client) or @auth0/auth0-spa-js (successor to auth0-js) to authenticate the user and obtain tokens.
  2. Frontend sends the access token to your backend API in the Authorization header.
  3. Backend uses passport with passport-jwt (which internally uses jsonwebtoken) to validate the token and authorize the request.

You would never use auth0-js and passport in the same layer — one is frontend, the other backend.

🚫 Deprecation Status: What Not to Use

  • auth0-js: Deprecated. Use @auth0/auth0-spa-js instead.
  • oidc-client: Deprecated. Use oidc-client-ts instead.
  • jsonwebtoken: Actively maintained. Safe for backend use.
  • passport: Actively maintained. Standard in Node.js auth.

If you’re starting a new project:

  • For frontend OIDC, pick oidc-client-ts (generic) or @auth0/auth0-spa-js (Auth0-specific).
  • For backend token handling, use passport + strategies or jsonwebtoken directly.

💡 Summary: When to Use What

ScenarioRecommended Package(s)
Building a React app with Auth0@auth0/auth0-spa-js (not auth0-js)
Building a React app with any OIDC provideroidc-client-ts (not oidc-client)
Validating JWTs in a Node.js APIpassport + passport-jwt or jsonwebtoken
Creating custom JWTs after loginjsonwebtoken (server only)
Implementing username/password login backendpassport + passport-local

Choose based on layer (frontend vs backend) and protocol (generic OIDC vs Auth0-specific). Never mix responsibilities — keep token creation on the server, and leave browser flows to dedicated frontend SDKs.

How to Choose: jsonwebtoken vs passport vs auth0-js vs oidc-client
  • jsonwebtoken:

    Choose jsonwebtoken when you need to programmatically sign or verify JWTs in a Node.js backend environment — for example, issuing tokens after successful login or validating tokens in protected API routes. Never use it in frontend code, as it requires access to secret keys that must remain confidential. It’s a low-level tool; pair it with frameworks like Express or authentication middleware like Passport for complete solutions.

  • passport:

    Choose passport when building a Node.js backend (typically with Express) that needs flexible, strategy-based authentication — such as supporting local username/password, social logins (Google, GitHub), or JWT validation. It’s a mature, well-tested middleware that handles request authentication cleanly. Remember, Passport runs only on the server; it should never be included in frontend bundles.

  • auth0-js:

    Avoid auth0-js in new projects — it is officially deprecated by Auth0. If you're integrating with Auth0 specifically, use its modern replacement @auth0/auth0-spa-js, which offers better security (PKCE by default), smaller bundle size, and ongoing support. Only consider legacy auth0-js if maintaining an old application that hasn't been migrated yet.

  • oidc-client:

    Do not use oidc-client for new development — it is deprecated and no longer maintained. Instead, adopt its official successor oidc-client-ts, which provides the same generic OpenID Connect functionality with TypeScript support and active updates. Use this family of libraries only when you need a standards-compliant OIDC client for the browser that works with any identity provider like IdentityServer, Okta, or Keycloak.

README for jsonwebtoken

jsonwebtoken

BuildDependency
Build StatusDependency Status

An implementation of JSON Web Tokens.

This was developed against draft-ietf-oauth-json-web-token-08. It makes use of node-jws

Install

$ npm install jsonwebtoken

Migration notes

Usage

jwt.sign(payload, secretOrPrivateKey, [options, callback])

(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 exp or any other claim is only set if the payload is an object literal. Buffer or string payloads are not checked for JSON validity.

If payload is not a buffer or a string, it will be coerced into a string using JSON.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").

  • audience
  • issuer
  • jwtid
  • subject
  • noTimestamp
  • header
  • keyid
  • mutatePayload: 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 RSA
  • 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.

There are no default values for expiresIn, notBefore, audience, subject, issuer. These claims can also be provided in the payload directly with exp, nbf, aud, sub and iss respectively, 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');

Token Expiration (exp claim)

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

jwt.verify(token, secretOrPublicKey, [options, callback])

(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 here
  • clockTolerance: number of seconds to tolerate when checking the nbf and exp claims, to deal with small clock differences among different servers
  • maxAge: 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
});

Need to peek into a JWT without verifying it? (Click to expand)

jwt.decode(token [, options])

(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.verify instead.

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)

Errors & Codes

Possible thrown errors during verification. Error is the first argument of the verification callback.

TokenExpiredError

Thrown error if the token is expired.

Error object:

  • name: 'TokenExpiredError'
  • message: 'jwt expired'
  • expiredAt: [ExpDate]
jwt.verify(token, 'shhhhh', function(err, decoded) {
  if (err) {
    /*
      err = {
        name: 'TokenExpiredError',
        message: 'jwt expired',
        expiredAt: 1408621000
      }
    */
  }
});

JsonWebTokenError

Error object:

  • name: 'JsonWebTokenError'
  • message:
    • 'invalid token' - the header or payload could not be parsed
    • 'jwt malformed' - the token does not have three components (delimited by a .)
    • 'jwt signature is required'
    • 'invalid signature'
    • 'jwt audience invalid. expected: [OPTIONS AUDIENCE]'
    • 'jwt issuer invalid. expected: [OPTIONS ISSUER]'
    • 'jwt id invalid. expected: [OPTIONS JWT ID]'
    • 'jwt subject invalid. expected: [OPTIONS SUBJECT]'
jwt.verify(token, 'shhhhh', function(err, decoded) {
  if (err) {
    /*
      err = {
        name: 'JsonWebTokenError',
        message: 'jwt malformed'
      }
    */
  }
});

NotBeforeError

Thrown if current time is before the nbf claim.

Error object:

  • name: 'NotBeforeError'
  • message: 'jwt not active'
  • date: 2018-10-04T16:10:44.000Z
jwt.verify(token, 'shhhhh', function(err, decoded) {
  if (err) {
    /*
      err = {
        name: 'NotBeforeError',
        message: 'jwt not active',
        date: 2018-10-04T16:10:44.000Z
      }
    */
  }
});

Algorithms supported

Array of supported algorithms. The following algorithms are currently supported.

alg Parameter ValueDigital Signature or MAC Algorithm
HS256HMAC using SHA-256 hash algorithm
HS384HMAC using SHA-384 hash algorithm
HS512HMAC using SHA-512 hash algorithm
RS256RSASSA-PKCS1-v1_5 using SHA-256 hash algorithm
RS384RSASSA-PKCS1-v1_5 using SHA-384 hash algorithm
RS512RSASSA-PKCS1-v1_5 using SHA-512 hash algorithm
PS256RSASSA-PSS using SHA-256 hash algorithm (only node ^6.12.0 OR >=8.0.0)
PS384RSASSA-PSS using SHA-384 hash algorithm (only node ^6.12.0 OR >=8.0.0)
PS512RSASSA-PSS using SHA-512 hash algorithm (only node ^6.12.0 OR >=8.0.0)
ES256ECDSA using P-256 curve and SHA-256 hash algorithm
ES384ECDSA using P-384 curve and SHA-384 hash algorithm
ES512ECDSA using P-521 curve and SHA-512 hash algorithm
noneNo digital signature or MAC value included

Refreshing JWTs

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.

TODO

  • X.509 certificate chain is not checked

Issue Reporting

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.

Author

Auth0

License

This project is licensed under the MIT license. See the LICENSE file for more info.