Skip to content

@responsivevoice/api-client

REST and WebSocket client for the ResponsiveVoice Text-to-Speech API. This is the Node.js entry point — re-exports the shared surface from ./index.common and adds the Node-only FileStorage adapter plus its factory registration. Browsers resolve to ./index.browser via the package exports map.

Defined in: src/errors.ts:28

Error thrown when an API request fails

new ApiError(
message,
status,
statusText,
url,
body?,
cause?): ApiError;

Defined in: src/errors.ts:41

ParameterType
messagestring
statusnumber
statusTextstring
urlstring
body?unknown
cause?Error

ApiError

ResponsiveVoiceError.constructor

readonly optional body?: unknown;

Defined in: src/errors.ts:36

Response body, if available

readonly optional cause?: Error;

Defined in: src/errors.ts:11

Original error that caused this error, if any

ResponsiveVoiceError.cause

message: string;

Defined in: lib.es5.d.ts:1075

ResponsiveVoiceError.message

name: string;

Defined in: lib.es5.d.ts:1074

ResponsiveVoiceError.name

optional stack?: string;

Defined in: lib.es5.d.ts:1076

ResponsiveVoiceError.stack

readonly status: number;

Defined in: src/errors.ts:30

HTTP status code of the failed request

readonly statusText: string;

Defined in: src/errors.ts:33

HTTP status text

readonly url: string;

Defined in: src/errors.ts:39

Request URL that failed

get isClientError(): boolean;

Defined in: src/errors.ts:60

Check if this error is a client error (4xx)

boolean

get isRetryable(): boolean;

Defined in: src/errors.ts:75

Check if this error is retryable Server errors (5xx) and rate limits (429) are retryable

boolean

get isServerError(): boolean;

Defined in: src/errors.ts:67

Check if this error is a server error (5xx)

boolean


Defined in: src/errors.ts:83

Error thrown when authentication fails (401/403)

new AuthError(
message,
status,
statusText,
url,
body?): AuthError;

Defined in: src/errors.ts:84

ParameterType
messagestring
statusnumber
statusTextstring
urlstring
body?unknown

AuthError

ApiError.constructor

readonly optional body?: unknown;

Defined in: src/errors.ts:36

Response body, if available

ApiError.body

readonly optional cause?: Error;

Defined in: src/errors.ts:11

Original error that caused this error, if any

ApiError.cause

message: string;

Defined in: lib.es5.d.ts:1075

ApiError.message

name: string;

Defined in: lib.es5.d.ts:1074

ApiError.name

optional stack?: string;

Defined in: lib.es5.d.ts:1076

ApiError.stack

readonly status: number;

Defined in: src/errors.ts:30

HTTP status code of the failed request

ApiError.status

readonly statusText: string;

Defined in: src/errors.ts:33

HTTP status text

ApiError.statusText

readonly url: string;

Defined in: src/errors.ts:39

Request URL that failed

ApiError.url

get isClientError(): boolean;

Defined in: src/errors.ts:60

Check if this error is a client error (4xx)

boolean

ApiError.isClientError

get isRetryable(): boolean;

Defined in: src/errors.ts:75

Check if this error is retryable Server errors (5xx) and rate limits (429) are retryable

boolean

ApiError.isRetryable

get isServerError(): boolean;

Defined in: src/errors.ts:67

Check if this error is a server error (5xx)

boolean

ApiError.isServerError


Defined in: src/voice-cache.ts:77

Client-side voice cache with multi-environment storage support.

new ClientVoiceCache(config?): ClientVoiceCache;

Defined in: src/voice-cache.ts:88

ParameterType
configVoiceCacheConfig

ClientVoiceCache

readonly enabled: boolean;

Defined in: src/voice-cache.ts:86

Whether caching is active; mirrors VoiceCacheConfig.enabled.

clear(): Promise<void>;

Defined in: src/voice-cache.ts:349

Clear the voice cache.

Promise&lt;void>

getBrowserVoiceHash(): Promise<string | null>;

Defined in: src/voice-cache.ts:321

Get the stored browser voice hash. Stored separately from voice data so it persists across API URL changes.

Promise&lt;string | null>

getVoices(): Promise<CachedVoiceData | null>;

Defined in: src/voice-cache.ts:260

Get cached voice data.

Promise&lt;CachedVoiceData | null>

Cached voice data or null if not cached / cache disabled

isFresh(data): boolean;

Defined in: src/voice-cache.ts:284

Check whether cached data is still fresh (within TTL).

ParameterType
dataCachedVoiceData

boolean

migrateVoiceCache(): Promise<void>;

Defined in: src/voice-cache.ts:113

Migrate legacy unscoped cache entries to API-key-scoped keys. Should be called once during initialization when apiKey is available.

Promise&lt;void>

setBrowserVoiceHash(hash): Promise<void>;

Defined in: src/voice-cache.ts:335

Store the browser voice hash.

ParameterType
hashstring

Promise&lt;void>

setVoices(
etag,
voices,
systemVoices): Promise<void>;

Defined in: src/voice-cache.ts:296

Store voice data in the cache.

ParameterTypeDescription
etagstringETag from the server response
voicesVoiceData[]Voice collection to cache
systemVoicesSystemVoiceResponse[] | undefinedSystem voices to cache

Promise&lt;void>

static create(config):
| ClientVoiceCache
| NoOpCache;

Defined in: src/voice-cache.ts:364

Create a ClientVoiceCache or NoOpCache based on configuration.

ParameterType
config| VoiceCacheConfig | undefined

| ClientVoiceCache | NoOpCache


Defined in: src/file-storage.ts:11

Node.js-only CacheStorageAdapter that persists voice-cache entries to a JSON file under the operating system's temp directory. Loaded lazily via dynamic import() of node:fs/node:os/node:path so browser bundlers never encounter node: built-ins. All operations are silent-fail: I/O errors (missing modules, permission denied, corrupt file) resolve to null/no-op rather than throwing.

new FileStorage(fileId): FileStorage;

Defined in: src/file-storage.ts:26

ParameterTypeDescription
fileIdstringIdentifier used to scope the temp file name (rv-voice-cache-{fileId}.json). Typically a hash of the API key so concurrent clients with different keys don't share storage.

FileStorage

getItem(key): Promise<string | null>;

Defined in: src/file-storage.ts:56

