DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

Create an AI Voice Assistant with ElevenLabs and Node.js

Introduction

If you’ve ever wanted a personal voice assistant that sounds exactly like you—or any other voice you can imagine—ElevenLabs makes it surprisingly easy. Their API delivers high‑quality text‑to‑speech (TTS) and voice‑cloning capabilities, and with a few lines of Node.js you can have a working AI assistant that speaks, listens, and responds in real time.

In this post we’ll walk through:

  • Setting up an ElevenLabs account (the link is right here: https://try.elevenlabs.io/kr07zfuqn1bp)
  • Installing the required Node.js packages
  • Building a tiny Express server that accepts text, calls the ElevenLabs TTS endpoint, and streams back an audio file
  • (Optional) Adding a voice‑cloned profile so the assistant sounds like you

By the end you’ll have a functional voice‑enabled chatbot that you can extend with your own NLP or LLM backend.


Prerequisites

What you need Why
Node.js ≥ 18 Modern fetch support and ES modules
npm or yarn Package management
ElevenLabs API key Required for authentication – get one from the affiliate link above
Microphone & speakers (or a simple curl test) To hear the assistant speak

If you don’t have an API key yet, sign up through the affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp – you’ll get a free quota to experiment with.


Installing the dependencies

Create a new folder and initialise a project:

mkdir ai-voice-assistant
cd ai-voice-assistant
npm init -y
Enter fullscreen mode Exit fullscreen mode

Now install the packages we’ll use:

npm install express multer node-fetch@2 dotenv
Enter fullscreen mode Exit fullscreen mode
  • express – lightweight HTTP server
  • multer – handles multipart form data (for future audio uploads)
  • node-fetch – makes HTTP calls to ElevenLabs (Node 18 already has fetch, but the package works across versions)
  • dotenv – loads your secret API key from a .env file

Create a .env file (add this to .gitignore later):

ELEVENLABS_API_KEY=your_api_key_here
Enter fullscreen mode Exit fullscreen mode

Setting up the ElevenLabs client

ElevenLabs’ API is straightforward: you POST JSON to /v1/text-to-speech/{voice_id} and receive an audio stream. Let’s wrap that in a small helper module.

// elevenlabs.js
import fetch from 'node-fetch';
import { Readable } from 'stream';
import dotenv from 'dotenv';
dotenv.config();

const API_KEY = process.env.ELEVENLABS_API_KEY;
const BASE_URL = 'https://api.elevenlabs.io/v1';

export async function synthesize(text, voiceId = 'EXAVITQu4vr4xnSDxMaL') {
  const url = `${BASE_URL}/text-to-speech/${voiceId}`;
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'xi-api-key': API_KEY,
      'Content-Type': 'application/json',
      'Accept': 'audio/mpeg',
    },
    body: JSON.stringify({
      text,
      voice_settings: {
        stability: 0.75,
        similarity_boost: 0.85,
      },
    }),
  });

  if (!response.ok) {
    const err = await response.text();
    throw new Error(`ElevenLabs error: ${response.status} ${err}`);
  }

  // Return a readable stream of the MP3 data
  return Readable.fromWeb(response.body);
}
Enter fullscreen mode Exit fullscreen mode

The default voiceId points to the “Rachel” voice, which is a good generic starting point. If you later create a cloned voice, replace the ID with the one you receive from ElevenLabs.


Building the Express server

Now let’s expose a /speak endpoint that accepts plain text and streams back the spoken audio.

// server.js
import express from 'express';
import { synthesize } from './elevenlabs.js';

const app = express();
app.use(express.json());

app.post('/speak', async (req, res) => {
  const { text, voiceId } = req.body;

  if (!text) {
    return res.status(400).json({ error: 'Missing "text" field' });
  }

  try {
    const audioStream = await synthesize(text, voiceId);
    res.set({
      'Content-Type': 'audio/mpeg',
      'Cache-Control': 'no-cache',
    });
    audioStream.pipe(res);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: err.message });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`🚀 Server listening on http://localhost:${PORT}`));
Enter fullscreen mode Exit fullscreen mode

Run it:

node server.js
Enter fullscreen mode Exit fullscreen mode

You now have a tiny TTS micro‑service. Test it with curl:

curl -X POST http://localhost:3000/speak \
  -H "Content-Type: application/json" \
  -d '{"text":"Hello, I am your new AI assistant!"}' \
  --output hello.mp3
Enter fullscreen mode Exit fullscreen mode

