auth0 (specifically the auth0 and auth0-next SDKs) and passport represent two fundamentally different approaches to securing applications. auth0 is the official SDK for the Auth0 Identity Platform, a managed SaaS solution that handles user storage, social login connections, and complex security protocols (like MFA and breach detection) off your servers. It focuses on redirect-based flows (OIDC/OAuth2) where the identity provider manages the session. passport, conversely, is a modular authentication middleware for Node.js. It is not a service but a toolkit that allows you to plug in over 500 different strategies (Local, Google, Facebook, JWT, etc.) directly into your Express or Koa application. With passport, you retain full control over the authentication logic and user database, but you also bear the responsibility of implementing secure session management, password hashing, and protocol compliance.
Authentication is one of the most critical parts of any application, yet it is also one of the most dangerous to build from scratch. The choice between the auth0 SDK and passport isn't just about picking a library; it's a decision between buying a managed service versus building a custom solution. Let's break down how they differ in real-world engineering scenarios.
auth0 acts as your bridge to a managed identity platform.
// auth0: Initializing the client for a Next.js app
import { initAuth0 } from '@auth0/nextjs-auth0';
export const auth0 = initAuth0({
baseURL: 'https://your-app.com',
clientID: process.env.AUTH0_CLIENT_ID,
clientSecret: process.env.AUTH0_CLIENT_SECRET,
issuerBaseURL: 'https://your-tenant.auth0.com'
});
// Usage in an API route to handle login
export default async function login(req, res) {
try {
await auth0.handleLogin(req, res);
} catch (error) {
res.status(error.status || 500).end(error.message);
}
}
passport is a collection of middleware functions you assemble yourself.
// passport: Setting up a local strategy in Express
import passport from 'passport';
import { Strategy as LocalStrategy } from 'passport-local';
passport.use(new LocalStrategy(
async function(username, password, done) {
// You must write the DB query yourself
const user = await db.users.findOne({ username });
if (!user) { return done(null, false); }
// You must verify the hash yourself
const isValid = await bcrypt.compare(password, user.hash);
if (!isValid) { return done(null, false); }
return done(null, user);
}
));
// Usage in a route
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
(req, res) => res.redirect('/dashboard')
);
auth0 treats social providers as toggle switches in a dashboard.
// auth0: The code remains identical regardless of provider
// The 'connection' parameter determines the social provider
export default async function login(req, res) {
await auth0.handleLogin(req, res, {
authorizationParams: { connection: 'google-oauth2' } // Or 'github', 'facebook'
});
}
passport requires a separate package and configuration for every provider.
passport-google-oauth20, passport-github2, etc.// passport: Requires distinct setup for each provider
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "/auth/google/callback"
},
async (accessToken, refreshToken, profile, done) => {
// You must handle profile mapping logic here
const user = await findOrCreateUser(profile);
return done(null, user);
}
));
auth0 stores user credentials and profiles in their cloud (by default).
// auth0: Fetching user profile from the token or API
export default async function profileHandler(req, res) {
const session = await auth0.getSession(req);
if (!session) return res.status(401).json({ error: 'Not logged in' });
// Data comes from the ID token or Management API
res.json({
email: session.user.email,
name: session.user.name
});
}
passport typically relies on your existing database.
// passport: Direct database access is standard
app.get('/profile', (req, res) => {
if (!req.user) return res.redirect('/login');
// Direct access to your DB model
res.json({
email: req.user.email,
role: req.user.role
});
});
auth0 includes enterprise security features out of the box.
// auth0: Enforcing MFA is often a dashboard setting or simple parameter
await auth0.handleLogin(req, res, {
authorizationParams: {
acr_values: 'http://schemas.openid.net/pape/policies:2008/07/multifactor'
}
});
passport requires you to implement advanced security logic manually.
// passport: MFA requires custom middleware and DB checks
app.post('/verify-mfa', async (req, res) => {
const { code, userId } = req.body;
const user = await db.users.findById(userId);
// You must implement the TOTP verification logic
const isValid = speakeasy.totp.verify({
secret: user.mfaSecret,
encoding: 'base32',
token: code
});
if (isValid) { /* Log user in */ }
});
Despite their architectural differences, both tools aim to solve the same problem securely.
// Both can verify a JWT (conceptually)
// Auth0: Verified automatically by the SDK middleware
// Passport: Verified via 'passport-jwt' strategy
const JwtStrategy = require('passport-jwt').Strategy;
// Setup involves defining the secret and issuer, similar to Auth0's config
// Auth0: Manages session in encrypted cookies automatically
const session = await auth0.getSession(req);
// Passport: Relies on express-session middleware
app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
app.use(passport.session());
// Auth0: Protection middleware
app.get('/admin', withApiAuthRequired(async (req, res) => {
res.json({ secret: 'data' });
}));
// Passport: Protection middleware
app.get('/admin', passport.authenticate('jwt'), (req, res) => {
res.json({ secret: 'data' });
});
// Auth0: Action (cloud-side)
exports.onExecutePostLogin = async (event, api) => {
if (event.user.app_metadata.role === 'admin') {
api.idToken.setCustomClaim('role', 'admin');
}
};
// Passport: Inline callback (app-side)
passport.use(new LocalStrategy((user, pass, done) => {
if (user.isBanned) return done(null, false);
return done(null, user);
}));
// Auth0: Official Next.js SDK
import { useUser } from '@auth0/nextjs-auth0/client';
// Passport: Community strategy for almost anything
import { Strategy as TwitterStrategy } from 'passport-twitter';
| Feature | Shared by Auth0 and Passport |
|---|---|
| Protocols | š OAuth2, OIDC, JWT |
| Integration | ā” Express/Koa Middleware |
| Sessions | š Cookie-based sessions |
| Social Login | š± Google, Facebook, GitHub |
| Extensibility | ā Custom logic hooks |
| Security | š”ļø HTTPS enforcement |
| Feature | auth0 | passport |
|---|---|---|
| Architecture | š¢ Managed SaaS + SDK | š§° Library + Self-Hosted Logic |
| User Storage | āļø Auth0 Cloud (Default) | šļø Your Database |
| Social Setup | āļø Dashboard Toggles | š» Code per Provider |
| MFA/Security | š”ļø Built-in & Configurable | šØ Build It Yourself |
| Cost Model | š° Monthly Active Users (MAU) | šø Free (Dev Time Costs) |
| Lock-in | š High (Vendor Specific) | š Low (Standard Code) |
auth0 is like renting a high-security apartment complex š¢. Everything is maintained for you (locks, cameras, front desk), and you just hand out keys to your tenants. It's perfect if you want to focus on your app's core value and don't want to worry about the liabilities of storing passwords. However, you pay rent per tenant, and you can't knock down walls easily.
passport is like buying raw land and building your own house š . You choose every brick, install your own security system, and own the deed completely. It's free to start, but if you forget to lock the back door, that's on you. It's ideal for teams with specific data requirements, legacy systems, or those who want to avoid recurring identity costs.
Final Thought: If your goal is speed to market and enterprise-grade security without the headache, go with auth0. If your goal is total control, zero vendor dependency, and you have the engineering bandwidth to manage security, go with passport.
Choose auth0 if you want to offload the security burden to a specialized provider, need enterprise features like SSO, MFA, or anomaly detection out of the box, and prefer a managed dashboard for user administration. This is the ideal path for teams that need to comply with strict security standards quickly without building custom identity infrastructure, or for applications requiring complex B2B identity scenarios.
Choose passport if you need complete control over the authentication flow, want to keep user data in your own database, or require a highly customized login experience that managed providers might restrict. It is best suited for applications where you already have an existing user base, need to support niche authentication methods not covered by major providers, or wish to avoid vendor lock-in and recurring identity platform costs.

