or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

audio

audio-processing.mdrealtime-transcription.mdspeech-to-speech.mdspeech-to-text.mdtext-to-speech.md
index.md
tile.json

client.mddocs/core/

Client Setup

Initialize and configure the ElevenLabs client for your application.

Installation

npm install @elevenlabs/elevenlabs-js

Basic Import

import { ElevenLabsClient, ElevenLabs } from "@elevenlabs/elevenlabs-js";

For CommonJS:

const { ElevenLabsClient } = require("@elevenlabs/elevenlabs-js");

Client Initialization

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;
}

Environments

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

/**
 * 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;
}

Fetch Function Types

/**
 * 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 };

Usage Examples

Basic Initialization

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();

Custom Environment

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",
});

Custom Timeouts and Retries

const client = new ElevenLabsClient({
  apiKey: "your-api-key",
  timeoutInSeconds: 300, // 5 minutes
  maxRetries: 5, // Retry failed requests up to 5 times
});

Custom Headers

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()}`,
  },
});

Custom Fetch Implementation

import { fetch as nodeFetch } from "node-fetch";

const client = new ElevenLabsClient({
  apiKey: "your-api-key",
  fetch: nodeFetch, // Use custom fetch implementation
});

Advanced Fetch Customization

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.

Logging Configuration

// 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),
    },
  },
});

Client Methods

Save Voice Preview

/**
 * 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>;

Environment Variables

The SDK supports the following environment variables:

  • ELEVENLABS_API_KEY - Your API key (used if not provided in constructor)

Best Practices

  1. Security: Never commit API keys to version control. Use environment variables or secure key management.

  2. Timeouts: Adjust timeouts based on your use case:

    • Short timeouts (60s) for quick operations
    • Long timeouts (240s+) for music generation or large file processing
  3. Retries: Default retry count (2) works well for transient failures. Increase for unreliable networks.

  4. Logging: Enable debug logging during development, disable in production for performance.

  5. Headers: Use dynamic header functions for authentication tokens that expire.

  6. Environments: Use regional endpoints (US, EU, India) for lower latency based on your location.

Related Documentation

  • Request Options - Per-request configuration overrides
  • Error Handling - Error types and handling patterns
  • Response Handling - Working with HTTP responses