Read a stored value by key. Returns null when the key is absent, the backing file is missing/unreadable, or the runtime is not Node.js.

ParameterType
keystring

Promise&lt;string | null>

CacheStorageAdapter.getItem

removeItem(key): Promise<void>;

Defined in: src/file-storage.ts:97

Remove a stored value. Deletes the backing file when the last entry is removed. Silently no-ops when the runtime is not Node.js.

ParameterType
keystring

Promise&lt;void>

CacheStorageAdapter.removeItem

setItem(key, value): Promise<void>;

Defined in: src/file-storage.ts:73

Persist a value under key, merging into any existing JSON payload. Silently no-ops when the runtime is not Node.js or the write fails.

ParameterType
keystring
valuestring

Promise&lt;void>

CacheStorageAdapter.setItem


Defined in: src/voice-cache.ts:13

In-memory storage adapter. Lives for the process/page lifetime.

new MemoryStorage(): MemoryStorage;

MemoryStorage

getItem(key): string | null;

Defined in: src/voice-cache.ts:17

Retrieve a stored value by key, or null if absent.

ParameterType
keystring

string | null

CacheStorageAdapter.getItem

removeItem(key): void;

Defined in: src/voice-cache.ts:27

Remove the value stored under key. No-op if absent.

ParameterType
keystring

void

CacheStorageAdapter.removeItem

setItem(key, value): void;

Defined in: src/voice-cache.ts:22

Store value under key, overwriting any existing entry.

ParameterType
keystring
valuestring

void

CacheStorageAdapter.setItem


Defined in: src/errors.ts:156

Error thrown when a network error occurs

new NetworkError(
message,
url,
cause?): NetworkError;

Defined in: src/errors.ts:160

ParameterType
messagestring
urlstring
cause?Error

NetworkError

ResponsiveVoiceError.constructor

readonly optional cause?: Error;

Defined in: src/errors.ts:11

Original error that caused this error, if any

ResponsiveVoiceError.cause

message: string;

Defined in: lib.es5.d.ts:1075

ResponsiveVoiceError.message

name: string;

Defined in: lib.es5.d.ts:1074

ResponsiveVoiceError.name

optional stack?: string;

Defined in: lib.es5.d.ts:1076

ResponsiveVoiceError.stack

readonly url: string;

Defined in: src/errors.ts:158

Request URL that failed

get isRetryable(): boolean;

Defined in: src/errors.ts:169

Network errors are always retryable

boolean


Defined in: src/errors.ts:93

Error thrown when a resource is not found (404)

new NotFoundError(
message,
resource,
status,
statusText,
url,
body?): NotFoundError;

Defined in: src/errors.ts:97

ParameterType
messagestring
resourcestring
statusnumber
statusTextstring
urlstring
body?unknown

NotFoundError

ApiError.constructor

readonly optional body?: unknown;

Defined in: src/errors.ts:36

Response body, if available

ApiError.body

readonly optional cause?: Error;

Defined in: src/errors.ts:11

Original error that caused this error, if any

ApiError.cause

message: string;

Defined in: lib.es5.d.ts:1075

ApiError.message

name: string;

Defined in: lib.es5.d.ts:1074

ApiError.name

readonly resource: string;

Defined in: src/errors.ts:95

The resource that was not found

optional stack?: string;

Defined in: lib.es5.d.ts:1076

ApiError.stack

readonly status: number;

Defined in: src/errors.ts:30

HTTP status code of the failed request

ApiError.status

readonly statusText: string;

Defined in: src/errors.ts:33

HTTP status text

ApiError.statusText

readonly url: string;

Defined in: src/errors.ts:39

Request URL that failed

ApiError.url

get isClientError(): boolean;

Defined in: src/errors.ts:60

Check if this error is a client error (4xx)

boolean

ApiError.isClientError

get isRetryable(): boolean;

Defined in: src/errors.ts:75

Check if this error is retryable Server errors (5xx) and rate limits (429) are retryable

boolean

ApiError.isRetryable

get isServerError(): boolean;

Defined in: src/errors.ts:67

Check if this error is a server error (5xx)

boolean

ApiError.isServerError


Defined in: src/errors.ts:114

Error thrown when rate limited (429)

new RateLimitError(
message,
status,
statusText,
url,
retryAfter?,
body?): RateLimitError;

Defined in: src/errors.ts:118

ParameterType
messagestring
statusnumber
statusTextstring
urlstring
retryAfter?number
body?unknown

RateLimitError

ApiError.constructor

readonly optional body?: unknown;

Defined in: src/errors.ts:36

Response body, if available

ApiError.body

readonly optional cause?: Error;

Defined in: src/errors.ts:11

Original error that caused this error, if any

ApiError.cause

message: string;

Defined in: lib.es5.d.ts:1075

ApiError.message

name: string;

Defined in: lib.es5.d.ts:1074

ApiError.name

readonly optional retryAfter?: number;

Defined in: src/errors.ts:116

Time in seconds to wait before retrying, if provided by the API

optional stack?: string;

Defined in: lib.es5.d.ts:1076

ApiError.stack

readonly status: number;

Defined in: src/errors.ts:30

HTTP status code of the failed request

ApiError.status

readonly statusText: string;

Defined in: src/errors.ts:33

HTTP status text

ApiError.statusText

readonly url: string;

Defined in: src/errors.ts:39

Request URL that failed

ApiError.url

get isClientError(): boolean;

Defined in: src/errors.ts:60

Check if this error is a client error (4xx)

boolean

ApiError.isClientError

get isRetryable(): boolean;

Defined in: src/errors.ts:75

Check if this error is retryable Server errors (5xx) and rate limits (429) are retryable

boolean

ApiError.isRetryable

get isServerError(): boolean;

Defined in: src/errors.ts:67

Check if this error is a server error (5xx)

boolean

ApiError.isServerError


Defined in: src/errors.ts:210

Error thrown when API response validation fails This is for client-side validation of response data against expected schemas

new ResponseValidationError(
message,
issues,
data): ResponseValidationError;

Defined in: src/errors.ts:217

ParameterType
messagestring
issues{ message: string; path: string; }[]
dataunknown

ResponseValidationError

ResponsiveVoiceError.constructor

readonly optional cause?: Error;

Defined in: src/errors.ts:11

Original error that caused this error, if any

