API Reference
Complete API reference for Supernal TTS
📚 Supernal TTS API Documentation
:::caution Under Development The Supernal TTS API is currently in active development. Some features may be incomplete, unstable, or subject to breaking changes. Please use with caution in production environments. :::
Base URL
https://tts.supernal.ai/api/v1
Authentication
Currently, the API is open for development. In production, add authentication headers:
Authorization: Bearer YOUR_API_KEY
Endpoints
1. Generate Audio
Generate TTS audio from text, with automatic caching.
Endpoint: POST /generate
Request Body:
{
"text": "The text to convert to speech",
"options": {
"provider": "openai", // optional: openai, cartesia, azure, mock
"voice": "fable", // optional: provider-specific voice
"speed": 1.0, // optional: 0.25 to 4.0
"format": "mp3", // optional: mp3, wav, ogg
"quality": "medium", // optional: low, medium, high
"language": "en-US", // optional: language code
"cache": true, // optional: enable caching (default: true)
"ttl": 86400, // optional: cache TTL in seconds
"private": false // optional: owner-only audio, see "Private audio" below
},
"metadata": {
"contentId": "blog-post-123",
"userId": "user-456",
"tags": ["blog", "tech"],
"priority": 1
}
}
Response:
{
"hash": "a1b2c3d4e5f6...",
"audioUrl": "/api/v1/audio/a1b2c3d4e5f6",
"cached": false,
"duration": 12.5,
"cost": 0.0045,
"metadata": {
"provider": "openai",
"voice": "fable",
"generatedAt": "2024-01-20T10:30:00Z",
"fileSize": 245760
}
}
Status Codes:
200- Success400- Invalid request429- Rate limit exceeded500- Server error
Example:
curl -X POST https://tts.supernal.ai/api/v1/generate \
-H "Content-Type: application/json" \
-d '{
"text": "Hello world!",
"options": {
"provider": "openai",
"voice": "nova"
}
}'
Private audio
Set "private": true in options when the narration must not be shared, for example a story a buyer paid for. A private result behaves differently from normal cached audio:
- It is stored under a random id that starts with
prv_, not under a hash of the text. Nobody can work the id out from the text. /hash-lookupand/hash-existsnever find it, and it never fills the shared cache. A later public request for the same text generates fresh audio.- The server keeps no copy of the text with it. Its metadata returns an empty
originalText. - Only the key or user token that generated it can read it. A request without credentials gets
401. Any other key gets404. - It is always sent with
Cache-Control: private, no-store. - It expires 90 days after generation (operators can change this with
TTS_PRIVATE_AUDIO_TTL_DAYS). The response carriesexpiresAt, and after that time the audio answers404, even to its owner. - Each owner can make 50 private generations per day (
TTS_PRIVATE_DAILY_CAP). Past that the API answers429 PRIVATE_DAILY_CAP_EXCEEDED. A generation that fails still counts. - The text may be at most 20,000 characters (
TTS_PRIVATE_MAX_CHARS). A request whose audio could exceed 50 MB (TTS_PRIVATE_MAX_BYTES) is refused before any provider is called, with400 PRIVATE_TEXT_TOO_LONGor400 PRIVATE_AUDIO_TOO_LARGE. Uncompressed formats reach that limit sooner. - The owner can delete it with
DELETE /audio/{id}. Any other caller gets404, and the route does not delete public audio.
On deployed storage (Supabase or Redis+S3) only a user (JWT) token can own private audio. sk-tts- API keys are kept in server memory and get new ids when the server restarts, so they are refused there. On local disk storage, which private mode allows only when NODE_ENV is development or test, a sk-tts- key used from a server (no Origin header) can own it. Browser keys paired to a website origin are shared by every visitor of that site and can never own private audio. Every refusal answers 403 PRIVATE_REQUIRES_OWNER. The HTML converter (POST /api/convert-html with "private": true) needs the same user token in its Authorization header. It answers 401 for an invalid or expired token, skips the shared URL cache, and returns "private": true, "requiresAuth": true and Cache-Control: private, no-store. Fetch the returned audioUrl with the token as a bearer header; a plain <audio src> cannot play it. Because an <audio> tag cannot send an Authorization header, play private audio through your own backend, which fetches it with the owner's token and passes it to the buyer.
The response looks like a normal generate response, with "private": true, the prv_ id in hash and audioUrl, and no hashes field. Private mode works on POST /generate only. POST /generate-progressive answers 400 PRIVATE_NOT_SUPPORTED.
If the server has no private storage set up, private requests get 503 PRIVATE_MODE_NOT_CONFIGURED before any provider is called. The operator must set TTS_PRIVATE_AUDIO_SECRET (32 or more random characters, different from JWT_SECRET; the server refuses to start with a weak one) and, with Supabase storage, SUPABASE_PRIVATE_BUCKET. That bucket must exist and be non-public; the server checks it at startup and leaves private mode off if it is public or missing. Private metadata goes to the service-role-only table private_audio_metadata, never to audio_metadata. On deployed storage the server also needs REDIS_URL, so the daily cap is shared across instances and survives restarts; without it private requests get 503. The server checks the private bucket once, at startup; if it is missing or public, private mode stays off (503) until the process restarts. After changing bucket settings an operator must restart the server. That check only reads the bucket's public flag, so the operator must also keep storage.objects policies closed for that bucket: no policy may let anon or authenticated read it.
Rotating TTS_PRIVATE_AUDIO_SECRET cuts every owner off from their existing private audio, because each id is signed with the secret in force when it was made. After a rotation the old ids answer 404 to everyone, including their owners, and the files stay in storage until an operator deletes them.
Expired audio stops being served at once but stays stored until an operator purges it. Run node scripts/purge-expired-private-audio.mjs with SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY and TTS_SUPABASE_PROJECT_REF (the project ref in that URL; the script refuses to run if they differ) set, on any schedule. It is safe to re-run, works oldest first, and logs and skips any item it cannot remove so the next run retries it. It does the same as these two steps by hand: first remove the files listed by SELECT s3_bucket, s3_key FROM public.private_audio_metadata WHERE expires_at < now(); from their bucket (Storage API remove, or the dashboard), then run DELETE FROM public.private_audio_metadata WHERE expires_at < now();. Remove the files first: a row deleted before its file leaves a file nothing points to.
2. Generate Audio (Progressive Streaming)
Generate audio with progressive streaming using Server-Sent Events (SSE). Ideal for long-form content.
Endpoint: POST /generate-progressive
Request Body: Same as /generate
Response: Server-Sent Events stream
Event Types:
// Started event
{
"type": "started",
"totalChunks": 5
}
// Progress events
{
"type": "progress",
"completed": 3,
"total": 5,
"progress": 60
}
// Complete event
{
"type": "complete",
"hash": "a1b2c3d4e5f6...",
"audioUrl": "/api/v1/audio/a1b2c3d4e5f6",
"duration": 12.5,
"chunks": 5,
"parallelTime": 2.3,
"metadata": {
"provider": "openai",
"voice": "fable",
"generatedAt": "2024-01-20T10:30:00Z",
"fileSize": 245760
}
}
// Error event
{
"type": "error",
"message": "Error description"
}
Example:
const eventSource = new EventSource('/api/v1/generate-progressive', {
method: 'POST',
body: JSON.stringify({
text: "Your long text here...",
options: { provider: "openai", voice: "nova" }
})
});
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'progress') {
console.log(`Progress: ${data.progress}%`);
} else if (data.type === 'complete') {
console.log('Audio ready:', data.audioUrl);
eventSource.close();
}
};
3. Retrieve Audio
Get the generated audio file by hash.
Endpoint: GET /audio/{hash}
Public audio needs no credentials and is sent with Cache-Control: public, max-age=31536000. A prv_ id needs the owning key, as described under "Private audio".
The endpoint honours a single byte range, so players can seek. Range: bytes=0-1023 returns 206 Partial Content with Content-Range: bytes 0-1023/<size>. Open-ended (bytes=1024-) and suffix (bytes=-500) ranges work too. A well-formed range that starts past the end of the file returns 416 with Content-Range: bytes */<size>. A malformed Range header is ignored and the whole file comes back with 200. A request for several separate ranges gets the whole file with 200.
Response: Audio file (binary)
Headers:
Content-Type: audio/mpeg
Content-Length: 245760
Cache-Control: public, max-age=31536000
Accept-Ranges: bytes
Example:
curl https://tts.supernal.ai/api/v1/audio/a1b2c3d4e5f6 -o output.mp3
4. Get Audio Metadata
Retrieve metadata about a cached audio file without downloading it.
Endpoint: GET /audio/{hash}/metadata
Response:
{
"hash": "a1b2c3d4e5f6",
"provider": "openai",
"voice": "nova",
"language": "en-US",
"format": "mp3",
"duration": 1.2,
"fileSize": 24576,
"generatedAt": "2024-01-20T10:30:00Z",
"lastAccessedAt": "2024-01-20T11:00:00Z",
"accessCount": 5
}
5. Check Audio Exists
Check if audio exists without downloading it (HEAD request).
Endpoint: HEAD /audio/{hash}
Returns the same headers as GET, including Content-Length, and no body. A Range header gives the 206 headers for that range. Private ids follow the same access rules as GET.
Response:
200- Audio exists (with Content-Length header)404- Audio not found
Example:
curl -I https://tts.supernal.ai/api/v1/audio/a1b2c3d4e5f6
6. Estimate Cost
Estimate the cost of generating audio without actually generating it.
Endpoint: POST /estimate
Request Body:
{
"text": "Your text here",
"options": {
"provider": "openai",
"quality": "high"
}
}
Response:
{
"cost": 0.0045,
"characterCount": 150,
"currency": "USD"
}
7. Get Available Providers
List all configured providers.
Endpoint: GET /providers
Response:
{
"providers": ["openai", "mock"]
}
8. List Supported Voices
Get available voices for a provider.
Endpoint: GET /voices?provider={provider}
Query Parameters:
provider(optional) - Filter by provider (e.g., "openai")
Response:
{
"voices": [
"alloy",
"echo",
"fable",
"onyx",
"nova",
"shimmer",
"coral"
]
}
9. Get Hash Information
Get all hash variants (direct, content, semantic) for given text and options.
Endpoint: POST /hash-info
Auth: required. Send an API key or user token; anonymous requests get 401.
Request Body:
{
"text": "Your text here",
"options": {
"provider": "openai",
"voice": "nova"
}
}
Response:
{
"hashes": {
"direct": "a1b2c3d4e5f6...",
"content": "x7y8z9...",
"semantic": "m3n4o5..."
},
"text": {
"original": "Your text here",
"length": 15
}
}
10. Lookup Cached Audio by Hash
Lookup cached audio using different hash modes with optional fallback.
Endpoint: POST /hash-lookup
Requires an API key or user token. Without one the endpoint answers 401. Private audio is never reported.
Request Body:
{
"text": "Your text here",
"options": {
"provider": "openai",
"voice": "nova"
},
"hashMode": "semantic", // "direct", "content", or "semantic"
"allowFallback": true // optional: try other hash modes if not found
}
Response (found):
{
"found": true,
"hash": "a1b2c3d4e5f6...",
"mode": "semantic",
"confidence": 0.95,
"audioUrl": "/api/v1/audio/a1b2c3d4e5f6",
"metadata": {
"provider": "openai",
"voice": "nova",
"duration": 1.2,
"fileSize": 24576,
"generatedAt": "2024-01-20T10:30:00Z"
}
}
Response (not found):
{
"found": false,
"hashes": {
"direct": "a1b2c3...",
"content": "x7y8z9...",
"semantic": "m3n4o5..."
},
"message": "No cached audio found for this content"
}
11. Check if Content Exists
Quick check if content exists in cache without retrieving it.
Endpoint: POST /hash-exists
Requires an API key or user token. Without one the endpoint answers 401. Private audio is never reported.
Request Body:
{
"text": "Your text here",
"options": {
"provider": "openai",
"voice": "nova"
},
"hashMode": "direct" // "direct", "content", or "semantic"
}
Response:
{
"exists": true,
"hashMode": "direct",
"hashes": {
"direct": "a1b2c3d4e5f6...",
"content": "x7y8z9...",
"semantic": "m3n4o5..."
}
}
12. Delete Cached Audio (Admin)
Remove audio from cache. Requires admin authentication.
Endpoint: DELETE /cache/{hash}
Headers:
Authorization: Bearer ADMIN_API_KEY
Response:
{
"deleted": true
}
13. Get Cache Statistics (Admin)
Get overall cache statistics. Requires admin authentication.
Endpoint: GET /cache/stats
Headers:
Authorization: Bearer ADMIN_API_KEY
Response:
{
"totalEntries": 1234,
"totalSize": 1073741824,
"oldestEntry": "2024-01-01T00:00:00Z",
"newestEntry": "2024-01-20T15:30:00Z"
}
14. Clear Cache (Admin)
Clear all cached audio files. Requires admin authentication.
Endpoint: DELETE /cache
Headers:
Authorization: Bearer ADMIN_API_KEY
Response:
{
"message": "Cache cleared successfully"
}
15. Health Check
Check API health status.
Endpoint: GET /health
Response:
{
"status": "healthy",
"timestamp": "2024-01-20T10:30:00Z",
"uptime": 3600,
"environment": "production",
"version": "0.1.0"
}
Upcoming Features
The following endpoints are planned but not yet implemented:
GET /languages?provider={provider}- List supported languages by providerGET /stats/providers- Get usage statistics for each providerGET /health/ready- Kubernetes readiness probeGET /health/live- Kubernetes liveness probe
Upgrading
POST /hash-lookupandPOST /hash-existsnow require an API key. They were anonymous before.GETandHEAD /audio/{hash}now honour theRangeheader (single byte ranges,206and416).- A failed cache lookup now returns
500before any provider call.
Error Responses
All errors follow this format:
{
"error": {
"message": "Human-readable error message",
"code": "ERROR_CODE",
"provider": "openai",
"details": {
// Additional error details
}
}
}
Error Codes
| Code | Description | HTTP Status |
|---|---|---|
INVALID_VOICE | Voice not supported by provider | 400 |
INVALID_SPEED | Speed out of valid range | 400 |
INVALID_FORMAT | Audio format not supported | 400 |
PROVIDER_NOT_CONFIGURED | Provider not set up | 500 |
OPENAI_GENERATION_ERROR | OpenAI API error | 502 |
CARTESIA_GENERATION_ERROR | Cartesia API error | 502 |
AZURE_GENERATION_ERROR | Azure API error | 502 |
RATE_LIMIT_EXCEEDED | Too many requests | 429 |
Rate Limiting
Default rate limits:
- 100 requests per minute per IP
- Configurable via
API_RATE_LIMITenvironment variable
Rate limit headers:
RateLimit-Limit: 100
RateLimit-Remaining: 95
RateLimit-Reset: 1642680000
Provider-Specific Options
System Options (Free, Browser-Native)
The system provider uses the Web Speech API built into browsers. Completely free - no API calls required!
:::note Client-Side Only
The system provider runs entirely in the browser using the Web Speech API. It does not make API calls to the server - the widget handles speech synthesis locally.
:::
// Widget configuration (not API call)
SupernalTTS.init({
provider: 'system',
voice: 'Google US English', // Browser-dependent
speed: 1.0 // 0.25 to 4.0
});
Features:
- Zero cost - no API charges
- Works offline
- Instant playback (no generation delay)
- Pause/resume support
- Cross-browser: Chrome, Safari (iOS/macOS), Firefox, Edge
Voice availability varies by browser/OS:
- Chrome: "Google US English", "Google UK English Female", etc.
- Safari: "Samantha", "Alex", "Daniel", etc.
- Windows: "Microsoft David", "Microsoft Zira", etc.
OpenAI Options
{
"provider": "openai",
"voice": "coral", // alloy, echo, fable, onyx, nova, shimmer, coral
"quality": "high", // standard or high (HD)
"speed": 1.0 // 0.25 to 4.0
}
Cartesia Options
{
"provider": "cartesia",
"voice": "confident-british-man",
"speed": 1.0, // 0.5 to 2.0
"emotion": {
"positivity": 0.8, // -1 to 1
"energy": 0.6 // -1 to 1
}
}
Azure Options
{
"provider": "azure",
"voice": "en-US-JennyNeural",
"speed": 1.0, // 0.5 to 2.0
"pitch": 0 // -50 to 50 (semitones)
}
Mock Options
{
"provider": "mock",
"voice": "mock-voice-1"
}
Client SDKs
JavaScript/TypeScript
npm install @supernal-tts/client
import { TTSClient } from '@supernal-tts/client';
const client = new TTSClient({
apiUrl: 'https://tts.supernal.ai'
});
const { audioUrl } = await client.generate({
text: "Hello world!"
});
Python (Coming Soon)
from supernal_tts import TTSClient
client = TTSClient(api_url="https://tts.supernal.ai")
response = client.generate("Hello world!")
Postman Collection
Import the Postman collection for easy API testing.
OpenAPI Specification
View the OpenAPI spec for detailed schema information.
For more examples and integration guides, see the Examples section.
Changelog
- 2026-10-29:
POST /hash-infonow requires authentication (API key or user token). Anonymous requests get401.