⚡ JavaScript & Node.js Developer Guide

JavaScript Text to Speech API Quickstart

Integrate high-speed voice synthesis powered by Aura and Rapid models into web applications and server environments with production-ready security patterns.

⚠️Security Best Practice: Never Expose API Keys in Client-Side Code

Never hardcode or expose your X-API-Key in public browser bundles or frontend JavaScript. Anyone inspecting client-side requests via Browser DevTools can copy your key. Always proxy client requests through a secure backend route (e.g. Next.js API Route or Node.js Express server) where your key is safely stored in environment variables (process.env.YOURVOIC_API_KEY).

1. Getting Started & Authentication

All requests require a valid API Key in the X-API-Key header. Generate your key from your account console:

2. Secure Backend Proxy Route (Next.js / Express)

Create a server-side route handler that securely attaches your X-API-Key from server environment variables before calling the official REST endpoint.

pages/api/speech.js (Server Proxy)
// Secure Backend Route (Next.js API Route / Node.js ES Modules)
// file: pages/api/speech.js
import axios from 'axios';

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  // 🔒 Retrieve API Key safely from server environment variables
  const API_KEY = process.env.YOURVOIC_API_KEY;

  if (!API_KEY) {
    return res.status(500).json({ error: 'Server misconfiguration: Missing API Key' });
  }

  try {
    const response = await axios({
      method: 'post',
      url: 'https://yourvoic.com/api/v1/tts/generate',
      headers: {
        'X-API-Key': API_KEY, // Server-side request header
        'Content-Type': 'application/json'
      },
      data: req.body,
      responseType: 'arraybuffer' // Binary stream response
    });

    res.setHeader('Content-Type', 'audio/mpeg');
    return res.send(Buffer.from(response.data));

  } catch (error) {
    const statusCode = error.response ? error.response.status : 500;
    return res.status(statusCode).json({ error: 'TTS Backend Error' });
  }
}

Client-Side Browser Fetching

Your frontend browser JavaScript calls your internal /api/speech route to retrieve audio streams safely.

browser_client.js
// Client-Side Browser Code: Calls your backend proxy (/api/speech)
async function generateSpeechBrowser(textToSynthesize) {
  try {
    // 🔒 Calling your secure backend proxy route instead of exposing your API key
    const response = await fetch('/api/speech', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        text: textToSynthesize || 'Hello! Experience secure client-side text-to-speech synthesis.',
        model: 'aura-lite', // Options: aura-lite, aura-prime, aura-max, rapid-flash, rapid-max
        voice: 'Peter',     // Options: Peter, Kylie, Rahul, Deepika
        language: 'en-US',
        format: 'mp3'
      })
    });

    if (!response.ok) {
      throw new Error(`Speech synthesis failed with status ${response.status}`);
    }

    // Convert response stream to Web Audio Blob and play
    const audioBlob = await response.blob();
    const audioUrl = URL.createObjectURL(audioBlob);
    const audio = new Audio(audioUrl);
    await audio.play();

    console.log('Playing audio speech successfully!');
  } catch (error) {
    console.error('Client TTS Error:', error.message);
  }
}

generateSpeechBrowser();

3. Node.js Server-Side Integration (`axios` & `fs`)

For backend scripts, CLI tools, or batch processing jobs executing directly in Node.js server environments:

node_direct_tts.js
// Node.js Direct Script (Server-Side / CLI Batch Jobs)
// npm install axios

const axios = require('axios');
const fs = require('fs');

// 🔒 Load API key from environment variable
const API_KEY = process.env.YOURVOIC_API_KEY || 'YOUR_API_KEY';

async function generateSpeechNode() {
  try {
    const response = await axios({
      method: 'post',
      url: 'https://yourvoic.com/api/v1/tts/generate',
      headers: {
        'X-API-Key': API_KEY,
        'Content-Type': 'application/json'
      },
      data: {
        text: 'Synthesize speech on Node.js backend services with high-speed AI models.',
        model: 'aura-lite',
        voice: 'Peter',
        language: 'en-US',
        format: 'mp3'
      },
      responseType: 'arraybuffer'
    });

    // Write binary MP3 buffer to filesystem
    fs.writeFileSync('output_speech.mp3', response.data);
    console.log('Successfully saved audio to output_speech.mp3');

  } catch (error) {
    if (error.response) {
      console.error(`HTTP Error ${error.response.status}:`, error.response.data.toString());
    } else {
      console.error('Request Error:', error.message);
    }
  }
}

generateSpeechNode();

4. JavaScript API Options

KeyTypeDetails
textstringPlain text string for speech generation.
modelstringModel: rapid-flash, aura-lite, rapid-max, aura-prime, aura-max.
voicestringTarget voice name (e.g. Peter, Kylie, Rahul, Deepika).
formatstringAudio format: mp3 or wav.

Check Other Code Examples & Full Specs

View Python code snippets or read detailed REST API documentation.