# Auth0 Node.js SDK

Auth0 Node.js SDK provides comprehensive access to Auth0's Authentication and Management APIs, enabling developers to integrate Auth0's identity and access management services into their Node.js applications. The SDK offers three main clients for different use cases: authentication flows, user management, and user information retrieval.

## Package Information

- **Package Name**: auth0
- **Package Type**: npm
- **Language**: TypeScript
- **Installation**: `npm install auth0`
- **Node.js**: >=18

## Core Imports

```typescript
import { ManagementClient, AuthenticationClient, UserInfoClient } from "auth0";
```

For CommonJS:

```javascript
const { ManagementClient, AuthenticationClient, UserInfoClient } = require("auth0");
```

## Basic Usage

```typescript
import { AuthenticationClient, ManagementClient } from "auth0";

// Authentication client for user authentication flows
const auth = new AuthenticationClient({
  domain: "your-domain.auth0.com",
  clientId: "your-client-id",
  clientSecret: "your-client-secret"
});

// Management client for administrative operations
const management = new ManagementClient({
  domain: "your-domain.auth0.com",
  clientId: "your-client-id",
  clientSecret: "your-client-secret"
});

// Exchange authorization code for tokens
const tokens = await auth.oauth.authorizationCodeGrant({
  code: "auth-code",
  redirect_uri: "https://yourapp.com/callback"
});

// Get user profile
const user = await management.users.get({ id: "user_id" });
```

## Architecture

The Auth0 Node.js SDK is structured around three main clients:

- **AuthenticationClient**: Handles user authentication flows, token exchange, and password operations
- **ManagementClient**: Provides administrative access to Auth0 resources through 39 specialized managers
- **UserInfoClient**: Retrieves user profile information using access tokens

Each client is configured with domain and authentication credentials, and provides a clean Promise-based API that abstracts Auth0's REST endpoints while maintaining full feature parity.

## Capabilities

### Authentication API

Core authentication flows including OAuth 2.0, OIDC, passwordless, and CIBA for user authentication and token management.

```typescript { .api }
class AuthenticationClient {
  constructor(options: AuthenticationClientOptions);
  database: Database;
  oauth: OAuth;
  passwordless: Passwordless;
  backchannel: IBackchannel;
  tokenExchange: ICustomTokenExchange;
}

interface AuthenticationClientOptions extends ClientOptions {
  domain: string;
  clientId: string;
  clientSecret?: string;
  clientAssertionSigningKey?: string;
  clientAssertionSigningAlg?: string;
  idTokenSigningAlg?: string;
  clockTolerance?: number;
  useMTLS?: boolean;
}
```

[Authentication API](./authentication.md)

### Management API

Administrative access to Auth0 resources including users, applications, connections, and tenant configuration through 39 specialized managers.

```typescript { .api }
class ManagementClient extends ManagementClientBase {
  constructor(options: ManagementClientOptionsWithToken);
  constructor(options: ManagementClientOptionsWithClientCredentials);
  
  // User & Identity Management
  users: UsersManager;
  usersByEmail: UsersByEmailManager;
  userBlocks: UserBlocksManager;
  
  // Application & Client Management
  clients: ClientsManager;
  clientGrants: ClientGrantsManager;
  
  // ... 34 additional managers
}

interface ManagementClientOptionsWithToken extends ManagementClientOptions {
  token: string | (() => Promise<string>) | (() => string);
}

type ManagementClientOptionsWithClientCredentials = ManagementClientOptions &
  (ManagementClientOptionsWithClientSecret | ManagementClientOptionsWithClientAssertion);

interface ManagementClientOptionsWithClientSecret extends ManagementClientOptions {
  clientId: string;
  clientSecret: string;
}

interface ManagementClientOptionsWithClientAssertion extends ManagementClientOptions {
  clientId: string;
  clientAssertionSigningKey: string;
  clientAssertionSigningAlg?: string;
}
```

[Management API](./management.md)

### User Information API

Retrieval of user profile information using OIDC-compliant access tokens.

```typescript { .api }
class UserInfoClient extends BaseAPI {
  constructor(options: { domain: string } & ClientOptions);
  getUserInfo(accessToken: string, initOverrides?: InitOverride): Promise<JSONApiResponse<UserInfoResponse>>;
}

interface UserInfoResponse {
  sub: string;
  name: string;
  given_name?: string;
  family_name?: string;
  nickname: string;
  email: string;
  email_verified: boolean;
  // ... additional OIDC standard claims
}
```

[User Information API](./userinfo.md)

## Core Types

### Configuration Options