ResponsiveVoiceError.cause

readonly data: unknown;

Defined in: src/errors.ts:215

The raw response data that failed validation

readonly issues: {
message: string;
path: string;
}[];

Defined in: src/errors.ts:212

Detailed validation issues from Zod

message: string;
path: string;
message: string;

Defined in: lib.es5.d.ts:1075

ResponsiveVoiceError.message

name: string;

Defined in: lib.es5.d.ts:1074

ResponsiveVoiceError.name

optional stack?: string;

Defined in: lib.es5.d.ts:1076

ResponsiveVoiceError.stack

get formattedIssues(): string;

Defined in: src/errors.ts:227

Get a formatted string of all validation issues

string


Defined in: src/client.ts:93

ResponsiveVoice API Client

Provides methods to interact with the ResponsiveVoice TTS API:

  • Synthesize text to speech
  • List available voices
  • Get specific voice information
const client = new ResponsiveVoiceAPIClient({ apiKey: 'your-api-key' });
// Synthesize text
const audio = await client.synthesize({
text: 'Hello, world!',
lang: 'en-US',
});
// Play the audio
const audioElement = new Audio(audio.url);
audioElement.play();
new ResponsiveVoiceAPIClient(config): ResponsiveVoiceAPIClient;

Defined in: src/client.ts:112

Create a new ResponsiveVoice API client

ParameterTypeDescription
configResponsiveVoiceAPIClientConfigClient configuration

ResponsiveVoiceAPIClient

Error if apiKey is not provided

get baseUrl(): string;

Defined in: src/client.ts:169

Get the current base URL

string

clearVoiceCache(): Promise<void>;

Defined in: src/client.ts:456

Clear the client-side voice cache

Promise&lt;void>

getBrowserVoiceHash(): Promise<string | null>;

Defined in: src/client.ts:471

Get the stored browser voice hash. Used by core to check if browser voices changed since last report.

Promise&lt;string | null>

getCachedVoiceData(): Promise<CachedVoiceData | null>;

Defined in: src/client.ts:463

Get the raw cached voice data.

Promise&lt;CachedVoiceData | null>

getConfig(requestOptions?): Promise&lt;{
analytics: {
enabled: boolean;
};
auth?: {
exp: number;
token: string;
};
features: {
accessibilityNavigation: {
enabled: boolean;
};
exitIntent: {
enabled: boolean;
text: string | null;
};
paragraphNavigation: {
enabled: boolean;
};
speakEndPage: {
enabled: boolean;
text: string | null;
};
speakInactivity: {
enabled: boolean;
text: string | null;
};
speakLinks: {
enabled: boolean;
};
speakSelectedText: {
enabled: boolean;
};
webPlayer: {
controls: {
brand: boolean;
progress: boolean;
skip: boolean;
speed: boolean;
time: boolean;
};
enabled: boolean;
layout: {
display: "inline" | "block";
mode: "fill" | "shrink";
};
miniPlayer: {
animation: "none" | "fade" | "slide" | "pop";
enabled: boolean;
position: | "top-left"
| "top-right"
| "bottom-left"
| "bottom-right"
| {
bottom?: string;
left?: string;
right?: string;
top?: string;
};
};
navigation: {
paragraphClick: boolean;
paragraphHighlight: boolean;
};
paragraphSelector: string;
pitch?: number;
position: | "inline"
| "before"
| "after"
| {
at: "before" | "after" | "inside";
target: string;
};
rate?: number;
sanitize: {
enabled: boolean;
exclude: string[];
};
selector: string;
theme: | "neutral"
| "responsivevoice"
| {
accent?: string;
accentSoft?: string;
bg?: string;
border?: string;
fg?: string;
fill?: string;
hover?: string;
muted?: string;
track?: string;
};
voice?: | string
| {
flags?: string;
regex: string;
}
| {
gender?: "male" | "female" | "f" | "m";
isByok?: boolean;
lang?: string;
name?: string;
provider?: string;
};
volume?: number;
};
welcomeMessage: {
enabled: boolean;
text: string | null;
};
welcomeMessageOnce: boolean;
};
voice: {
name: string;
pitch: number;
rate: number;
volume: number;
};
}>;

Defined in: src/client.ts:707

Fetch the per-website configuration (features, voice profile, analytics). Returns a typed WebsiteConfigResponse validated against the Zod schema.

ParameterType
requestOptions?RequestOptions

Promise&lt;{ analytics: { enabled: boolean; }; auth?: { exp: number; token: string; }; features: { accessibilityNavigation: { enabled: boolean; }; exitIntent: { enabled: boolean; text: string | null; }; paragraphNavigation: { enabled: boolean; }; speakEndPage: { enabled: boolean; text: string | null; }; speakInactivity: { enabled: boolean; text: string | null; }; speakLinks: { enabled: boolean; }; speakSelectedText: { enabled: boolean; }; webPlayer: { controls: { brand: boolean; progress: boolean; skip: boolean; speed: boolean; time: boolean; }; enabled: boolean; layout: { display: "inline" | "block"; mode: "fill" | "shrink"; }; miniPlayer: { animation: "none" | "fade" | "slide" | "pop"; enabled: boolean; position: | "top-left" | "top-right" | "bottom-left" | "bottom-right" | { bottom?: string; left?: string; right?: string; top?: string; }; }; navigation: { paragraphClick: boolean; paragraphHighlight: boolean; }; paragraphSelector: string; pitch?: number; position: | "inline" | "before" | "after" | { at: "before" | "after" | "inside"; target: string; }; rate?: number; sanitize: { enabled: boolean; exclude: string[]; }; selector: string; theme: | "neutral" | "responsivevoice" | { accent?: string; accentSoft?: string; bg?: string; border?: string; fg?: string; fill?: string; hover?: string; muted?: string; track?: string; }; voice?: | string | { flags?: string; regex: string; } | { gender?: "male" | "female" | "f" | "m"; isByok?: boolean; lang?: string; name?: string; provider?: string; }; volume?: number; }; welcomeMessage: { enabled: boolean; text: string | null; }; welcomeMessageOnce: boolean; }; voice: { name: string; pitch: number; rate: number; volume: number; }; }>