Play hello.mp3 and hear the result. If you hear clear, natural speech, congratulations—you’ve just leveraged ElevenLabs in a Node app!


Adding a cloned voice (optional but fun)

One of the coolest features of ElevenLabs is voice cloning. You can upload a short audio sample (as little as 30 seconds) and receive a voice_id that mimics the speaker.

1. Upload your sample

curl -X POST "https://api.elevenlabs.io/v1/voices/add" \
  -H "xi-api-key: $ELEVENLABS_API_KEY" \
  -F "name=MyClone" \
  -F "files[]=@/path/to/sample.wav"
Enter fullscreen mode Exit fullscreen mode

The response will contain a voice_id. Save it somewhere safe.

2. Use the cloned voice in your app

Update the request payload to include the new ID:

// client.js (example usage)
import fetch from 'node-fetch';
import fs from 'fs';

const text = "Hey, this is my own voice!";
const voiceId = 'YOUR_CLONED_VOICE_ID';

fetch('http://localhost:3000/speak', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ text, voiceId })
})
  .then(res => res.body.pipe(fs.createWriteStream('myclone.mp3')))
  .catch(console.error);
Enter fullscreen mode Exit fullscreen mode

Now the assistant will speak with your voice. This is perfect for building personalized bots, audiobooks, or even custom IVR systems.


Hooking up an LLM (quick demo)

The voice service is only half the story; you still need something to generate the response text. Here’s a minimal example that calls OpenAI’s Chat Completion API and then streams the spoken reply back to the client.

// chat.js
import fetch from 'node-fetch';
import { synthesize } from './elevenlabs.js';
import dotenv from 'dotenv';
dotenv.config();

const OPENAI_KEY = process.env.OPENAI_API_KEY;

export async function chatAndSpeak(prompt, voiceId) {
  // 1️⃣ Get a reply from the LLM
  const chatRes = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${OPENAI_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: 'gpt-4o-mini',
      messages: [{ role: 'user', content: prompt }],
    }),
  });

  const { choices } = await chatRes.json();
  const reply = choices?.[0]?.message?.content ?? 'I could not understand that.';

  // 2️⃣ Convert the reply to speech
  return synthesize(reply, voiceId);
}
Enter fullscreen mode Exit fullscreen mode

You can now replace the /speak route with a /chat route that both thinks and talks:

app.post('/chat', async (req, res) => {
  const { prompt, voiceId } = req.body;
  try {
    const audioStream = await chatAndSpeak(prompt, voiceId);
    res.set({ 'Content-Type': 'audio/mpeg' });
    audioStream.pipe(res);
  } catch (e) {
    console.error(e);
    res.status(500).json({ error: e.message });
  }
});
Enter fullscreen mode Exit fullscreen mode

Send a request:

curl -X POST http://localhost:3000/chat \
  -H "Content-Type: application/json" \
  -d '{"prompt":"What is the capital of Iceland?","voiceId":"EXAVITQu4vr4xnSDxMaL"}' \
  --output answer.mp3
Enter fullscreen mode Exit fullscreen mode

You now have a full “ask‑and‑listen” loop powered by an LLM and ElevenLabs’ TTS.


Debugging tips

Symptom Likely cause Fix
401 Unauthorized from ElevenLabs Wrong or missing API key Verify ELEVENLABS_API_KEY in .env and that the key is active
Empty MP3 file voice_settings values too low Increase stability/similarity_boost or omit the object entirely
Slow response (>5 s) Large prompt or heavy LLM call Cache frequent responses or use a smaller model
Audio distortion Streaming pipe broken Ensure you forward the response body as a stream (Readable.fromWeb) and set Content-Type: audio/mpeg

Wrap‑up

We’ve covered the whole pipeline:

  1. Create an ElevenLabs account (use the affiliate link for a quick start)
  2. Set up a Node.js server that talks to the ElevenLabs TTS endpoint
  3. Optionally clone a voice for a truly personal assistant
  4. Combine with an LLM for dynamic conversation

All of this fits into a single file or a couple of modules, making it easy to embed in larger projects like home automation, Discord bots, or mobile apps.


Call to action

Ready to give your AI assistant a voice that sounds like you—or any character you can imagine? Head over to ElevenLabs using the link below, grab your API key, and start experimenting today:

👉 https://try.elevenlabs.io/kr07zfuqn1bp

Happy coding, and may your bots speak clearly!

Top comments (0)