The Auth0 Node.js SDK v5 is a TypeScript-based SDK providing Auth0 Authentication and Management API clients. The codebase uses Fern-generated code for the Management API with custom wrappers, alongside hand-written Authentication API clients.
Key Capabilities:
- Authentication API client for login, token exchange, and user authentication flows
- Management API client for tenant administration and user management
- UserInfo API client for user profile retrieval
- Dual module system supporting both CommonJS and ESM
- TypeScript-first with comprehensive type definitions
- Legacy v4 compatibility layer for migration
# Install dependencies
yarn install
# Build both CommonJS and ESM distributions
yarn build
# Build only CommonJS
yarn build:cjs
# Build only ESM (includes .mjs renaming)
yarn build:esm
# Run all tests
yarn test
# Run specific test suites
yarn test:unit # Unit tests (src/management/tests)
yarn test:browser # Browser environment tests
yarn test:wire # Integration tests with mock server
# Run linter
yarn lint
# Fix linting issues
yarn lint:fix
# Generate documentation
yarn docs
# Validate entire project (lint, format, build, test)
yarn validateCommon operations for working with the SDK:
# Build and test after changes
yarn build && yarn test
# Run tests with coverage
yarn test:coverage
# Watch mode for development (use specific TypeScript configs)
tsc --project ./tsconfig.cjs.json --watch
# Test specific functionality
yarn test:unit -- --testNamePattern="ManagementClient"
# Run linter with auto-fix
yarn lint:fix
# Format code
yarn format- Source TypeScript files live in
src/ - Compiled output goes to
dist/cjs/(CommonJS) anddist/esm/(ESM) - ESM build automatically renames
.js→.mjsand.d.ts→.d.mts - Always run
yarn buildbefore testing SDK changes - Use TypeScript project references for different build targets
src/ # TypeScript source
├── index.ts # Main SDK exports
├── utils.ts # Shared utilities
├── auth/ # Authentication API client (hand-written)
│ ├── base-auth-api.ts # Base authentication class
│ ├── client-authentication.ts # Client credential flows
│ ├── database.ts # Database connection flows
│ ├── oauth.ts # OAuth flows
│ ├── passwordless.ts # Passwordless authentication
│ └── id-token-validator.ts # JWT validation
├── management/ # Management API client
│ ├── Client.ts # Fern-generated client (READ-ONLY)
│ ├── api/ # Fern-generated API definitions (READ-ONLY)
│ ├── wrapper/ # Custom wrapper classes (SAFE TO EDIT)
│ │ └── ManagementClient.ts # Main Management API wrapper
│ ├── request-options.ts # Helper functions for API calls
│ └── tests/ # Management API tests
├── userinfo/ # UserInfo API client
├── lib/ # Shared libraries and utilities
└── auth0/ # Legacy compatibility exports
- Use strict TypeScript configuration (see
tsconfig.base.json) - Define shared types in
src/lib/models.ts - Follow existing patterns for API client implementations
- Use proper async/await patterns, avoid callbacks
- Import with
.jsextensions (TypeScript will resolve to.ts)
Every API client follows this structure:
class ApiClient {
constructor(options: ClientOptions) {
// Initialize with domain, credentials, etc.
}
async methodName(params: MethodParams): Promise<Response> {
// Implementation with proper error handling
}
}CRITICAL: Never edit Fern-generated files directly.
// ❌ Don't edit: src/management/Client.ts (Fern-generated)
// ✅ Use: src/management/wrapper/ManagementClient.ts
export class ManagementClient {
private _client: FernClient;
constructor(options: ManagementClientOptions) {
this._client = new FernClient(options);
// Custom logic, token handling, telemetry
}
}Use helper functions from src/management/request-options.ts:
import { withTimeout, withRetries, withHeaders, CustomDomainHeader } from "auth0";
const options = {
...withTimeout(30),
...withRetries(3),
...CustomDomainHeader("auth.example.com"),
};- ManagementError - For Management API errors
- AuthApiError - For Authentication API errors
- IdTokenValidatorError - For JWT validation errors
- Use
.withRawResponse()for accessing raw HTTP response data - Provide clear, actionable error messages
# All tests
yarn test
# Specific test projects
yarn test:unit # Fast unit tests
yarn test:browser # Browser compatibility tests
yarn test:wire # Integration tests with mock server
# With coverage
yarn test:coverage
yarn test:coverage:unit
# Specific test files
yarn test -- src/management/tests/ManagementClient.test.ts
# Pattern matching
yarn test -- --testNamePattern="should authenticate user"- Tests mirror
src/directory structure in correspondingtests/folders - Use
.test.tsextensions - Unit tests use mocks/stubs for external dependencies
- Integration tests use MSW (Mock Service Worker) for HTTP mocking
- Browser tests validate cross-platform compatibility
Pattern for testing Management API wrappers:
import { ManagementClient } from "../wrapper/ManagementClient.js";
describe("ManagementClient", () => {
let client: ManagementClient;
beforeEach(() => {
client = new ManagementClient({
domain: "test.auth0.com",
clientId: "test-client-id",
clientSecret: "test-client-secret",
});
});
it("should handle API calls correctly", async () => {
// Test implementation
});
});Pattern for testing Authentication API clients:
import { AuthenticationClient } from "../index.js";
import nock from "nock";
describe("AuthenticationClient", () => {
let auth0: AuthenticationClient;
beforeEach(() => {
auth0 = new AuthenticationClient({
domain: "test.auth0.com",
clientId: "test-client-id",
});
});
afterEach(() => {
nock.cleanAll();
});
});- Maintain minimum coverage thresholds (see
jest.config.mjs) - Add tests for any new API methods or features
- Test both success and error paths
- Test edge cases and validation logic
- Add method to appropriate class in
src/auth/ - Follow existing patterns for parameter validation
- Add proper TypeScript types
- Write comprehensive tests
- Update API reference documentation
- Never edit
src/management/Client.tsorsrc/management/api/(Fern-generated) - Extend
src/management/wrapper/ManagementClient.ts - Add custom methods with proper error handling
- Use helper functions from
request-options.ts - Add tests to
src/management/tests/
- Legacy exports in
legacy/exports/maintain v4 API compatibility - Use
import { ... } from 'auth0/legacy'for v4 imports - See
v5_MIGRATION_GUIDE.mdfor breaking changes - Test both new and legacy APIs when making changes
The SDK supports dual module systems:
// CommonJS (default)
const { ManagementClient } = require("auth0");
// ESM
import { ManagementClient } from "auth0";
// Legacy v4 compatibility
import { ManagementClient } from "auth0/legacy";# Always run validation before commit
yarn validateThis runs: lint → format → build → test → package validation
- All tests pass locally (
yarn test) - Code builds successfully (
yarn build) - Linting passes (
yarn lint) - Code is formatted (
yarn format) - New code has corresponding tests
- TypeScript compiles without errors
- Updated API reference if adding public methods
- Added entry to
CHANGELOG.mdif user-facing change - Tested with both CommonJS and ESM if applicable
- Verified backward compatibility
Follow conventional commits style:
feat: add support for new Management API endpointfix: resolve token refresh issue in Authentication clientdocs: update Management API examplestest: add coverage for passwordless authenticationrefactor: simplify error handling in base client
- Never commit Auth0 credentials, client secrets, or tokens
- Use environment variables for sensitive configuration
- Example configs use placeholder values
- Test configurations should use dedicated development tenants
- All inputs validated before API calls
- Proper sanitization of user-provided data
- JWT validation follows security best practices
- Rate limiting and retry logic implemented
- Use dedicated development/testing tenants only
- Never run tests against production tenants
- Store credentials in environment variables
- Clean up test resources after test runs
# Set environment variable for verbose logging
export DEBUG=auth0:*
yarn test- Build errors: Check TypeScript configuration and import paths
- Fern generation conflicts: Never edit auto-generated files
- Module resolution: Ensure
.jsextensions in imports - Test failures: Check mock server setup in wire tests
- Type errors: Verify all imports resolve correctly
# Check compiled output structure
ls -la dist/cjs/ dist/esm/
# Validate package exports
yarn lint:package
# Run specific test suite with verbose output
yarn test:unit --verbose
# Check TypeScript compilation
tsc --noEmit --project ./tsconfig.base.json
# Analyze bundle size
du -sh dist/- SDK Entry (
src/index.ts) → Export all public APIs - Client Initialization → Authentication or Management client
- Method Call → Route to appropriate API handler
- Request Processing → Add authentication, headers, retries
- HTTP Client → Make actual API call to Auth0
- Response Processing → Parse response, handle errors
- Return Result → Typed response to consumer
- Management API uses Fern-generated code for type safety
- Generated files are read-only - never edit directly
- Custom logic goes in wrapper classes
- Fern handles OpenAPI spec changes automatically
auth0 (main export)
├── ManagementClient (tenant administration)
├── AuthenticationClient (user authentication)
├── UserInfoClient (user profile data)
└── Legacy exports (v4 compatibility)
- Migration Guide:
v5_MIGRATION_GUIDE.md - API Reference:
reference.md - Full Documentation: auth0.com/docs
- TypeScript Docs: Generated in
docs/directory - Examples: See README.md for usage examples
// Authentication Client
const auth0 = new AuthenticationClient({
domain: "your-tenant.auth0.com",
clientId: "your-client-id",
clientSecret: "your-client-secret", // Optional
});
// Management Client
const management = new ManagementClient({
domain: "your-tenant.auth0.com",
clientId: "your-client-id",
clientSecret: "your-client-secret",
scope: "read:users create:users", // Optional
});src/index.ts- Main SDK exportssrc/management/wrapper/ManagementClient.ts- Management API wrappersrc/auth/- All Authentication API clientssrc/management/request-options.ts- Request configuration helperssrc/lib/models.ts- Shared TypeScript typesjest.config.mjs- Test configuration with multiple projects- Files marked "auto-generated by Fern" - READ-ONLY
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_CLIENT_ID=your-test-client-id
AUTH0_CLIENT_SECRET=your-test-client-secret
AUTH0_M2M_TOKEN=your-machine-to-machine-token