getVoice(name, requestOptions?): Promise&lt;{
deprecated?: boolean;
fallbackVoice?: boolean;
gender?: string;
id: number;
lang?: string;
name: string;
pitch?: number;
rate?: number;
service?: "g1" | "g2" | "g3" | "g5" | "gwn" | "msv" | "oai";
timerSpeed?: number;
voiceName?: string;
volume?: number;
}>;

Defined in: src/client.ts:490

Get a specific voice by name

Retrieves detailed information about a specific system voice.

ParameterTypeDescription
namestringThe voice name to look up
requestOptions?RequestOptionsOptional request configuration

Promise&lt;{ deprecated?: boolean; fallbackVoice?: boolean; gender?: string; id: number; lang?: string; name: string; pitch?: number; rate?: number; service?: "g1" | "g2" | "g3" | "g5" | "gwn" | "msv" | "oai"; timerSpeed?: number; voiceName?: string; volume?: number; }>

Promise resolving to SystemVoice object

const voice = await client.getVoice('UK English Female');
console.log(`Voice service: ${voice.service}`);
getVoices(filters?, requestOptions?): Promise&lt;{
systemVoices: {
deprecated?: boolean;
fallbackVoice?: boolean;
gender?: string;
id: number;
lang?: string;
name: string;
pitch?: number;
rate?: number;
service?: "g1" | "g2" | "g3" | "g5" | "gwn" | "msv" | "oai";
timerSpeed?: number;
voiceName?: string;
volume?: number;
}[];
voices: {
deprecated?: boolean;
flag: string;
gender: "f" | "m";
isByok?: boolean;
lang: string;
name: string;
provider?: string;
voiceIDs: number[];
}[];
}>;

Defined in: src/client.ts:402

Retrieves the list of available voices, optionally filtered by language or gender. Without filters, results are served from the client-side cache when fresh; filtered queries always hit the network.

ParameterTypeDescription
filters?VoiceFiltersOptional filters to apply
requestOptions?RequestOptionsOptional per-request configuration

Promise&lt;{ systemVoices: { deprecated?: boolean; fallbackVoice?: boolean; gender?: string; id: number; lang?: string; name: string; pitch?: number; rate?: number; service?: "g1" | "g2" | "g3" | "g5" | "gwn" | "msv" | "oai"; timerSpeed?: number; voiceName?: string; volume?: number; }[]; voices: { deprecated?: boolean; flag: string; gender: "f" | "m"; isByok?: boolean; lang: string; name: string; provider?: string; voiceIDs: number[]; }[]; }>

Both the user-facing voices array and the personalized systemVoices array (see SystemVoice from @responsivevoice/types)

// Get all voices
const { voices } = await client.getVoices();
// Get female voices
const { voices: female } = await client.getVoices({ gender: 'female' });
// Get Spanish voices
const { voices: spanish } = await client.getVoices({ lang: 'es' });
getVoicesByLanguage(lang, requestOptions?): Promise&lt;{
deprecated?: boolean;
flag: string;
gender: "f" | "m";
isByok?: boolean;
lang: string;
name: string;
provider?: string;
voiceIDs: number[];
}[]>;

Defined in: src/client.ts:532

Get voices for a specific language

Retrieves all voices available for the specified language code.

ParameterTypeDescription
langstringBCP-47 language code (e.g., 'en-US', 'es', 'fr-FR')
requestOptions?RequestOptionsOptional request configuration

Promise&lt;{ deprecated?: boolean; flag: string; gender: "f" | "m"; isByok?: boolean; lang: string; name: string; provider?: string; voiceIDs: number[]; }[]>

Promise resolving to array of Voice objects

const germanVoices = await client.getVoicesByLanguage('de-DE');
const frenchVoices = await client.getVoicesByLanguage('fr');
refreshAuth(requestOptions?): Promise&lt;{
exp: number;
token: string;
}>;

Defined in: src/client.ts:645

Re-run the v2 browser handshake and mint a fresh AuthToken. Called by core when its current handshake token nears expiry or after a 401 from a previously-valid token. Origin verification uses the same headers as /v2/config.

ParameterType
requestOptions?RequestOptions

Promise&lt;{ exp: number; token: string; }>

reportVoices(report, requestOptions?): Promise&lt;{
count: number;
systemVoices: {
deprecated?: boolean;
fallbackVoice?: boolean;
gender?: string;
id: number;
lang?: string;
name: string;
pitch?: number;
rate?: number;
service?: "g1" | "g2" | "g3" | "g5" | "gwn" | "msv" | "oai";
timerSpeed?: number;
voiceName?: string;
volume?: number;
}[];
voices: {
deprecated?: boolean;
flag: string;
gender: "f" | "m";
isByok?: boolean;
lang: string;
name: string;
provider?: string;
voiceIDs: number[];
}[];
}>;

Defined in: src/client.ts:594

Report browser voices and receive a personalized voice collection

Sends information about available browser voices to the server, which returns an optimized voice collection for the user's browser/OS combination and subscription tier.

ParameterTypeDescription
report{ platform: { browser: string; browserVersion: string; deviceType?: "desktop" | "mobile" | "tablet"; os: string; osVersion: string; }; sdkVersion?: string; timestamp: string; voices: { default?: boolean; lang: string; localService: boolean; name: string; voiceURI: string; }[]; }Voice report containing platform info and browser voices
report.platform{ browser: string; browserVersion: string; deviceType?: "desktop" | "mobile" | "tablet"; os: string; osVersion: string; }Platform information
report.platform.browser?stringBrowser name (e.g., "Chrome", "Safari", "Firefox")
report.platform.browserVersion?stringBrowser version (e.g., "120.0.6099.109")
report.platform.deviceType?"desktop" | "mobile" | "tablet"Device type hint
report.platform.os?stringOS name (e.g., "Windows", "macOS", "iOS", "Android")
report.platform.osVersion?stringOS version (e.g., "14.2", "11", "10")
report.sdkVersion?stringClient SDK version
report.timestamp?stringClient timestamp (ISO 8601)
report.voices?{ default?: boolean; lang: string; localService: boolean; name: string; voiceURI: string; }[]List of available browser voices
requestOptions?RequestOptions & { browserVoiceHash?: string; }Optional request configuration

