DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

Integrating ElevenLabs with Next.js: Step-by-Step Guide

Why Text‑to‑Speech Is a Game‑Changer for Modern Apps

If you’ve been building web or mobile experiences lately, you’ve probably seen how much more engaging content feels when it’s spoken. From accessibility to on‑the‑go consumption, voice can turn a static page into a dynamic conversation partner. That’s why I’m excited to share a step‑by‑step guide to integrating ElevenLabs’ voice‑AI into a Next.js project. ElevenLabs gives you high‑quality, customizable voices with a straightforward API, making it the go‑to choice for developers who want to add speech without wrestling with low‑level synthesis code.

Prerequisites

  • Node.js ≥ 14
  • A fresh or existing Next.js 13 (or newer) application
  • An ElevenLabs API key (get one at https://try.elevenlabs.io/kr07zfuqn1bp)
  • Basic knowledge of React hooks and server‑less API routes

Step 1: Set Up Your Project

First, create or navigate to your Next.js app:

npx create-next-app@latest voice-demo
cd voice-demo
Enter fullscreen mode Exit fullscreen mode

Add the ElevenLabs SDK (or just use fetch, but the SDK simplifies request building):

npm i elevenlabs
Enter fullscreen mode Exit fullscreen mode

Create a .env.local file at the root of your project and add:

ELEVENLABS_API_KEY=YOUR_ELEVENLABS_KEY
Enter fullscreen mode Exit fullscreen mode

⚡️ Tip: Never commit your .env.local to Git. Add it to .gitignore if it’s missing.


Step 2: Build a Server‑Side API Route

Next.js lets you create API routes that run on the server, keeping your API key hidden. In app/api/tts/route.js (or pages/api/tts.js if you’re on the older pages router) add:

import { ElevenLabs } from "elevenlabs";

const eleven = new ElevenLabs({
  apiKey: process.env.ELEVENLABS_API_KEY,
});

export async function POST(request) {
  const { text, voiceId } = await request.json();

  try {
    const audioBuffer = await eleven.textToSpeech({
      text,
      voice: voiceId || "Rachel", // Default voice
    });

    // Return the audio as a binary response
    return new Response(audioBuffer, {
      headers: {
        "Content-Type": "audio/mpeg",
        "Content-Disposition": "attachment; filename=voice.mp3",
      },
    });
  } catch (error) {
    console.error(error);
    return new Response(JSON.stringify({ error: "Failed to synthesize" }), {
      status: 500,
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

👉 The ElevenLabs SDK automatically handles authentication, retries, and rate‑limiting for you.


Step 3: Create a Front‑End Component

Now let’s build a simple UI that lets users type text and hear it back. In app/page.js (or wherever you prefer) add:

"use client";

import { useState } from "react";

export default function VoiceDemo() {
  const [text, setText] = useState("");
  const [loading, setLoading] = useState(false);
  const [audioUrl, setAudioUrl] = useState("");

  const handleSpeak = async () => {
    setLoading(true);
    setAudioUrl("");

    const res = await fetch("/api/tts", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ text }),
    });

    if (!res.ok) {
      alert("Error generating speech");
      setLoading(false);
      return;
    }

    const blob = await res.blob();
    const url = URL.createObjectURL(blob);
    setAudioUrl(url);
    setLoading(false);
  };

  return (
    <div className="p-8">
      <h1 className="text-2xl font-bold mb-4">ElevenLabs Text‑to‑Speech Demo</h1>
      <textarea
        className="w-full border rounded p-2 mb-4"
        rows={4}
        placeholder="Type something to hear it spoken..."
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
      <button
        onClick={handleSpeak}
        disabled={loading || !text.trim()}
        className="px-4 py-2 bg-blue-600 text-white rounded disabled:opacity-50"
      >
        {loading ? "Speaking…" : "Speak"}
      </button>

      {audioUrl && (
        <div className="mt-6">
          <audio controls src={audioUrl} />
        </div>
      )}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

That’s it—type in the textarea, click Speak, and you’ll hear ElevenLabs’ voice in your browser.


Step 4: Add Voice Cloning (Optional)

If you want to go beyond stock voices, ElevenLabs offers voice cloning. First, upload an audio sample:

curl -X POST \
  https://api.elevenlabs.io/v1/voice-clone \
  -H "xi-api-key: $ELEVENLABS_API_KEY" \
  -F "audio=@/path/to/your/sample.wav"
Enter fullscreen mode Exit fullscreen mode

ElevenLabs will return a voice_id. Store that ID and pass it to the voice field in the API route. That way, you can synthesize speech in a custom voice that sounds like your own or a brand mascot.


Step 5: Handle Streaming (Advanced)

For real‑time applications, you might want to stream the audio back to the client. ElevenLabs supports streaming via ReadableStream. In the API route, replace the buffer logic with:

const audioStream = await eleven.textToSpeechStream({
  text,
  voice: voiceId,
});

return new Response(audioStream, {
  headers: { "Content-Type": "audio/mpeg" },
});
Enter fullscreen mode Exit fullscreen mode

On the client, you can consume the stream with the Web Audio API or a library like react-use-audio-player.


Best Practices

Tip Why it matters
Keep the API key server‑side Prevents accidental exposure in the browser bundle
Cache responses Reduces API calls for repeated phrases
Respect rate limits ElevenLabs enforces per‑minute limits; handle 429 responses gracefully
Use environment variables for different stages NEXT_PUBLIC_ELEVENLABS_API_KEY for client‑side only if you must (rare)

Wrap‑Up

Integrating ElevenLabs into a Next.js app is a breeze:

  1. Install the SDK and store your key in .env.local.
  2. Create a server‑side API route that calls textToSpeech.
  3. Build a client component that posts to that route and plays the returned audio.
  4. (Optional) Add voice cloning or streaming for advanced use cases.

ElevenLabs’ API is designed for developers, so you can focus on building features rather than wrestling with low‑level synthesis. Whether you’re creating an accessible learning platform, a voice‑enabled chatbot, or a personalized audiobook, the combination of ElevenLabs and Next.js gives you the power to bring speech to life.


Ready to give your app a voice?

If you’re interested in adding high���quality, customizable TTS to your projects, check out ElevenLabs here: https://try.elevenlabs.io/kr07zfuqn1bp. Their free tier is generous, and you’ll get a solid set of voices plus the option to clone your own. Happy coding—and happy listening!

Top comments (0)