auth0 vs passport
Architecting Authentication: Managed Identity vs. Modular Middleware
auth0passportSimilar Packages:

Architecting Authentication: Managed Identity vs. Modular Middleware

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.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
auth0068211.5 MB136 days agoMIT
passport023,531157 kB3983 years agoMIT

Auth0 SDK vs. Passport: Choosing Your Authentication Architecture

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.

šŸ—ļø Core Philosophy: Managed Service vs. Modular Toolkit

auth0 acts as your bridge to a managed identity platform.

  • You redirect users to Auth0's hosted login page.
  • Auth0 handles the password reset, social login connections, and database storage.
  • Your app receives a token and trusts it.
// 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.

  • You define exactly how the request is processed.
  • You connect it to your own database or specific APIs.
  • You decide where the session lives (cookie, Redis, memory).
// 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')
);

šŸ” Handling Social Logins: Configuration vs. Code

auth0 treats social providers as toggle switches in a dashboard.

  • You enable "Google" or "GitHub" in the Auth0 portal.
  • The SDK requires no code changes to support new providers.
  • Auth0 normalizes the user profile data for you.
// 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.

  • You install passport-google-oauth20, passport-github2, etc.
  • You must write specific setup code for each strategy.
  • You are responsible for mapping different profile shapes to your user model.
// 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);
  }
));

šŸ—„ļø User Data Ownership: External vs. Internal

auth0 stores user credentials and profiles in their cloud (by default).

  • Great for compliance (GDPR, SOC2) as they manage the security.
  • Harder to run complex SQL queries on user data directly from your app.
  • You sync data via rules or actions if you need it locally.
// 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.

  • You have full SQL/NoSQL access to user records.
  • You control password hashing algorithms and rotation policies.
  • Ideal if you have legacy user data or strict data residency requirements.
// 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 
  });
});

šŸ›”ļø Advanced Security Features: Built-in vs. DIY

auth0 includes enterprise security features out of the box.

  • Multi-Factor Authentication (MFA), Breach Detection, and Bot Protection are configurable via UI.
  • No code changes needed to enforce MFA for high-risk logins.
  • Automatically handles OIDC protocol complexities.
// 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.

  • MFA requires custom database fields, SMS/Email integration, and UI flows.
  • You must implement rate limiting and brute-force protection yourself.
  • High flexibility, but high risk of implementation errors.
// 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 */ }
});

šŸ¤ Similarities: Shared Ground Between Auth0 and Passport

Despite their architectural differences, both tools aim to solve the same problem securely.

1. šŸ”‘ Support for Open Standards

  • Both rely heavily on OAuth 2.0 and OpenID Connect (OIDC).
  • Both can issue and validate JWTs (JSON Web Tokens).
// 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

2. 🌐 Session Management

  • Both integrate with Node.js session mechanisms.
  • Both allow you to maintain a logged-in state across requests.
// 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());

3. ⚔ Middleware Integration

  • Both are designed to plug into the Express/Koa request pipeline.
  • Both use middleware functions to protect routes.
// 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' }); 
});

4. āœ… Customization Points

  • Both allow custom logic during the auth flow.
  • Auth0 uses "Actions" (serverless functions in their cloud); Passport uses inline callbacks.
// 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);
}));

5. šŸ‘„ Ecosystem & Community

  • Both have massive adoption and extensive documentation.
  • Auth0 has official SDKs for every major framework; Passport has community strategies for every provider.
// 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';

šŸ“Š Summary: Key Similarities

FeatureShared 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

šŸ†š Summary: Key Differences

Featureauth0passport
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)

šŸ’” The Big Picture

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.

How to Choose: auth0 vs passport

  • auth0:

    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.

  • passport:

    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.

README for auth0

Node.js client library for Auth0

Release Codecov Ask DeepWiki Downloads License fern shield

šŸ“š Documentation - šŸš€ Getting Started - šŸ’» API Reference - šŸ’¬ Feedback

Documentation

Getting Started

Requirements

This library supports the following tooling versions:

  • Node.js: ^20.19.0 || ^22.12.0 || ^24.0.0 || ^26.0.0

Installation

Using npm in your project directory run the following command:

npm install auth0

Configure the SDK

Authentication API Client

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}",
});

Management API Client

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

Individual Management sub-clients (smaller bundles)

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

  • Import each client as a value from its own entry point (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 request and response types with import type { Management } from "auth0". Types are erased, so this is always free regardless of the entry point.
  • Prefer 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).
  • Configure authentication once with 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.

UserInfo API Client

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

Legacy Usage

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.

Installing Legacy Version

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");

Legacy Configuration

The legacy API uses the node-auth0 v4.x configuration format and method signatures, which are different from the current v6 API:

Legacy Management Client

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

Legacy Authentication Client

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

Migration from Legacy (node-auth0 v4) to v5

When migrating from node-auth0 v4.x to the current v5 SDK, note the following key differences:

  1. Method Names: Many method names have changed to be more descriptive
  2. Type Safety: Enhanced TypeScript support with better type definitions
  3. Error Handling: Unified error handling with specific error types
  4. Configuration: Simplified configuration options

Example Migration

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

Request and Response Types

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

API Reference

Generated Documentation

Key Classes

  • ManagementClient - for Auth0 Management API operations
  • AuthenticationClient - for Auth0 Authentication API operations
  • UserInfoClient - for retrieving user profile information

Exception Handling

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

Pagination

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

Advanced

Additional Headers

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",
        },
    },
);

Request Helpers

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 requests
  • withTimeout(seconds) - Set request timeout
  • withRetries(count) - Configure retry attempts
  • withHeaders(headers) - Add custom headers
  • withAbortSignal(signal) - Enable request cancellation

To 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.

Retries

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:

  • 408 (Timeout)
  • 429 (Too Many Requests)
  • 5XX (Internal Server Errors)

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

Timeouts

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

Aborting Requests

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

Logging

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

Access Raw Response Data

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

Runtime Compatibility

The SDK defaults to node-fetch but will use the global fetch client if present. The SDK works in the following runtimes:

  • Node.js 20.19.0+, 22.12.0+, 24+, 26+
  • Vercel
  • Cloudflare Workers
  • Deno v1.25+
  • Bun 1.0+
  • React Native

Feedback

Contributing

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!

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

What is Auth0?

Auth0 Logo

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.