```typescript { .api }
interface ClientOptions {
  telemetry?: boolean;
  clientInfo?: { name: string; [key: string]: unknown };
  fetch?: FetchAPI;
  middleware?: Middleware[];
  agent?: Dispatcher;
  headers?: HTTPHeaders;
  timeoutDuration?: number;
  retry?: RetryConfiguration;
}

interface ManagementClientOptions extends ClientOptions {
  domain: string;
  audience?: string;
  headers?: Record<string, string>;
}
```

### HTTP and Network Types

```typescript { .api }
/** Custom fetch implementation interface */
type FetchAPI = (url: URL | RequestInfo, init?: RequestInit) => Promise<Response>;

/** HTTP headers as key-value pairs */
type HTTPHeaders = { [key: string]: string };

/** HTTP methods supported by the SDK */
type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';

/** HTTP query parameters */
type HTTPQuery = {
  [key: string]:
    | string
    | number
    | null
    | boolean
    | Array<string | number | null | boolean>
    | HTTPQuery;
};

/** HTTP request body types */
type HTTPBody = any | FormData | URLSearchParams;

/** Request initialization override */
type InitOverride = RequestInit | InitOverrideFunction;

type InitOverrideFunction = (requestContext: {
  init: HTTPRequestInit;
  context: RequestOpts;
}) => Promise<RequestInit>;
```

### Middleware System

```typescript { .api }
interface Middleware {
  /** Pre-request middleware hook */
  pre?(context: RequestContext): Promise<FetchParams | void> | FetchParams | void;
  /** Post-response middleware hook */
  post?(context: ResponseContext): Promise<Response | void> | Response | void;
  /** Error handling middleware hook */
  onError?(context: ErrorContext): Promise<Response | void> | Response | void;
}

interface RequestContext {
  url: URL;
  init: RequestInit;
}

interface ResponseContext {
  url: URL;
  init: RequestInit;
  response: Response;
}

interface ErrorContext {
  url: URL;
  init: RequestInit;
  error: Error;
}

interface FetchParams {
  url: URL;
  init: RequestInit;
}
```

### Retry Configuration

```typescript { .api }
interface RetryConfiguration {
  /** Maximum number of retry attempts */
  maxRetries?: number;
  /** Delay between retries in milliseconds */
  retryDelay?: number;
  /** Whether to use exponential backoff */
  exponentialBackoff?: boolean;
  /** Custom retry condition function */
  retryCondition?: (error: Error, attempt: number) => boolean;
}
```

### Token Types

```typescript { .api }
interface TokenSet {
  access_token: string;
  refresh_token?: string;
  id_token?: string;
  token_type: 'Bearer';
  expires_in: number;
}
```

### Response Types

```typescript { .api }
class JSONApiResponse<T> implements ApiResponse<T> {
  data: T;
  status: number;
  statusText: string;
  headers: Headers;
}

class VoidApiResponse implements ApiResponse<undefined> {
  data: undefined;
  status: number;
  statusText: string;
  headers: Headers;
}

class TextApiResponse implements ApiResponse<string> {
  data: string;
  status: number;
  statusText: string;
  headers: Headers;
}
```

## Error Handling

The SDK provides specialized error classes for different API contexts:

```typescript { .api }
class AuthApiError extends Error {
  name: 'AuthApiError';
  constructor(
    public error: string,
    public error_description: string,
    public statusCode: number,
    public body: string,
    public headers: Headers
  );
}

class ManagementApiError extends Error {
  name: 'ManagementApiError';
  constructor(
    public errorCode: string | undefined,
    public error: string,
    public statusCode: number,
    public body: string,
    public headers: Headers,
    public msg: string
  );
}

class UserInfoError extends Error {
  name: 'UserInfoError';
  constructor(
    public error: string,
    public error_description: string,
    public statusCode: number,
    public body: string,
    public headers: Headers
  );
}

class ResponseError extends Error {
  name: 'ResponseError';
  constructor(
    public statusCode: number,
    public body: string,
    public headers: Headers,
    msg?: string
  );
}

class TimeoutError extends Error {
  name: 'TimeoutError';
}

class FetchError extends Error {
  name: 'FetchError';
}
```

## HTTP Response Utilities

Utilities for parsing rate limit information from Auth0 API responses:

```typescript { .api }
class HttpResponseHeadersUtils {
  static getClientQuotaLimit(headers: Headers): TokenQuotaBucket | null;
  static getOrganizationQuotaLimit(headers: Headers): TokenQuotaBucket | null;
}

interface TokenQuotaBucket {
  perHour?: TokenQuotaLimit;
  perDay?: TokenQuotaLimit;
}

interface TokenQuotaLimit {
  quota: number;
  remaining: number;
  resetAfter: number;
}
```

