The official TypeScript library for the OpenAI API
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Client configuration in the OpenAI Node.js SDK covers initialization options for the OpenAI and AzureOpenAI clients, per-request customization through RequestOptions, and environment variable setup for both standard and Azure deployments.
The SDK provides flexible configuration at multiple levels:
OpenAI or AzureOpenAIRequestOptionsThis approach allows you to balance convenience (environment variables for simple scripts) with flexibility (request-level overrides for complex applications).
class OpenAI {
constructor(options?: ClientOptions): void;
}The main API client for standard OpenAI services.
Basic usage:
import { OpenAI } from 'openai';
const client = new OpenAI({
apiKey: 'sk-...',
});withOptions(options: Partial<ClientOptions>): this;Create a new client instance re-using the same options given to the current client with optional overriding. This method is useful for creating derived clients with different configurations while preserving most settings from the parent client.
Usage:
import { OpenAI } from 'openai';
// Base client with default settings
const baseClient = new OpenAI({
apiKey: 'sk-...',
organization: 'org-...',
timeout: 60000,
});
// Create a new client with modified timeout, keeping other settings
const slowClient = baseClient.withOptions({
timeout: 120000,
});
// Create a new client with different organization
const otherOrgClient = baseClient.withOptions({
organization: 'org-other',
});Common use cases:
/**
* API key setter function that returns a promise resolving to a string token.
* Invoked before each request to allow dynamic key rotation or refresh.
*/
type ApiKeySetter = () => Promise<string>;
interface ClientOptions {
apiKey?: string | ApiKeySetter | undefined;
organization?: string | null | undefined;
project?: string | null | undefined;
baseURL?: string | null | undefined;
timeout?: number | undefined;
maxRetries?: number | undefined;
defaultHeaders?: HeadersLike | undefined;
defaultQuery?: Record<string, string | undefined> | undefined;
dangerouslyAllowBrowser?: boolean | undefined;
fetchOptions?: MergedRequestInit | undefined;
fetch?: Fetch | undefined;
logLevel?: LogLevel | undefined;
logger?: Logger | undefined;
webhookSecret?: string | null | undefined;
}apiKey (string | ApiKeySetter)
API key for authentication. Can be a static string or an async function that returns a token.
process.env['OPENAI_API_KEY']OpenAIError otherwiseOpenAIError with original as cause// Static string
const client = new OpenAI({ apiKey: 'sk-...' });
// Dynamic token provider
const client = new OpenAI({
apiKey: async () => {
const token = await getAccessToken();
return token;
}
});organization (string | null)
OpenAI organization ID for API requests.
process.env['OPENAI_ORG_ID']null to explicitly disableOpenAI-Organization headerproject (string | null)
OpenAI project ID for API requests.
process.env['OPENAI_PROJECT_ID']null to explicitly disableOpenAI-Project headerbaseURL (string)
Override the default base URL for API requests.
process.env['OPENAI_BASE_URL'] or https://api.openai.com/v1timeout (number)
Maximum time in milliseconds to wait for a response.
600000 (10 minutes)maxRetries timesRequestOptionsmaxRetries (number)
Maximum number of retry attempts for transient failures.
2RequestOptionsdefaultHeaders (HeadersLike)
Default HTTP headers sent with every request.
null in request options to removedefaultQuery (Record<string, string | undefined>)
Default query parameters added to all requests.
undefined in request options to removedangerouslyAllowBrowser (boolean)
Enable browser execution of the client.
falsetrue if credentials are properly protected (e.g., API gateway, proxy)azureADTokenProvider in AzureOpenAI automatically enablesfetchOptions (MergedRequestInit)
Additional options passed to fetch calls.
Agent, SSL certificates, keepalive settingsfetchOptionsfetch (Fetch)
Custom fetch implementation.
logLevel (LogLevel)
Control logging verbosity.
type LogLevel = 'off' | 'error' | 'warn' | 'info' | 'debug';process.env['OPENAI_LOG'] or 'off'logger (Logger)
Custom logger implementation.
interface Logger {
error: (message: string, ...rest: unknown[]) => void;
warn: (message: string, ...rest: unknown[]) => void;
info: (message: string, ...rest: unknown[]) => void;
debug: (message: string, ...rest: unknown[]) => void;
}globalThis.consoledebug(), info(), warn(), error() methodslogLevel to control verbositywebhookSecret (string)
Secret for verifying webhook signatures.
process.env['OPENAI_WEBHOOK_SECRET']client.webhooks.verifySignature()class AzureOpenAI extends OpenAI {
constructor(options?: AzureClientOptions): void;
}Azure-specific OpenAI client with Azure authentication and deployment support.
Basic usage:
import { AzureOpenAI } from 'openai';
const client = new AzureOpenAI({
endpoint: 'https://my-resource.openai.azure.com/',
apiKey: 'your-azure-api-key',
apiVersion: '2024-08-01-preview',
});interface AzureClientOptions extends ClientOptions {
apiVersion?: string | undefined;
endpoint?: string | undefined;
deployment?: string | undefined;
apiKey?: string | undefined;
azureADTokenProvider?: (() => Promise<string>) | undefined;
}apiVersion (string)
Azure OpenAI API version for requests.
process.env['OPENAI_API_VERSION']OpenAIError if missing'2024-08-01-preview'api-version query parameterendpoint (string)
Azure OpenAI endpoint URL including resource name.
https://{resource-name}.openai.azure.com/process.env['AZURE_OPENAI_ENDPOINT']baseURL/openai to construct base URLdeployment (string)
Model deployment name for Azure.
/deployments/{deployment}model parameter if not specifiedapiKey (string)
Azure API key for authentication.
process.env['AZURE_OPENAI_API_KEY']azureADTokenProviderapi-key headerazureADTokenProvider (() => Promise<string>)
Function providing Microsoft Entra access tokens.
apiKeydangerouslyAllowBrowserExample with Microsoft Entra:
import { AzureOpenAI } from 'openai';
import { DefaultAzureCredential } from '@azure/identity';
const credential = new DefaultAzureCredential();
const client = new AzureOpenAI({
endpoint: 'https://my-resource.openai.azure.com/',
apiVersion: '2024-08-01-preview',
azureADTokenProvider: async () => {
const token = await credential.getToken('https://cognitiveservices.azure.com/.default');
return token.token;
}
});Per-request configuration for individual API calls.
type RequestOptions = {
method?: HTTPMethod;
path?: string;
query?: object | undefined | null;
body?: unknown;
headers?: HeadersLike;
maxRetries?: number;
timeout?: number;
fetchOptions?: MergedRequestInit;
signal?: AbortSignal | undefined | null;
idempotencyKey?: string;
defaultBaseURL?: string | undefined;
stream?: boolean | undefined;
}headers (HeadersLike)
Request-specific HTTP headers.
defaultHeaders from client confignull to remove default headermaxRetries (number)
Retry count for this specific request.
maxRetriestimeout (number)
Timeout in milliseconds for this request.
timeoutsignal (AbortSignal)
Abort signal for canceling request.
fetch callconst controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
try {
const response = await client.chat.completions.create({
model: 'gpt-4',
messages: [...],
}, { signal: controller.signal });
} finally {
clearTimeout(timeout);
}idempotencyKey (string)
Unique key for idempotency tracking.
The SDK automatically reads these environment variables if not provided in options:
OPENAI_API_KEY (required for standard OpenAI)
API key for OpenAI platform.
export OPENAI_API_KEY='sk-...'OPENAI_ORG_ID (optional)
OpenAI organization ID.
export OPENAI_ORG_ID='org-...'OPENAI_PROJECT_ID (optional)
OpenAI project ID.
export OPENAI_PROJECT_ID='proj_...'OPENAI_BASE_URL (optional)
Custom base URL for requests.
export OPENAI_BASE_URL='https://api.example.com/v1'OPENAI_LOG (optional)
Logging level: 'debug', 'info', 'warn', 'error'
export OPENAI_LOG='debug'OPENAI_WEBHOOK_SECRET (optional)
Secret for webhook signature verification.
export OPENAI_WEBHOOK_SECRET='whsec_...'Azure-specific environment variables:
import { OpenAI } from 'openai';
// Uses OPENAI_API_KEY from environment
const client = new OpenAI();
// Explicit API key
const client = new OpenAI({
apiKey: 'sk-...',
});import { AzureOpenAI } from 'openai';
// Using API key
const client = new AzureOpenAI({
endpoint: 'https://my-resource.openai.azure.com/',
apiKey: 'your-key',
apiVersion: '2024-08-01-preview',
});
// Using deployment
const client = new AzureOpenAI({
endpoint: 'https://my-resource.openai.azure.com/',
apiKey: 'your-key',
apiVersion: '2024-08-01-preview',
deployment: 'gpt-4-deployment',
});import { OpenAI } from 'openai';
// Use proxy or custom API
const client = new OpenAI({
apiKey: 'sk-...',
baseURL: 'https://proxy.example.com/openai/v1',
});
// Per-request override
const response = await client.chat.completions.create({
model: 'gpt-4',
messages: [...],
}, {
defaultBaseURL: 'https://alternate-proxy.example.com/v1',
});import { OpenAI } from 'openai';
import { HttpProxyAgent, HttpsProxyAgent } from 'http-proxy-agent';
const httpAgent = new HttpProxyAgent('http://proxy.example.com:8080');
const httpsAgent = new HttpsProxyAgent('https://proxy.example.com:8080');
const client = new OpenAI({
apiKey: 'sk-...',
fetchOptions: {
agent: httpAgent, // Node.js HTTP agent
},
});import { OpenAI } from 'openai';
// Custom timeout and retries
const client = new OpenAI({
apiKey: 'sk-...',
timeout: 30000, // 30 seconds
maxRetries: 3, // Retry up to 3 times
});
// Per-request override
const response = await client.chat.completions.create({
model: 'gpt-4',
messages: [...],
}, {
timeout: 60000, // 60 seconds for this request
maxRetries: 1, // Only 1 retry for this request
});import { OpenAI } from 'openai';
const client = new OpenAI({
apiKey: 'sk-...',
defaultHeaders: {
'X-Custom-Header': 'value',
'X-Correlation-ID': generateTraceId(),
},
});
// Remove default header for specific request
const response = await client.chat.completions.create({
model: 'gpt-4',
messages: [...],
}, {
headers: {
'X-Custom-Header': null, // Remove this header
},
});import { OpenAI } from 'openai';
// Enable browser usage (only with appropriate security measures)
const client = new OpenAI({
apiKey: 'sk-...',
dangerouslyAllowBrowser: true,
});
// WARNING: This exposes your API key to the client browser.
// Only use with:
// - Proxies that hide the real API key
// - API gateways that enforce auth
// - Time-limited tokensimport { OpenAI } from 'openai';
const client = new OpenAI({ apiKey: 'sk-...' });
// Override headers, timeout, retries per request
const response = await client.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: 'Hello' }],
}, {
headers: {
'X-Request-ID': generateRequestId(),
},
timeout: 120000,
maxRetries: 0, // Don't retry this request
signal: abortController.signal,
});import { OpenAI } from 'openai';
async function getAccessToken() {
// Fetch from your token service
return 'sk-...';
}
const client = new OpenAI({
apiKey: getAccessToken, // Function called before each request
});
// Keys automatically refreshed on each request
const response = await client.chat.completions.create({
model: 'gpt-4',
messages: [...],
});Never commit API keys to version control
.gitignore for .env filesProtect keys in browser environments
dangerouslyAllowBrowser: true with backend proxyRotate credentials regularly
# Development (.env file - add to .gitignore)
OPENAI_API_KEY=sk-...
OPENAI_ORG_ID=org-...
# Production (use secrets management)
# AWS: AWS Secrets Manager, Parameter Store
# Azure: Key Vault
# Google Cloud: Secret Manager
# GitHub: Secrets (for CI/CD)import { OpenAI } from 'openai';
import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';
async function initializeClient() {
const secretsClient = new SecretsManagerClient({ region: 'us-east-1' });
const response = await secretsClient.send(
new GetSecretValueCommand({ SecretId: 'openai-api-key' })
);
const apiKey = response.SecretString;
return new OpenAI({ apiKey });
}
const client = await initializeClient();import { OpenAI } from 'openai';
const client = new OpenAI({
apiKey: 'sk-...',
logLevel: 'info', // Log requests for audit trail
});Use organization and project IDs to scope API access:
const client = new OpenAI({
apiKey: 'sk-...',
organization: 'org-...', // Restrict to organization
project: 'proj_...', // Further restrict to project
});This enables:
Install with Tessl CLI
npx tessl i tessl/npm-openai