Initialize and configure the ElevenLabs client for your application.
npm install @elevenlabs/elevenlabs-jsimport { ElevenLabsClient, ElevenLabs } from "@elevenlabs/elevenlabs-js";For CommonJS:
const { ElevenLabsClient } = require("@elevenlabs/elevenlabs-js");class ElevenLabsClient {
constructor(options?: ElevenLabsClient.Options);
}
interface ElevenLabsClient.Options {
/** Your ElevenLabs API key. Required (or set ELEVENLABS_API_KEY env var) */
apiKey?: string;
/** API environment to use. Defaults to Production */
environment?: ElevenLabsEnvironment | string;
/** Custom base URL for API requests */
baseUrl?: string;
/** Additional headers to include in all requests. Supplier<T> allows static values, promises, or functions */
headers?: Record<string, string | Supplier<string>>;
/** Default timeout for requests in seconds (default: 240) */
timeoutInSeconds?: number;
/** Default number of retry attempts (default: 2) */
maxRetries?: number;
/** Custom fetch implementation */
fetch?: typeof fetch;
/** Custom fetcher function for advanced fetch customization */
fetcher?: FetchFunction;
/** Request/response logging configuration. See LogConfig and ILogger types */
logging?: LogConfig | ILogger;
}const ElevenLabsEnvironment = {
Production: "https://api.elevenlabs.io",
ProductionUs: "https://api.us.elevenlabs.io",
ProductionEu: "https://api.eu.residency.elevenlabs.io",
ProductionIndia: "https://api.in.residency.elevenlabs.io",
};/**
* Logging configuration
*/
interface LogConfig {
/** Minimum log level to output (debug, info, warn, error) */
level?: "debug" | "info" | "warn" | "error";
/** Custom logger implementation */
logger?: ILogger;
/** Silence all logging */
silent?: boolean;
}
/**
* Logger interface for custom implementations
*/
interface ILogger {
debug(message: string, ...args: unknown[]): void;
info(message: string, ...args: unknown[]): void;
warn(message: string, ...args: unknown[]): void;
error(message: string, ...args: unknown[]): void;
}/**
* Custom fetch function type for advanced fetch customization
*/
type FetchFunction = <R = unknown>(args: Fetcher.Args) => Promise<APIResponse<R, Fetcher.Error>>;
/**
* Supplier type allows static values, promises, or functions
*/
type Supplier<T> = T | Promise<T> | (() => T | Promise<T>);
/**
* Arguments passed to the fetch function
*/
interface Fetcher.Args {
/** Target URL for the request */
url: string;
/** HTTP method (GET, POST, PUT, DELETE, etc.) */
method: string;
/** Content type header value */
contentType?: string;
/** Request headers (supports Supplier for dynamic values) */
headers?: Record<string, string | Supplier<string | null | undefined> | null | undefined>;
/** Query parameters to append to URL */
queryParameters?: Record<string, unknown>;
/** Request body */
body?: unknown;
/** Request timeout in milliseconds */
timeoutMs?: number;
/** Maximum number of retry attempts */
maxRetries?: number;
/** Include credentials in cross-origin requests */
withCredentials?: boolean;
/** Abort signal for canceling the request */
abortSignal?: AbortSignal;
/** Type of request body being sent */
requestType?: "json" | "file" | "bytes" | "form" | "other";
/** Expected response type */
responseType?: "json" | "blob" | "sse" | "streaming" | "text" | "arrayBuffer" | "binary-response";
/** Duplex mode for streaming */
duplex?: "half";
/** Custom fetch implementation */
fetchFn?: typeof fetch;
/** Logging configuration */
logging?: LogConfig | ILogger;
}
/**
* API response wrapper
*/
type APIResponse<Success, Failure> = SuccessfulResponse<Success> | FailedResponse<Failure>;
interface SuccessfulResponse<T> {
ok: true;
body: T;
rawResponse: RawResponse;
}
interface FailedResponse<T> {
ok: false;
error: T;
rawResponse: RawResponse;
}
/**
* Raw HTTP response (Response object minus body and functions)
*/
type RawResponse = Omit<
{ [K in keyof Response as Response[K] extends Function ? never : K]: Response[K] },
"ok" | "body" | "bodyUsed"
>;
/**
* Error types returned by the fetcher
*/
type Fetcher.Error =
| { reason: "status-code"; statusCode: number; body: unknown }
| { reason: "non-json"; statusCode: number; rawBody: string }
| { reason: "body-is-null"; statusCode: number }
| { reason: "timeout" }
| { reason: "unknown"; errorMessage: string };import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";
// Using API key directly
const client = new ElevenLabsClient({
apiKey: "your-api-key",
});
// Using environment variable
// Set ELEVENLABS_API_KEY in your environment
const client = new ElevenLabsClient();import { ElevenLabsClient, ElevenLabsEnvironment } from "@elevenlabs/elevenlabs-js";
// Use EU data residency
const client = new ElevenLabsClient({
apiKey: "your-api-key",
environment: ElevenLabsEnvironment.ProductionEu,
});
// Or use custom base URL
const client = new ElevenLabsClient({
apiKey: "your-api-key",
baseUrl: "https://custom-api.example.com",
});const client = new ElevenLabsClient({
apiKey: "your-api-key",
timeoutInSeconds: 300, // 5 minutes
maxRetries: 5, // Retry failed requests up to 5 times
});const client = new ElevenLabsClient({
apiKey: "your-api-key",
headers: {
"X-Custom-Header": "value",
// Headers can be static values
"X-Static": "static-value",
// Or promises
"X-Async": Promise.resolve("async-value"),
// Or functions
"X-Dynamic": () => `timestamp-${Date.now()}`,
},
});import { fetch as nodeFetch } from "node-fetch";
const client = new ElevenLabsClient({
apiKey: "your-api-key",
fetch: nodeFetch, // Use custom fetch implementation
});For more advanced control over request/response handling, use the fetcher option:
const client = new ElevenLabsClient({
apiKey: "your-api-key",
fetcher: async (args) => {
// Custom pre-request logic
console.log("Making request to:", args.url);
// Execute the request
const response = await fetch(args.url, {
method: args.method,
headers: args.headers,
body: args.body,
});
// Custom post-response logic
console.log("Response status:", response.status);
return response;
},
});The fetcher function receives request arguments and must return a Response object. This allows for request/response logging, metric collection, or custom error handling.
// Enable debug logging
const client = new ElevenLabsClient({
apiKey: "your-api-key",
logging: {
level: "debug",
},
});
// Silent mode
const client = new ElevenLabsClient({
apiKey: "your-api-key",
logging: {
silent: true,
},
});
// Custom logger
const client = new ElevenLabsClient({
apiKey: "your-api-key",
logging: {
logger: {
debug: (msg, ...args) => console.debug(`[DEBUG] ${msg}`, ...args),
info: (msg, ...args) => console.info(`[INFO] ${msg}`, ...args),
warn: (msg, ...args) => console.warn(`[WARN] ${msg}`, ...args),
error: (msg, ...args) => console.error(`[ERROR] ${msg}`, ...args),
},
},
});/**
* Save a voice preview to the voice library.
* Note: Use client.textToVoice.create() for full control over voice creation.
* @param requestOptions - Optional request configuration
* @returns Promise that resolves when voice is saved
*/
client.saveAVoicePreview(
requestOptions?: RequestOptions
): HttpResponsePromise<void>;The SDK supports the following environment variables:
ELEVENLABS_API_KEY - Your API key (used if not provided in constructor)Security: Never commit API keys to version control. Use environment variables or secure key management.
Timeouts: Adjust timeouts based on your use case:
Retries: Default retry count (2) works well for transient failures. Increase for unreliable networks.
Logging: Enable debug logging during development, disable in production for performance.
Headers: Use dynamic header functions for authentication tokens that expire.
Environments: Use regional endpoints (US, EU, India) for lower latency based on your location.