## SDK Utilities

### Version Information

The SDK exports version information for debugging and compatibility checks:

```typescript { .api }
/** SDK version string (e.g., "4.29.0") */
declare const version: string;
```

**Usage:**

```typescript
import { version } from "auth0";

console.log(`Auth0 SDK Version: ${version}`);
```

### Utility Functions

```typescript { .api }
/** Generates client information for telemetry purposes */
declare const generateClientInfo: () => {
  name: string;
  version: string;
  env: Record<string, string>;
};

/** Mutual TLS prefix for domain configuration */
declare const mtlsPrefix: string;

/** Resolves a value that can be static, sync function, or async function */
declare const resolveValueToPromise: <T>(
  value: T | (() => T) | (() => Promise<T>)
) => Promise<T>;
```

## Deprecations

The SDK includes deprecated type aliases maintained for backward compatibility. These should be avoided in new code:

```typescript { .api }
/** @deprecated Use EmailProviderUpdate instead */
type PatchProviderRequest = EmailProviderUpdate;

/** @deprecated Use EmailProviderCreate instead */
type PostProviderRequest = EmailProviderCreate;

/** @deprecated Use ClientCreateOidcLogout instead */
type ClientCreateOidcBackchannelLogout = ClientCreateOidcLogout;
```

## Advanced/Internal APIs

The following APIs are exported but intended for advanced use cases or internal SDK operations. Use with caution as these may change in future versions.

### Base Classes and Internal Infrastructure

```typescript { .api }
/** Base class for authentication API operations */
declare class BaseAuthAPI {
  constructor(options: AuthenticationClientOptions);
  protected domain: string;
  protected clientId: string;
  protected request: (opts: RequestOpts, init?: InitOverride) => Promise<Response>;
  protected addClientAuthentication: (body: any) => Promise<void>;
}

/** Base class for all API operations */
declare class BaseAPI {
  constructor(configuration: Configuration);
  protected request: (requestOpts: RequestOpts, initOverrides?: InitOverride) => Promise<Response>;
}

/** Core configuration interface for API clients */
interface Configuration {
  baseUrl: string;
  parseError: (response: Response) => Promise<Error>;
  fetch?: FetchAPI;
  middleware?: Middleware[];
  agent?: Dispatcher;
  headers?: HTTPHeaders;
  timeoutDuration?: number;
  retry?: RetryConfiguration;
}
```

### Middleware Classes

```typescript { .api }
/** Telemetry middleware for SDK usage tracking */
declare class TelemetryMiddleware implements Middleware {
  constructor(options: ClientOptions);
  pre(context: RequestContext): Promise<FetchParams | void>;
}

/** Token provider middleware for Management API authentication */
declare class TokenProviderMiddleware implements Middleware {
  constructor(tokenProvider: TokenProvider);
  pre(context: RequestContext): Promise<FetchParams | void>;
}

/** Token provider for Management API client credentials */
declare class TokenProvider {
  constructor(options: ManagementClientOptionsWithClientCredentials);
  getToken(): Promise<string>;
}
```

### Runtime Utilities

```typescript { .api }
/** Validates required request parameters */
declare function validateRequiredRequestParams(params: any, required: string[]): void;

/** Applies query parameters to URL */
declare function applyQueryParams(url: URL, params: HTTPQuery): void;

/** Parses form parameter from request body */
declare function parseFormParam(body: any, key: string): string | undefined;

/** Authentication grant function */
declare function grant(
  baseAPI: BaseAuthAPI,
  grantType: string,
  body: any,
  grantOptions?: any
): Promise<JSONApiResponse<TokenSet>>;
```

### Client Authentication Utilities

```typescript { .api }
/** Adds client authentication to request payload */
declare function addClientAuthentication(
  payload: any,
  options: AuthenticationClientOptions
): Promise<void>;

/** Client authentication payload interface */
interface AddClientAuthenticationPayload {
  client_id?: string;
  client_secret?: string;
  client_assertion?: string;
  client_assertion_type?: string;
}
```

### Retry Functionality

```typescript { .api }
/** Generic retry function with exponential backoff */
declare function retry<T>(
  fn: () => Promise<T>,
  config: RetryConfiguration
): Promise<T>;
```

**Important Notes:**

- These APIs are exported for extensibility but are subject to change without notice
- Direct usage is not recommended for most applications
- Use the main client APIs (`AuthenticationClient`, `ManagementClient`, `UserInfoClient`) instead
- These are primarily for advanced customization and SDK extension scenarios