Promise&lt;{ count: number; systemVoices: { deprecated?: boolean; fallbackVoice?: boolean; gender?: string; id: number; lang?: string; name: string; pitch?: number; rate?: number; service?: "g1" | "g2" | "g3" | "g5" | "gwn" | "msv" | "oai"; timerSpeed?: number; voiceName?: string; volume?: number; }[]; voices: { deprecated?: boolean; flag: string; gender: "f" | "m"; isByok?: boolean; lang: string; name: string; provider?: string; voiceIDs: number[]; }[]; }>

Personalized voice collection with count

const report = {
platform: {
browser: 'Chrome',
browserVersion: '120.0.0',
os: 'Windows',
osVersion: '11',
},
voices: speechSynthesis.getVoices().map(v => ({
name: v.name,
lang: v.lang,
localService: v.localService,
voiceURI: v.voiceURI,
default: v.default,
})),
timestamp: new Date().toISOString(),
};
const response = await client.reportVoices(report);
console.log(`Received ${response.count} personalized voices`);
synthesize(options, requestOptions?): Promise&lt;{
blob: Blob;
duration?: number;
format: "mp3" | "ogg" | "wav";
prosodyApplied: ("pitch" | "rate" | "volume")[];
url: string;
}>;

Defined in: src/client.ts:194

Synthesize text to speech

Converts text to audio using the specified voice and parameters. Returns an AudioResponse with a Blob and URL that can be used for playback.

ParameterTypeDescription
options{ engine?: "g1" | "g2" | "g3" | "g5" | "gwn" | "msv" | "oai"; format?: "mp3" | "ogg" | "wav"; gender?: "male" | "female"; lang?: string; name?: string; pitch?: number; rate?: number; text: string; voice?: string; volume?: number; }Synthesis options including text, language, and voice parameters
options.engine?"g1" | "g2" | "g3" | "g5" | "gwn" | "msv" | "oai"TTS service engine to use
options.format?"mp3" | "ogg" | "wav"Audio output format
options.gender?"male" | "female"Voice gender preference
options.lang?stringBCP-47 language code (e.g., "en-US"). Required unless voice is provided.
options.name?stringSystem voice name
options.pitch?numberVoice pitch (0–2, default 1 = normal). Providers may normalize to their own scale.
options.rate?numberSpeech rate (0–2, default 1 = normal). Providers may normalize to their own scale.
options.text?stringText to synthesize (max 4000 characters)
options.voice?stringResponsiveVoice name (e.g., "UK English Male"). Resolved server-side to engine + lang.
options.volume?numberVolume (0–1, default 1 = full).
requestOptions?RequestOptionsOptional request configuration

Promise&lt;{ blob: Blob; duration?: number; format: "mp3" | "ogg" | "wav"; prosodyApplied: ("pitch" | "rate" | "volume")[]; url: string; }>

Promise resolving to AudioResponse with audio blob and URL

const audio = await client.synthesize({
text: 'Hello, world!',
voice: 'US English Female',
});
console.log(`Audio format: ${audio.format}`);
console.log(`Audio URL: ${audio.url}`);
synthesizeStream(options, requestOptions?): AsyncGenerator<StreamChunk>;

Defined in: src/client.ts:250

Synthesize text to speech with HTTP streaming.

Returns an AsyncGenerator that yields StreamChunk objects as audio data arrives from the server. The server streams audio incrementally as it is synthesized (HTTP audio streaming), reducing time-to-first-byte.

ParameterTypeDescription
options{ engine?: "g1" | "g2" | "g3" | "g5" | "gwn" | "msv" | "oai"; format?: "mp3" | "ogg" | "wav"; gender?: "male" | "female"; lang?: string; name?: string; pitch?: number; rate?: number; text: string; voice?: string; volume?: number; }Synthesis options (same as synthesize())
options.engine?"g1" | "g2" | "g3" | "g5" | "gwn" | "msv" | "oai"TTS service engine to use
options.format?"mp3" | "ogg" | "wav"Audio output format
options.gender?"male" | "female"Voice gender preference
options.lang?stringBCP-47 language code (e.g., "en-US"). Required unless voice is provided.
options.name?stringSystem voice name
options.pitch?numberVoice pitch (0–2, default 1 = normal). Providers may normalize to their own scale.
options.rate?numberSpeech rate (0–2, default 1 = normal). Providers may normalize to their own scale.
options.text?stringText to synthesize (max 4000 characters)
options.voice?stringResponsiveVoice name (e.g., "UK English Male"). Resolved server-side to engine + lang.
options.volume?numberVolume (0–1, default 1 = full).
requestOptions?RequestOptionsOptional request configuration (timeout, signal)

AsyncGenerator&lt;StreamChunk>

AsyncGenerator yielding StreamChunk objects

const chunks: Uint8Array[] = [];
for await (const chunk of client.synthesizeStream({ text: 'Hello', lang: 'en-US' })) {
if (chunk.type === 'audio') chunks.push(chunk.data);
if (chunk.type === 'end') console.log(`${chunk.totalBytes} bytes`);
}
updateBaseUrl(newUrl): void;

Defined in: src/client.ts:162

Update the base URL for subsequent requests. Called internally when X-Server-URL header is received, or externally by consumers.

ParameterType
newUrlstring

void

verifyOrigin(token, requestOptions?): Promise<VerifyOriginResponse>;

Defined in: src/client.ts:674

Submit an origin-verification token to confirm site ownership. Sent as an Authorization: Bearer credential; on success the site is marked verified. Not retried.

ParameterType
tokenstring
requestOptions?RequestOptions

Promise&lt;VerifyOriginResponse>


Defined in: src/errors.ts:9

Base error class for all API client errors

  • Error
new ResponsiveVoiceError(message, cause?): ResponsiveVoiceError;

Defined in: src/errors.ts:13

ParameterType
messagestring
cause?Error

ResponsiveVoiceError

Error.constructor
readonly optional cause?: Error;

Defined in: src/errors.ts:11

Original error that caused this error, if any

Error.cause
message: string;

Defined in: lib.es5.d.ts:1075

Error.message
name: string;

Defined in: lib.es5.d.ts:1074

Error.name
optional stack?: string;

Defined in: lib.es5.d.ts:1076

Error.stack

Defined in: src/errors.ts:191

Error thrown when all retry attempts are exhausted

new RetryExhaustedError(
message,
attempts,
lastError): RetryExhaustedError;

Defined in: src/errors.ts:198

ParameterType
messagestring
attemptsnumber
lastErrorError

