Authentication concepts and patterns in the WorkOS Node.js SDK
The WorkOS Node.js SDK provides comprehensive authentication capabilities for both server-side and client-side applications. This guide covers the core authentication concepts and patterns.
Server-side applications that can securely store secrets use an API key for authentication:
import { WorkOS } from '@workos-inc/node';// Initialize with API key (string)const workos = new WorkOS('sk_...');// Or with options objectconst workos = new WorkOS({ apiKey: 'sk_...', clientId: 'client_...'});
API keys can also be provided via the WORKOS_API_KEY environment variable:
For applications that cannot securely store secrets (browser apps, mobile apps, Electron apps, CLI tools), initialize with just a client ID:
import { WorkOS } from '@workos-inc/node';// Public client mode (no API key needed)const workos = new WorkOS({ clientId: 'client_...' });// Generate auth URL with automatic PKCEconst { url, codeVerifier } = await workos.userManagement.getAuthorizationUrlWithPKCE({ provider: 'authkit', redirectUri: 'myapp://callback', clientId: 'client_...', });// After user authenticates, exchange code for tokensconst { accessToken, refreshToken } = await workos.userManagement.authenticateWithCode({ code: authorizationCode, codeVerifier, clientId: 'client_...', });
Store codeVerifier securely on-device between generating the auth URL and handling the callback. For mobile apps, use platform secure storage (iOS Keychain, Android Keystore). For CLI apps, consider OS credential storage. The verifier must survive app restarts during the auth flow.
The refreshToken is only returned on initial authentication. Subsequent refresh operations return a new access token but may not include a new refresh token unless rotation is enabled.