auth0 Node.js SDK

repository·master·Indexed 20 days ago

https://github.com/auth0/node-auth0

The auth0 Node.js SDK (v6.1.0) provides programmatic access to the Auth0 Authentication, Management, and UserInfo APIs. It supports full-featured server-side applications and lightweight, tree-shakable environments like Cloudflare Workers, Deno, Bun, and React Native. The SDK includes specialized clients such as ManagementClient, AuthenticationClient, and UserInfoClient, along with utilities for token management, pagination, and automatic retries.

Tokens
97.9K
Snippets
386
Records
422
Agent score
71%

What's inside auth0

  1. Identify key client classes

    master

    The SDK provides three primary client classes for interacting with different Auth0 APIs:

    • ManagementClient: Used for Auth0 Management API operations (e.g., managing users, actions, connections).
    • AuthenticationClient: Used for Auth0 Authentication API operations (e.g., login, token exchange).
    • UserInfoClient: Used for retrieving user profile information.
  2. Use the Management namespace for types

    master

    In v5, all Management API request and response types are organized under the Management namespace. This provides more descriptive and consistent naming compared to the auto-generated types in v4. When using TypeScript, import Management from auth0 to access these types (e.g., Management.UpdateUserRequestContent).

    import { ManagementClient, Management } from "auth0";
    
    const client = new ManagementClient({
        domain: "your-tenant.auth0.com",
        clientId: "YOUR_CLIENT_ID",
        clientSecret: "YOUR_CLIENT_SECRET",
    });
    
    const request: Management.UpdateUserRequestContent = {
        user_metadata: { email: `'this@example.com'` },
    };
    
    await client.users.update("example_id", request);
  3. Use individual Management sub-clients for smaller bundles

    master

    To reduce bundle size (e.g., for Cloudflare Workers), import specific resource clients (like UsersClient or ClientsClient) from their own entry points instead of the full ManagementClient.

    To avoid repeating authentication logic, use createManagementAuth from auth0/management. This utility handles token fetching and refreshing via client credentials and returns an options object that can be spread into any sub-client. The token is cached and shared across clients.

    Best Practices for Small Bundles:

    • Import clients as values from specific entry points (e.g., auth0/users).
    • Import request/response types using import type { Management } from "auth0" to ensure they are erased at compile time.
    • Reuse client instances rather than constructing them per request.
    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 });
  4. Migrating Management API from v4 to v5

    master

    The Management API in v5 has been significantly restructured using Fern for code generation. Key changes include:

    • Resource Grouping: Subresources are now moved into sub-clients.
    • Consistent Naming: Methods follow a predictable pattern: list, create, update, delete, set, and get.
    • Improved Types: Uses an optimized OpenAPI specification for more accurate type definitions.

    When a resource has both a 'get one' and a 'get all' capability, the 'get all' method is now consistently named list() (e.g., client.users.list() instead of client.getUsers()).

  5. Configure automatic retries

    master

    The SDK automatically retries requests with exponential backoff if they are deemed retryable. A request is retryable if it returns one of the following HTTP status codes:

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

    The default retry limit is 2. You can override this using the maxRetries option at the request level.

    const response = await client.actions.create(
        {
            name: "my-action",
            supported_triggers: [{ id: "post-login" }],
        },
        {
            maxRetries: 0, // Disables retries for this specific request
        },
    );
  6. Migrate Management API sub-resource paths in v5

    master

    In node-auth0 v5, several Management API methods have been moved under more specific sub-resource namespaces to better reflect the Auth0 API structure. When migrating from v4, you must update the method calls to use these new paths.

    Email Management

    • emails.get() $\rightarrow$ emails.provider.get()
    • emails.update() $\rightarrow$ emails.provider.update()

    User Grants

    • grants.deleteByUserId() $\rightarrow$ userGrants.deleteByUserId()
    • grants.delete() $\rightarrow$ userGrants.delete()

    Signing Keys

    • keys.rotate() $\rightarrow$ keys.signing.rotate()
    • keys.get() $\rightarrow$ keys.signing.get()
    • keys.revoke() $\rightarrow$ keys.signing.revoke()

    User Identities and Security

    • users.link() $\rightarrow$ users.identities.link()
    • users.invalidateRememberBrowser() $\rightarrow$ users.multifactor.invalidateRememberBrowser()

    Encryption Keys

    • keys.createPublicWrappingKey() $\rightarrow$ keys.encryption.createPublicWrappingKey()
    // Example of sub-resource move migration
    
    // Before v5:
    // await auth0.emails.get({ id: 'email_id' });
    // await auth0.keys.rotate();
    
    // After v5:
    await auth0.emails.provider.get({ id: 'email_id' });
    await auth0.keys.signing.rotate();
  7. Migrate pagination from v4 to v5

    master

    In v5, all iterable responses from *.list() methods return a Page object instead of a plain object with a data property. To retrieve all data, you must manually iterate through pages using page.hasNextPage() and page.getNextPage().

    For offset-based pagination, you can pass page (0-indexed) and per_page in the options object. For checkpoint-based pagination (used by connections or organizations), use the take parameter.

    import { ManagementClient } from "auth0";
    
    const client = new ManagementClient({
        domain: "your-tenant.auth0.com",
        clientId: "YOUR_CLIENT_ID",
        clientSecret: "YOUR_CLIENT_SECRET",
    });
    
    // Manual pagination with default values
    let page = await client.clients.list();
    for (const client of page.data) {
        console.log(`Client ID: ${client.client_id}, Name: ${client.name}`);
    }
    
    while (page.hasNextPage()) {
        page = await page.getNextPage();
        for (const client of page.data) {
            console.log(`Client ID: ${client.client_id}, Name: ${client.name}`);
        }
    }
  8. Use the legacy node-auth0 v4 API

    master

    If you are migrating from or maintaining code compatible with node-auth0 v4.x, you can use the /legacy export path. This provides the old configuration format and method signatures.

    // Import the legacy version (node-auth0 v4.x API)
    import { ManagementClient, AuthenticationClient } from "auth0/legacy";
    
    // Or using CommonJS
    const { ManagementClient, AuthenticationClient } = require("auth0/legacy");
  9. Update PhoneProviderProtectionBackoffStrategyEnum values

    master

    The PhoneProviderProtectionBackoffStrategyEnum has been updated to align with the Auth0 API. The None variant has been renamed to Default, and its underlying string value has changed from "none" to "default".

    If you are using the enum, switch from .None to .Default. If you are passing the value as a raw string, change "none" to "default".

    import { Management } from "auth0";
    
    // After (v6)
    const strategy = Management.PhoneProviderProtectionBackoffStrategyEnum.Default; // "default"
  10. Supported Node.js versions for v5

    master

    The Auth0 TS SDK (v5) is guaranteed to work with the following Node.js versions:

    • ^20.19.0 (any Node 20 version starting from 20.19.0)
    • ^22.12.0 (any Node 22 version starting from 22.12.0)
    • ^24.0.0 (any Node 24 version)

    Other non-production versions of Node may work but are not directly supported.