RetryExhaustedError

ResponsiveVoiceError.constructor

readonly attempts: number;

Defined in: src/errors.ts:193

Number of attempts made

readonly optional cause?: Error;

Defined in: src/errors.ts:11

Original error that caused this error, if any

ResponsiveVoiceError.cause

readonly lastError: Error;

Defined in: src/errors.ts:196

The last error that occurred

message: string;

Defined in: lib.es5.d.ts:1075

ResponsiveVoiceError.message

name: string;

Defined in: lib.es5.d.ts:1074

ResponsiveVoiceError.name

optional stack?: string;

Defined in: lib.es5.d.ts:1076

ResponsiveVoiceError.stack


Defined in: src/errors.ts:177

Error thrown when a request times out

new TimeoutError(
message,
url,
timeout,
cause?): TimeoutError;

Defined in: src/errors.ts:181

ParameterType
messagestring
urlstring
timeoutnumber
cause?Error

TimeoutError

NetworkError.constructor

readonly optional cause?: Error;

Defined in: src/errors.ts:11

Original error that caused this error, if any

NetworkError.cause

message: string;

Defined in: lib.es5.d.ts:1075

NetworkError.message

name: string;

Defined in: lib.es5.d.ts:1074

NetworkError.name

optional stack?: string;

Defined in: lib.es5.d.ts:1076

NetworkError.stack

readonly timeout: number;

Defined in: src/errors.ts:179

Timeout duration in milliseconds

readonly url: string;

Defined in: src/errors.ts:158

Request URL that failed

NetworkError.url

get isRetryable(): boolean;

Defined in: src/errors.ts:169

Network errors are always retryable

boolean

NetworkError.isRetryable


Defined in: src/errors.ts:135

Error thrown when request validation fails (400)

new ValidationError(
message,
status,
statusText,
url,
errors?,
body?): ValidationError;

Defined in: src/errors.ts:139

ParameterType
messagestring
statusnumber
statusTextstring
urlstring
errors?Record&lt;string, string[]>
body?unknown

ValidationError

ApiError.constructor

readonly optional body?: unknown;

Defined in: src/errors.ts:36

Response body, if available

ApiError.body

readonly optional cause?: Error;

Defined in: src/errors.ts:11

Original error that caused this error, if any

ApiError.cause

readonly optional errors?: Record<string, string[]>;

Defined in: src/errors.ts:137

Validation error details, if provided by the API

message: string;

Defined in: lib.es5.d.ts:1075

ApiError.message

name: string;

Defined in: lib.es5.d.ts:1074

ApiError.name

optional stack?: string;

Defined in: lib.es5.d.ts:1076

ApiError.stack

readonly status: number;

Defined in: src/errors.ts:30

HTTP status code of the failed request

ApiError.status

readonly statusText: string;

Defined in: src/errors.ts:33

HTTP status text

ApiError.statusText

readonly url: string;

Defined in: src/errors.ts:39

Request URL that failed

ApiError.url

get isClientError(): boolean;

Defined in: src/errors.ts:60

Check if this error is a client error (4xx)

boolean

ApiError.isClientError

get isRetryable(): boolean;

Defined in: src/errors.ts:75

Check if this error is retryable Server errors (5xx) and rate limits (429) are retryable

boolean

ApiError.isRetryable

get isServerError(): boolean;

Defined in: src/errors.ts:67

Check if this error is a server error (5xx)

boolean

ApiError.isServerError


Defined in: src/websocket.ts:125

Persistent WebSocket client for the TTS streaming endpoint (/v2/text/stream). Maintains a single connection, demultiplexes audio frames by request ID, handles pings and exponential-backoff reconnection, and exposes the same StreamChunk iterator shape as the HTTP synthesizeStream() fallback so consumers can swap transports without reshaping their audio pipeline.

Instantiate via ResponsiveVoiceAPIClient's WebSocket transport mode; direct construction is supported for custom clients. The connection opens on first connect() or synthesizeStream() call — there is no eager handshake.

new WebSocketConnection(config): WebSocketConnection;

Defined in: src/websocket.ts:136

ParameterType
configWebSocketConnectionConfig

WebSocketConnection

get connected(): boolean;

Defined in: src/websocket.ts:158

Whether the WebSocket is currently open and ready

boolean

cancel(requestId): void;

Defined in: src/websocket.ts:319

Cancel an in-flight synthesis request.

ParameterType
requestIdstring

void

close(): void;

Defined in: src/websocket.ts:228

Close the connection gracefully.

void

connect(): Promise<void>;

Defined in: src/websocket.ts:166

Open the WebSocket connection. Resolves when the connection is open. If already connected, returns immediately.

Promise&lt;void>

synthesizeStream(request): AsyncGenerator<StreamChunk>;

Defined in: src/websocket.ts:248

Send a synthesis request and return a streaming chunk generator. The returned AsyncGenerator yields the same StreamChunk types as the HTTP synthesizeStream() method.

ParameterTypeDescription
request{ engine?: "g1" | "g2" | "g3" | "g5" | "gwn" | "msv" | "oai"; format?: "mp3" | "ogg" | "wav"; gender?: "male" | "female"; lang?: string; name?: string; pitch?: number; rate?: number; text: string; voice?: string; volume?: number; }-
request.engine?"g1" | "g2" | "g3" | "g5" | "gwn" | "msv" | "oai"TTS service engine to use
request.format?"mp3" | "ogg" | "wav"Audio output format
request.gender?"male" | "female"Voice gender preference
request.lang?stringBCP-47 language code (e.g., "en-US"). Required unless voice is provided.
request.name?stringSystem voice name
request.pitch?numberVoice pitch (0–2, default 1 = normal). Providers may normalize to their own scale.
request.rate?numberSpeech rate (0–2, default 1 = normal). Providers may normalize to their own scale.
request.textstringText to synthesize (max 4000 characters)
request.voice?stringResponsiveVoice name (e.g., "UK English Male"). Resolved server-side to engine + lang.
request.volume?numberVolume (0–1, default 1 = full).

AsyncGenerator&lt;StreamChunk>

Defined in: src/types.ts:55

Cached voice data stored in the client-side cache.

cachedAt: number;

Defined in: src/types.ts:63

Timestamp when the data was cached

etag: string;

Defined in: src/types.ts:57