š Documentation - š Getting Started - š» API Reference - š¬ Feedback
This library supports the following tooling versions:
^20.19.0 || ^22.12.0 || ^24.0.0 || ^26.0.0Using npm in your project directory run the following command:
npm install auth0
This client can be used to access Auth0's Authentication API.
import { AuthenticationClient } from "auth0";
const auth0 = new AuthenticationClient({
domain: "{YOUR_TENANT_AND REGION}.auth0.com",
clientId: "{YOUR_CLIENT_ID}",
clientSecret: "{OPTIONAL_CLIENT_SECRET}",
});
The Auth0 Management API is meant to be used by back-end servers or trusted parties performing administrative tasks. Generally speaking, anything that can be done through the Auth0 dashboard (and more) can also be done through this API.
Initialize your client class with a domain and token:
import { ManagementClient } from "auth0";
const management = new ManagementClient({
domain: "{YOUR_TENANT_AND REGION}.auth0.com",
token: "{YOUR_API_V2_TOKEN}",
});
Or use client credentials:
import { ManagementClient } from "auth0";
const management = new ManagementClient({
domain: "{YOUR_TENANT_AND REGION}.auth0.com",
clientId: "{YOUR_CLIENT_ID}",
clientSecret: "{YOUR_CLIENT_SECRET}",
withCustomDomainHeader: "auth.example.com", // Optional: Auto-applies to whitelisted endpoints
});
If you only need a few Management API resources, you can import them individually instead of
the full ManagementClient. Each resource has its own entry point (for example
auth0/clients, auth0/users, auth0/connections), so a bundler ships only the resources
you use. This keeps bundles small on size-constrained runtimes such as Cloudflare Workers.
To avoid wiring up authentication for every client, use createManagementAuth from
auth0/management. It handles the token once (fetching and refreshing via client
credentials, or accepting a static token) and gives you an options object you spread into
any sub-client. The token is cached and shared, so you are not re-authenticating per client.
import { createManagementAuth } from "auth0/management";
import { ClientsClient } from "auth0/clients";
import { UsersClient } from "auth0/users";
// Configure auth once and reuse it across clients.
const auth = createManagementAuth({
domain: "{YOUR_TENANT_AND_REGION}.auth0.com",
clientId: "{YOUR_CLIENT_ID}",
clientSecret: "{YOUR_CLIENT_SECRET}",
});
// Create each sub-client once and reuse the instances throughout your app.
export const clients = new ClientsClient(auth.clientOptions);
export const users = new UsersClient(auth.clientOptions);
await users.list({ page: 0, per_page: 10 });
You can also pass a static token:
const auth = createManagementAuth({
domain: "{YOUR_TENANT_AND_REGION}.auth0.com",
token: "{YOUR_API_V2_TOKEN}",
});
For lower-level control over the token lifecycle, TokenProvider is also exported from
auth0/management. It performs the client credentials grant and caches the token until
shortly before it expires:
import { TokenProvider } from "auth0/management";
import { ClientsClient } from "auth0/clients";
const tokenProvider = new TokenProvider({
domain: "{YOUR_TENANT_AND_REGION}.auth0.com",
clientId: "{YOUR_CLIENT_ID}",
clientSecret: "{YOUR_CLIENT_SECRET}",
audience: "https://{YOUR_TENANT_AND_REGION}.auth0.com/api/v2/",
});
const clients = new ClientsClient({
baseUrl: "https://{YOUR_TENANT_AND_REGION}.auth0.com/api/v2",
token: () => tokenProvider.getAccessToken(),
});
Request and response types for these clients live under the shared Management namespace and
are imported separately with import type { Management } from "auth0":
import type { Management } from "auth0";
const body: Management.CreateClientRequestContent = { name: "My App" };
const created: Management.CreateClientResponseContent = await clients.create(body);
Because they are TypeScript interfaces, import type is erased at compile time, so importing
types from the root auth0 entry adds nothing to your bundle and does not pull in the full
ManagementClient.
Recommendations for small bundles
auth0/clients, auth0/users,
and so on), not from the root auth0. A value import from the root pulls the full
ManagementClient and all resources into the module graph.import type { Management } from "auth0". Types are
erased, so this is always free regardless of the entry point.import type over a plain import for anything you only use in type positions. It
guarantees the import is erased and never accidentally ships runtime code (the one thing
that does add bytes is referencing an enum value, such as OauthScope.CreateActions).createManagementAuth (or a single shared
TokenProvider) and reuse the returned clientOptions across every sub-client. Create each
sub-client once and reuse the instance rather than constructing new clients per request.These smaller bundles rely on tree-shaking, so they apply when you consume the SDK as ESM through a bundler. A plain CommonJS
require()cannot tree-shake and loads the full resource graph.
This client can be used to retrieve user profile information.
import { UserInfoClient } from "auth0";
const userInfo = new UserInfoClient({
domain: "{YOUR_TENANT_AND REGION}.auth0.com",
});
// Get user info with an access token
const userProfile = await userInfo.getUserInfo(accessToken);
If you are migrating from the legacy node-auth0 package (v4.x) or need to maintain compatibility with legacy code, you can use the legacy export which provides the node-auth0 v4.x API interface.
The legacy version (node-auth0 v4.x) is available through the /legacy export path:
// Import the legacy version (node-auth0 v4.x API)
import { ManagementClient, AuthenticationClient } from "auth0/legacy";
// Or using CommonJS
const { ManagementClient, AuthenticationClient } = require("auth0/legacy");
The legacy API uses the node-auth0 v4.x configuration format and method signatures, which are different from the current v6 API:
import { ManagementClient } from "auth0/legacy";
const management = new ManagementClient({
domain: "{YOUR_TENANT_AND REGION}.auth0.com",
clientId: "{YOUR_CLIENT_ID}",
clientSecret: "{YOUR_CLIENT_SECRET}",
scope: "read:users update:users",
});
// Legacy API methods use promise-based patterns (node-auth0 v4.x style)
management.users
.getAll()
.then((users) => console.log(users))
.catch((err) => console.error(err));
// Or with async/await
try {
const users = await management.users.getAll();
console.log(users);
} catch (err) {
console.error(err);
}
import { AuthenticationClient } from "auth0/legacy";
const auth0 = new AuthenticationClient({
domain: "{YOUR_TENANT_AND REGION}.auth0.com",
clientId: "{YOUR_CLIENT_ID}",
clientSecret: "{YOUR_CLIENT_SECRET}",
});
// Legacy authentication methods (node-auth0 v4.x style)
auth0.oauth
.passwordGrant({
username: "user@example.com",
password: "password",
audience: "https://api.example.com",
})
.then((userData) => {
console.log(userData);
})
.catch((err) => {
console.error("Authentication error:", err);
});
// Or with async/await
try {
const userData = await auth0.oauth.passwordGrant({
username: "user@example.com",
password: "password",
audience: "https://api.example.com",
});
console.log(userData);
} catch (err) {
console.error("Authentication error:", err);
}
When migrating from node-auth0 v4.x to the current v5 SDK, note the following key differences:
Legacy (node-auth0 v4.x) code:
const { ManagementClient } = require("auth0/legacy");
const management = new ManagementClient({
domain: "your-tenant.auth0.com",
clientId: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET",
scope: "read:users",
});
// With promises
management.users
.getAll({ search_engine: "v3" })
.then((users) => {
console.log(users);
})
.catch((err) => {
console.error(err);
});
// Or with async/await
try {
const users = await management.users.getAll({ search_engine: "v3" });
console.log(users);
} catch (err) {
console.error(err);
}
v5 equivalent:
import { ManagementClient } from "auth0";
const management = new ManagementClient({
domain: "your-tenant.auth0.com",
clientId: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET",
});
// With promises
management.users
.list({
searchEngine: "v3",
})
.then((users) => {
console.log(users);
})
.catch((error) => {
console.error(error);
});
// Or with async/await
try {
const users = await management.users.list({
searchEngine: "v3",
});
console.log(users);
} catch (error) {
console.error(error);
}
The SDK exports all request and response types as TypeScript interfaces. You can import them directly:
import { ManagementClient, Management, ManagementError } from "auth0";
const client = new ManagementClient({
domain: "your-tenant.auth0.com",
token: "YOUR_TOKEN",
});
// Use the request type
const listParams: Management.ListActionsRequestParameters = {
triggerId: "post-login",
actionName: "my-action",
};
const actions = await client.actions.list(listParams);
When the API returns a non-success status code (4xx or 5xx response), a subclass of the following error will be thrown.
import { ManagementError } from "auth0";
try {
await client.actions.create({
name: "my-action",
supported_triggers: [{ id: "post-login" }],
code: "exports.onExecutePostLogin = async (event, api) => { console.log('Hello World'); };",
});
} catch (err) {
if (err instanceof ManagementError) {
console.log(err.statusCode);
console.log(err.message);
console.log(err.body);
console.log(err.rawResponse);
}
}
Some list endpoints are paginated. You can iterate through pages using default values:
import { ManagementClient } from "auth0";
const client = new ManagementClient({
domain: "your-tenant.auth0.com",
token: "YOUR_TOKEN",
});
// Using default pagination (page size defaults vary by endpoint)
let page = await client.actions.list();
for (const item of page.data) {
console.log(item);
}
while (page.hasNextPage()) {
page = await page.getNextPage();
for (const item of page.data) {
console.log(item);
}
}
Or you can explicitly control pagination using page and per_page parameters:
// Offset-based pagination (most endpoints)
let page = await client.actions.list({
page: 0, // Page number (0-indexed)
per_page: 25, // Number of items per page
});
for (const item of page.data) {
console.log(item);
}
while (page.hasNextPage()) {
page = await page.getNextPage();
for (const item of page.data) {
console.log(item);
}
}
Some endpoints use checkpoint pagination with from and take parameters:
// Checkpoint-based pagination (e.g., connections, organizations)
let page = await client.connections.list({
take: 50, // Number of items per page
});
for (const item of page.data) {
console.log(item);
}
while (page.hasNextPage()) {
page = await page.getNextPage();
for (const item of page.data) {
console.log(item);
}
}
If you would like to send additional headers as part of the request, use the headers request option.
const response = await client.actions.create(
{
name: "my-action",
supported_triggers: [{ id: "post-login" }],
},
{
headers: {
"X-Custom-Header": "custom value",
},
},
);
The SDK provides convenient helper functions for common request configuration patterns:
import { ManagementClient, CustomDomainHeader, withTimeout, withRetries, withHeaders, withAbortSignal } from "auth0";
const client = new ManagementClient({
domain: "your-tenant.auth0.com",
token: "YOUR_TOKEN",
});
// Example 1: Use custom domain header for specific requests
const reqOptions = {
...CustomDomainHeader("auth.example.com"),
timeoutInSeconds: 30,
};
await client.actions.list({}, reqOptions);
// Example 2: Combine multiple options
const reqOptions = {
...withTimeout(30),
...withRetries(3),
...withHeaders({
"X-Request-ID": crypto.randomUUID(),
"X-Operation-Source": "admin-dashboard",
}),
};
await client.actions.list({}, reqOptions);
// Example 3: For automatic custom domain header on whitelisted endpoints
const client = new ManagementClient({
domain: "your-tenant.auth0.com",
token: "YOUR_TOKEN",
withCustomDomainHeader: "auth.example.com", // Auto-applies to whitelisted endpoints
});
// Example 4: Request cancellation
const controller = new AbortController();
const reqOptions = {
...withAbortSignal(controller.signal),
...withTimeout(30),
};
const promise = client.actions.list({}, reqOptions);
// Cancel after 10 seconds
setTimeout(() => controller.abort(), 10000);
Available helper functions:
CustomDomainHeader(domain) - Configure custom domain header for specific requestswithTimeout(seconds) - Set request timeoutwithRetries(count) - Configure retry attemptswithHeaders(headers) - Add custom headerswithAbortSignal(signal) - Enable request cancellationTo apply the custom domain header globally across your application, use the withCustomDomainHeader option when initializing the ManagementClient. This will automatically inject the header for all whitelisted endpoints.
The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long as the request is deemed retryable and the number of retry attempts has not grown larger than the configured retry limit (default: 2).
A request is deemed retryable when any of the following HTTP status codes is returned:
Use the maxRetries request option to configure this behavior.
const response = await client.actions.create(
{
name: "my-action",
supported_triggers: [{ id: "post-login" }],
},
{
maxRetries: 0, // override maxRetries at the request level
},
);
The SDK defaults to a 60 second timeout. Use the timeoutInSeconds option to configure this behavior.
const response = await client.actions.create(
{
name: "my-action",
supported_triggers: [{ id: "post-login" }],
},
{
timeoutInSeconds: 30, // override timeout to 30s
},
);
The SDK allows users to abort requests at any point by passing in an abort signal.
const controller = new AbortController();
const response = await client.actions.create(
{
name: "my-action",
supported_triggers: [{ id: "post-login" }],
},
{
abortSignal: controller.signal,
},
);
controller.abort(); // aborts the request
The SDK supports configurable logging for debugging API requests and responses. By default, logging is silent.
import { ManagementClient } from "auth0";
const client = new ManagementClient({
domain: "your-tenant.auth0.com",
clientId: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET",
logging: {
level: "debug", // "debug" | "info" | "warn" | "error"
silent: false, // Set to false to enable logging output
},
});
You can also provide a custom logger implementation:
import { ManagementClient } from "auth0";
const customLogger = {
debug: (msg, ...args) => myLogger.debug(msg, args),
info: (msg, ...args) => myLogger.info(msg, args),
warn: (msg, ...args) => myLogger.warn(msg, args),
error: (msg, ...args) => myLogger.error(msg, args),
};
const client = new ManagementClient({
domain: "your-tenant.auth0.com",
clientId: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET",
logging: {
level: "info",
logger: customLogger,
silent: false,
},
});
The SDK provides access to raw response data, including headers, through the .withRawResponse() method.
The .withRawResponse() method returns a promise that results to an object with a data and a rawResponse property.
const { data, rawResponse } = await client.actions
.create({
name: "my-action",
supported_triggers: [{ id: "post-login" }],
})
.withRawResponse();
console.log(data);
console.log(rawResponse.headers);
The SDK defaults to node-fetch but will use the global fetch client if present. The SDK works in the following
runtimes:
We appreciate feedback and contribution to this repo! Before you get started, please see the following:
While we value open-source contributions to this SDK, this library is generated programmatically. Additions made directly to this library would have to be moved over to our generation code, otherwise they would be overwritten upon the next generated release. Feel free to open a PR as a proof of concept, but know that we will not be able to merge it as-is. We suggest opening an issue first to discuss with us!
On the other hand, contributions to the README are always very welcome!
To provide feedback or report a bug, please raise an issue on our issue tracker.
Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?
This project is licensed under the MIT license. See the LICENSE file for more info.