DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

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

Why Voice AI Matters in Modern Web Apps

Voice is becoming the new UI for many products—from voice assistants to accessibility tools, and even interactive storytelling.

If you’re building a Next.js application that needs realistic, natural‑sounding speech, the most powerful, developer‑friendly option right now is ElevenLabs.

Their text‑to‑speech (TTS) engine supports thousands of voices, custom voice cloning, and a clean REST API that plays nicely with React, TypeScript, and server‑less functions.

Below is a step‑by‑step guide to get you from a fresh Next.js project to a fully working TTS feature using ElevenLabs. Feel free to copy, tweak, and extend it to your use case.


1. Project Setup

# Create a new Next.js app (use TypeScript if you prefer)
npx create-next-app@latest elevenlabs-demo --typescript

cd elevenlabs-demo
Enter fullscreen mode Exit fullscreen mode

Install a few handy packages:

npm i axios   # HTTP client
npm i react-icons   # Optional icon set for UI
Enter fullscreen mode Exit fullscreen mode

2. Get Your ElevenLabs API Key

  1. Sign up or log in at the official ElevenLabs portal.
  2. Navigate to API → Generate Key.
  3. Copy the key and store it safely in a .env.local file:
ELEVENLABS_API_KEY=sk_your_key_here
Enter fullscreen mode Exit fullscreen mode

Tip: Never commit your key to version control. Use environment variables for production deployments.


3. Create a Backend Route to Call ElevenLabs

Next.js API routes let you keep secrets on the server side.

Create pages/api/speak.ts:

import type { NextApiRequest, NextApiResponse } from 'next';
import axios from 'axios';

const ELEVENLABS_API = 'https://api.elevenlabs.io/v1';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== 'POST') {
    res.setHeader('Allow', 'POST');
    return res.status(405).end('Method Not Allowed');
  }

  const { text, voiceId } = req.body;

  try {
    const response = await axios.post(
      `${ELEVENLABS_API}/text-to-speech/${voiceId}`,
      {
        text,
        voice_settings: { stability: 0.5, similarity_boost: 0.75 },
      },
      {
        headers: {
          'xi-api-key': process.env.ELEVENLABS_API_KEY,
          'Content-Type': 'application/json',
        },
        responseType: 'arraybuffer',
      }
    );

    // Return the audio data as a base64 string
    const audioBase64 = Buffer.from(response.data, 'binary').toString('base64');
    res.status(200).json({ audio: audioBase64 });
  } catch (error: any) {
    console.error('ElevenLabs error:', error.response?.data || error.message);
    res.status(500).json({ error: 'Failed to synthesize speech' });
  }
}
Enter fullscreen mode Exit fullscreen mode

What this does

  • Receives a POST request with text and voiceId.
  • Calls ElevenLabs’ TTS endpoint.
  • Returns the audio data encoded in base64 so the front‑end can play it immediately.

4. Front‑End Component to Trigger Speech

Create components/VoiceButton.tsx:

'use client';

import { useState } from 'react';

export default function VoiceButton() {
  const [isLoading, setLoading] = useState(false);

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

    const res = await fetch('/api/speak', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        text: 'Hello from ElevenLabs! This is a demo of TTS in Next.js.',
        voiceId: 'EXAVITQu4vr4xnSDxMaL', // Replace with your chosen voice
      }),
    });

    const { audio } = await res.json();
    const audioBlob = new Blob([Uint8Array.from(atob(audio), c => c.charCodeAt(0))], {
      type: 'audio/mpeg',
    });
    const url = URL.createObjectURL(audioBlob);
    const audioEl = new Audio(url);
    audioEl.play();

    setLoading(false);
  };

  return (
    <button
      onClick={handleSpeak}
      disabled={isLoading}
      className="px-4 py-2 bg-blue-600 text-white rounded"
    >
      {isLoading ? 'Generating…' : 'Speak with ElevenLabs'}
    </button>
  );
}
Enter fullscreen mode Exit fullscreen mode

Why this is neat

  • Uses the built‑in fetch API, so no extra dependencies.
  • Handles loading state and disables the button to avoid duplicate calls.
  • Works with any voice ID you want—just replace the hard‑coded value.

5. Add the Component to a Page

Open app/page.tsx (or pages/index.tsx if you’re on the classic router) and render the button:

import VoiceButton from '@/components/VoiceButton';

export default function Home() {
  return (
    <main className="flex flex-col items-center justify-center min-h-screen p-4">
      <h1 className="text-3xl font-bold mb-6">
        Text‑to‑Speech Demo with ElevenLabs
      </h1>
      <VoiceButton />
    </main>
  );
}
Enter fullscreen mode Exit fullscreen mode

Run the dev server:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Open http://localhost:3000 and click the button. You should hear the synthesized voice—thanks to ElevenLabs!


6. Going Further: Voice Cloning & Custom Voices

ElevenLabs lets you clone your own voice with just a few minutes of audio.

If you want a custom voice in your app:

  1. Upload a short clip (15–30 seconds) through the ElevenLabs web UI.
  2. Once processed, you’ll receive a voice ID.
  3. Replace the hard‑coded voiceId in the component with your custom ID.

You can also tweak the stability and similarity_boost parameters to fine‑tune the output—higher stability means less variation, while higher similarity boosts how closely the voice matches your original recording.


7. Deployment Tips

  • Serverless functions (e.g., Vercel) automatically keep your API key hidden.
  • For high‑traffic apps, consider caching the base64 audio in Redis or a CDN to reduce repeated calls to ElevenLabs.
  • Monitor API usage in the ElevenLabs dashboard to stay within your quota.

8. Wrap‑Up

You’ve now:

  • Set up a Next.js app with a secure serverless endpoint.
  • Integrated ElevenLabs’ TTS API.
  • Created a simple UI that speaks any text you give it.
  • Learned how to clone a custom voice for a truly unique experience.

ElevenLabs is the most developer‑friendly voice AI tool out there. Whether you’re building a chatbot, an accessibility feature, or a storytelling app, the combination of ElevenLabs and Next.js gives you lightning‑fast, high‑quality speech synthesis with minimal boilerplate.


Call to Action

Ready to bring natural voice to your Next.js project?

Sign up for ElevenLabs today and start experimenting with realistic TTS and voice cloning.

👉 Try ElevenLabs now: https://try.elevenlabs.io/kr07zfuqn1bp

Happy coding—and happy listening!

Top comments (0)