ETag from the server response

optional systemVoices?: SystemVoiceResponse[];

Defined in: src/types.ts:61

Cached system voices (dense; reachable from voices[*].voiceIDs chains)

voices: VoiceData[];

Defined in: src/types.ts:59

Cached voice collection


Defined in: src/types.ts:10

Storage adapter interface for plugging in custom cache backends. All methods may return synchronously or asynchronously.

getItem(key): string | Promise<string | null> | null;

Defined in: src/types.ts:12

Retrieve a value by key, or null if not present.

ParameterType
keystring

string | Promise&lt;string | null> | null

removeItem(key): void | Promise<void>;

Defined in: src/types.ts:16

Remove the value stored under key. No-op if absent.

ParameterType
keystring

void | Promise&lt;void>

setItem(key, value): void | Promise<void>;

Defined in: src/types.ts:14

Store a value under key, overwriting any existing entry.

ParameterType
keystring
valuestring

void | Promise&lt;void>


Defined in: src/types.ts:129

Rate-limit headers surfaced from a response; a field is null when absent.

limit: number | null;

Defined in: src/types.ts:131

X-RateLimit-Limit — max requests per window.

remaining: number | null;

Defined in: src/types.ts:133

X-RateLimit-Remaining — requests left in the current window.

retryAfter: number | null;

Defined in: src/types.ts:135

Retry-After — seconds to wait, present on 429.


Defined in: src/types.ts:191

Request options for API calls

optional signal?: AbortSignal;

Defined in: src/types.ts:196

Custom signal for abort control

optional skipRetry?: boolean;

Defined in: src/types.ts:199

Skip retry logic for this request

optional timeout?: number;

Defined in: src/types.ts:193

Custom timeout for this request


Defined in: src/types.ts:141

Resolved configuration with all defaults applied

apiKey: string;

Defined in: src/types.ts:143

API key used to authenticate every request.

apiSecret: string | null;

Defined in: src/types.ts:145

Server-issued secret; null when unset (browser callers).

authHeaders:
| (() =>
| Record<string, string>
| Promise<Record<string, string>>)
| null;

Defined in: src/types.ts:147

Auth-header injection hook; null when unset (server callers using only apiKey+secret).

baseUrl: string;

Defined in: src/types.ts:151

Fully-resolved base URL for the TTS API (no trailing slash).

fetch: (input, init?) => Promise<Response>;

Defined in: src/types.ts:159

Fetch implementation (defaults to the global fetch).

MDN Reference

ParameterType
inputRequestInfo | URL
init?RequestInit

Promise&lt;Response>

onRateLimit: ((info) => void) | null;

Defined in: src/types.ts:165

Rate-limit header observer; null when unset.

onServerUrlChange: ((newUrl) => void) | null;

Defined in: src/types.ts:163

Callback invoked when the server assigns a new base URL (X-RV-Server-URL header).

onTokenRenewed: ((renewed) => void) | null;

Defined in: src/types.ts:149

Sliding-renewal pickup callback; null when unset.

retryAttempts: number;

Defined in: src/types.ts:155

Max retry attempts for transient failures.

retryDelay: number;

Defined in: src/types.ts:157

Base delay between retries in milliseconds (exponential backoff multiplies this).

timeout: number;

Defined in: src/types.ts:153

Per-request timeout in milliseconds.

voiceCache: VoiceCacheConfig;

Defined in: src/types.ts:161

Voice-cache configuration resolved with defaults applied.


Defined in: src/types.ts:69

Configuration for the ResponsiveVoice API client

apiKey: string;

Defined in: src/types.ts:71

API key — account identifier; never used as a credential alone.

optional apiSecret?: string;

Defined in: src/types.ts:79

Server-issued secret paired with apiKey. When set, the client attaches X-API-Key + X-API-Secret headers to every request. For server-to-server callers only — should not be used in browser code.

optional authHeaders?: () =>
| Record<string, string>
| Promise<Record<string, string>>;

Defined in: src/types.ts:89

Hook returning auth headers to attach to every request. Called per request, so the caller can return a fresh bearer token each time (e.g. core injects Authorization: Bearer <jwt> here after a handshake). Headers returned merge into the request, overriding any conflicting X-API-Key/X-API-Secret. May return synchronously or as a Promise — the client awaits the result.

| Record&lt;string, string> | Promise&lt;Record&lt;string, string>>

optional baseUrl?: string;

Defined in: src/types.ts:99

