Why Voice Matters in Modern Web Apps
If you’ve ever built a chatbot, a language‑learning tool, or an accessibility feature, you know that audio feedback can turn a static UI into a truly interactive experience. Users love being able to hear content read aloud, and developers love the low‑friction integration that modern TTS (text‑to‑speech) APIs provide.
Among the many services out there, ElevenLabs stands out for its natural‑sounding voices, low latency, and a generous free tier that’s perfect for hobby projects and early‑stage products. In this post I’ll walk you through adding voice to a React app using ElevenLabs’ REST API, from setting up the key to playing the audio in the browser.
Prerequisites
| What you need | Why |
|---|---|
| Node.js ≥ 14 | To run the React development server |
| React 18+ | The example uses functional components and hooks |
| ElevenLabs API key | You’ll get this after signing up via the affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp |
| Basic knowledge of fetch / async‑await | The API calls are plain fetch requests |
If you don’t have an API key yet, grab one from the link above – it’ll also give you a few free credits to experiment with.
1. Set Up a Fresh React Project
npx create-react-app elevenlabs-tts-demo
cd elevenlabs-tts-demo
npm start
You should see the default CRA page at http://localhost:3000. We’ll replace the content in src/App.js with a simple UI that accepts text and reads it aloud.
2. Store Your API Key Securely
Create a .env file in the project root (make sure it’s added to .gitignore):
REACT_APP_ELEVENLABS_API_KEY=your_api_key_here
React automatically prefixes env variables with REACT_APP_ so they’re exposed to the client bundle. Never commit this file – it’s only for local development.
3. The Core API Call
ElevenLabs offers a /v1/text-to-speech/{voice_id} endpoint that returns an audio stream (MP3). For a quick start we’ll use the default “Rachel” voice (voice_id = "EXAVITQu4vr4xnSDxMaL"). Here’s a reusable helper function:
// src/api/elevenlabs.js
export async function synthesizeSpeech(text) {
const apiKey = process.env.REACT_APP_ELEVENLABS_API_KEY;
const voiceId = "EXAVITQu4vr4xnSDxMaL"; // Rachel (default)
const response = await fetch(
`https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"xi-api-key": apiKey,
},
body: JSON.stringify({
text,
// optional: voice settings like stability, similarity_boost, etc.
voice_settings: {
stability: 0.5,
similarity_boost: 0.75,
},
}),
}
);
if (!response.ok) {
const err = await response.json();
throw new Error(`ElevenLabs error: ${err.message}`);
}
// The API returns raw audio bytes. We convert them to a Blob for playback.
const audioBlob = await response.blob();
return URL.createObjectURL(audioBlob);
}
Note: The endpoint returns an
audio/mpegstream, which we turn into a temporary URL that the<audio>element can consume.
4. Building the UI
Replace the default content in src/App.js with the following component:
import { useState } from "react";
import { synthesizeSpeech } from "./api/elevenlabs";
function App() {
const [text, setText] = useState("");
const [audioSrc, setAudioSrc] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const handleSpeak = async () => {
setLoading(true);
setError("");
try {
const src = await synthesizeSpeech(text);
setAudioSrc(src);
} catch (e) {
setError(e.message);
} finally {
setLoading(false);
}
};
return (
<div style={{ maxWidth: 600, margin: "2rem auto", fontFamily: "sans-serif" }}>
<h1>🗣️ Add Voice with ElevenLabs</h1>
<textarea
rows={4}
placeholder="Enter some text..."
value={text}
onChange={(e) => setText(e.target.value)}
style={{ width: "100%", padding: "0.5rem" }}
/>
<button
onClick={handleSpeak}
disabled={loading || !text.trim()}
style={{
marginTop: "0.5rem",
padding: "0.5rem 1rem",
cursor: loading ? "wait" : "pointer",
}}
>
{loading ? "Generating…" : "Speak"}
</button>
{error && <p style={{ color: "red" }}>{error}</p>}
{audioSrc && (
<div style={{ marginTop: "1rem" }}>
<audio controls src={audioSrc} />
</div>
)}
</div>
);
}
export default App;
When you type a sentence and hit Speak, the app sends the text to ElevenLabs, receives an MP3, and plays it back instantly. Try it out—your browser should render a smooth, human‑like voice.
5. Tweaking Voice Settings
ElevenLabs lets you control stability (how consistent the voice sounds) and similarity boost (how closely it matches the reference voice). Adjust these values in the voice_settings object of the API call to experiment with different tonalities. For example:
voice_settings: {
stability: 0.75, // higher = more steady
similarity_boost: 0.9, // higher = closer to the base voice
}
Play around to find the sweet spot for your application—whether you need a calm narration or an energetic announcer.
6. Using cURL for Quick Tests
If you just want to see the raw response without writing code, fire up a terminal:
curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/EXAVITQu4vr4xnSDxMaL" \
-H "Content-Type: application/json" \
-H "xi-api-key: YOUR_API_KEY" \
-d '{"text":"Hello from ElevenLabs!","voice_settings":{"stability":0.5,"similarity_boost":0.75}}' \
--output speech.mp3
Replace YOUR_API_KEY with the key you got from the affiliate link. The command saves an speech.mp3 file you can play locally.
7. Scaling Up: Multiple Voices & Caching
For larger apps you might want to let users pick from a catalog of voices. ElevenLabs provides a /v1/voices endpoint that returns all available voice IDs and metadata. Fetch that list once, cache it (e.g., in localStorage), and let the UI present a dropdown.
export async function fetchVoices() {
const apiKey = process.env.REACT_APP_ELEVENLABS_API_KEY;
const res = await fetch("https://api.elevenlabs.io/v1/voices", {
headers: { "xi-api-key": apiKey },
});
const data = await res.json();
return data.voices; // array of { voice_id, name, ... }
}
When a user selects a voice, simply pass the chosen voice_id to synthesizeSpeech.
8. Handling Rate Limits & Errors
ElevenLabs imposes rate limits based on your subscription tier. A typical response for a throttled request looks like:
{
"detail": "Rate limit exceeded. Try again later."
}
In the helper function we already throw an error with response.ok check. In production you might want to implement exponential back‑off or show a friendly “Try again in a few seconds” message.
9. Deploying Your Voice‑Enabled App
Once you’re happy with the local prototype, push the code to GitHub and connect it to a platform like Vercel or Netlify. Both services support environment variables, so you can store REACT_APP_ELEVENLABS_API_KEY securely in the dashboard. After deployment, your app will be accessible worldwide, and the TTS latency remains low thanks to ElevenLabs’ global edge network.
10. Next Steps
- Voice cloning: ElevenLabs also offers a cloning endpoint where you can upload a few minutes of audio and generate a custom voice. Perfect for brand mascots or personalized assistants.
- Streaming: For very long texts you can enable streaming mode, receiving audio chunks as they’re generated.
- Combine with Speech‑to‑Text: Pair ElevenLabs with a transcription service (e.g., Whisper) to build a full‑cycle voice chatbot.
Wrap‑Up
Adding natural‑sounding speech to a React app is now a matter of a few lines of code. By leveraging the ElevenLabs API you get high‑quality audio without the hassle of managing your own models. The approach we covered—environment‑based API keys, a tiny fetch wrapper, and an <audio> tag—fits cleanly into any modern front‑end stack.
Ready to give your users a voice? Grab your free ElevenLabs credits via the affiliate link, follow the steps above, and start experimenting today.
👉 Try ElevenLabs now: https://try.elevenlabs.io/kr07zfuqn1bp
Top comments (0)