Base URL for the API (default: https://texttospeech.responsivevoice.org/v2)

optional fetch?: (input, init?) => Promise<Response>;

Defined in: src/types.ts:111

Custom fetch implementation (for testing or server-side usage)

MDN Reference

ParameterType
inputRequestInfo | URL
init?RequestInit

Promise&lt;Response>

optional onRateLimit?: (info) => void;

Defined in: src/types.ts:125

Hook fired on every response carrying rate-limit headers (X-RateLimit-Limit/X-RateLimit-Remaining/Retry-After). Lets callers pace requests against the advertised allowance rather than discovering the limit only by hitting 429s.

ParameterType
infoRateLimitInfo

void

optional onServerUrlChange?: (newUrl) => void;

Defined in: src/types.ts:117

Callback invoked when the server assigns a different URL via X-Server-URL header

ParameterType
newUrlstring

void

optional onTokenRenewed?: (renewed) => void;

Defined in: src/types.ts:96

Hook fired when a response carries an X-RV-Auth-Renewed header (sliding renewal piggy-back from tts-api). Receives the fresh token

  • exp so the caller can swap its stored bearer transparently.
ParameterType
renewed{ exp: number; token: string; }
renewed.expnumber
renewed.tokenstring

void

optional retryAttempts?: number;

Defined in: src/types.ts:105

Number of retry attempts for transient errors (default: 3)

optional retryDelay?: number;

Defined in: src/types.ts:108

Base delay between retries in milliseconds (default: 1000)

optional timeout?: number;

Defined in: src/types.ts:102

Request timeout in milliseconds (default: 30000)

optional voiceCache?: VoiceCacheConfig;

Defined in: src/types.ts:114

Voice cache configuration (enabled by default)


Defined in: src/retry.ts:10

Configuration for retry behavior

backoffMultiplier: number;

Defined in: src/retry.ts:21

Multiplier for exponential backoff

baseDelay: number;

Defined in: src/retry.ts:15

Base delay between retries in milliseconds

jitter: boolean;

Defined in: src/retry.ts:24

Whether to add jitter to delay times

maxAttempts: number;

Defined in: src/retry.ts:12

Maximum number of retry attempts (not including the initial request)

maxDelay: number;

Defined in: src/retry.ts:18

Maximum delay between retries in milliseconds


Defined in: src/retry.ts:41

Result of checking if an error is retryable

optional delay?: number;

Defined in: src/retry.ts:46

Suggested delay before retrying, in milliseconds

shouldRetry: boolean;

Defined in: src/retry.ts:43

Whether the operation should be retried


Defined in: src/client.ts:63

Response from POST /v2/auth/verify-origin.

origin: string;

Defined in: src/client.ts:67

The proven origin (scheme://host[:port]).

verified: boolean;

Defined in: src/client.ts:65

Whether the request origin was verified for the apiKey.


Defined in: src/types.ts:32

Configuration for the client-side voice cache.

optional apiKey?: string;

Defined in: src/types.ts:49

API key used to scope cache keys per-website (prevents cross-site cache collisions on same domain)

optional customStorage?: CacheStorageAdapter;

Defined in: src/types.ts:40

Custom storage adapter — overrides storage when provided

optional enabled?: boolean;

Defined in: src/types.ts:34

Whether caching is enabled (default: true)

optional keyPrefix?: string;

Defined in: src/types.ts:43

Key prefix for cache entries (default: 'rv-voice-cache')

optional storage?: CacheStorageType;

Defined in: src/types.ts:37

Storage backend selection (default: 'auto')

optional ttl?: number;

Defined in: src/types.ts:46

Cache TTL in seconds — cached data within this window is served without a network request (default: 300)


Defined in: src/types.ts:171

Filters for listing voices

optional browser?: string;

Defined in: src/types.ts:179

Platform context for personalized voice selection (not a filter for cache bypass)

optional browserVersion?: string;

Defined in: src/types.ts:181

Browser version (paired with browser for platform-aware voice resolution)

optional gender?: "male" | "female";

Defined in: src/types.ts:176

Filter by gender

optional lang?: string;

Defined in: src/types.ts:173

Filter by language code

optional os?: string;

Defined in: src/types.ts:183

Operating system name (paired with os_version for platform-aware voice resolution)

optional osVersion?: string;

Defined in: src/types.ts:185

Operating system version (paired with os for platform-aware voice resolution)


Defined in: src/websocket.ts:39

Configuration for constructing a WebSocketConnection. Only baseUrl is required; the rest control reconnect behaviour and authentication. Pass a WebSocket constructor to use the client outside browsers where the global WebSocket is unavailable.

optional apiKey?: string;

Defined in: src/websocket.ts:43

API key for authentication

optional autoReconnect?: boolean;

Defined in: src/websocket.ts:53

Auto-reconnect on unexpected close.

true
baseUrl: string;

Defined in: src/websocket.ts:41

Base URL of the TTS API (https://...) — will be converted to wss://

optional getAuthToken?: () => Promise<string | undefined>;

Defined in: src/websocket.ts:49

Resolves the bearer JWT to send as the token upgrade query param. Awaited on every connect() so reconnects carry a fresh, unexpired token. Returns undefined when no bearer is held (key-only upgrade).

Promise&lt;string | undefined>

optional maxReconnectAttempts?: number;

Defined in: src/websocket.ts:55

Max reconnect attempts before giving up.

5
optional pingInterval?: number;

Defined in: src/websocket.ts:51

Ping interval in ms to keep the connection alive.

25000
optional reconnectDelay?: number;

Defined in: src/websocket.ts:57

Base delay between reconnect attempts in ms (exponential backoff).

1000
optional WebSocket?: (url) => WebSocket;

Defined in: src/websocket.ts:68

Custom WebSocket constructor for environments where the global WebSocket is not available (e.g. Node.js below v22). Pass ws or any W3C-compatible implementation.

ParameterType
urlstring | URL

WebSocket

import WebSocket from 'ws';
new WebSocketConnection({ baseUrl: '...', WebSocket });
type CacheStorageType = "auto" | "localStorage" | "sessionStorage" | "filesystem" | "memory";

Defined in: src/types.ts:27

Storage type for voice cache.

  • 'auto' (default): detects environment and picks the best backend
  • 'localStorage': force browser localStorage
  • 'sessionStorage': force browser sessionStorage
  • 'filesystem': force Node.js filesystem (os.tmpdir())
  • 'memory': force in-memory Map (process/page lifetime only)
const DEFAULT_RETRY_CONFIG: RetryConfig;

Defined in: src/retry.ts:30

Default retry configuration

function calculateRetryDelay(
attempt,
config,
suggestedDelay?): number;

Defined in: src/retry.ts:90

Calculate delay for a retry attempt using exponential backoff

ParameterTypeDescription
attemptnumberThe retry attempt number (1-based)
configRetryConfigRetry configuration
suggestedDelay?numberOptional suggested delay (e.g., from Retry-After header)

number

Delay in milliseconds


function createRetryWrapper(config?): <T>(fn) => Promise<T>;

Defined in: src/retry.ts:178

Create a retry wrapper with pre-configured settings

ParameterType
configPartial&lt;RetryConfig>

&lt;T>(fn) => Promise&lt;T>


function isRetryableError(error): RetryDecision;

Defined in: src/retry.ts:52

Determine if an error is retryable

ParameterType
errorunknown

RetryDecision


function withRetry<T>(fn, config?): Promise<T>;

Defined in: src/retry.ts:130

Execute a function with retry logic

Type Parameter
T
ParameterTypeDescription
fn() => Promise&lt;T>The async function to execute
configPartial&lt;RetryConfig>Retry configuration (partial, merged with defaults)

Promise&lt;T>

The result of the function

RetryExhaustedError if all retries fail

Re-exports AudioFormat


Re-exports AudioResponse


Re-exports StreamAudioChunk


Re-exports StreamChunk


Re-exports StreamEnd


Re-exports StreamError


Re-exports StreamMetadata


Re-exports SynthesizeRequest


Re-exports SynthesizeResponse


Re-exports SystemVoice


Re-exports TTSService


Re-exports Voice


Re-exports VoiceGender