Using the ElevenLabs API in NodeJS

NicolasBrondinBernard

Author
@NicolasBrondinBernard

Generate text-to-speech voices with the best AI service, all in NodeJS!

Article published on 04/06/2025, last updated on 10/08/2026

In this tutorial, you're going to discover that generating voices with ElevenLabs directly from the API is super simple!

Let's start with the first step, the least fun but essential one for the rest of the tutorial: setting up the project.

Setting up the project

Getting your API key

First of all, you should know that every audio generation on ElevenLabs uses credits from the platform.

But good news, the free plan provides 10,000 credits per month (that's about 10 minutes of audio)

And if needed, you can take out a subscription for a few euros to get more additional credits (30,000 credits for $5)!

To start using your tokens, you need to get your API key. To do so, go to: https://elevenlabs.io/app/settings/api-keys

In the left menu, click on My Account, then on Api Keys

You'll then be able to click on the "Create API Key" button, choose a name, and copy the key that will be generated for you.

elevenlabs.jpg

Storing your key

Make sure to store your key in a configuration file called .env, inside your project folder, like this:

ELEVENLABS_API_KEY=sk_XXXXXXXXXXXX

Never share this key, and never add it to a Git repository (add .env to your .gitignore)

Creating the basics of the script

Now that we have our API key in the .env file of our project, we'll be able to install the dependencies.

Run the command npm install --save dotenv elevenlabs in your terminal.

Next, you'll need to create an index.js file and paste the following code into it:

const { ElevenLabsClient, play } = require("elevenlabs");
const fs = require("fs");
const dotenv = require("dotenv");
dotenv.config();

const client = new ElevenLabsClient({ apiKey: process.env.ELEVENLABS_API_KEY });
const voiceId = "a5n9pJUnAhX4fn7lx3uo";

As you've probably guessed, this script simply retrieves the ElevenLabs API key and initializes the SDK with it!

The rest of the tutorial will all take place in this index.js file.

The voice ID corresponds to this voice, but you can choose your own directly at: https://elevenlabs.io/app/voice-library

Using the SDK

For our tutorial, we're going to use the SDK's generate method:

// Fonction principale (pour utiliser async/await)
async function main() {
	
		// On génère le flux audio
    const audio = await client.generate({
        voice: voiceId,
        text: "Vous ne passerez pas !",
        model_id: "eleven_multilingual_v2",
        output_format: "mp3_44100_128"
    });

    // On créé un flux d'écriture vers un fichier
    const writeStream = fs.createWriteStream("out.mp3", { flush: true });
    
    // On redirige chaque paquet du flux audio, vers le flux d'écriture du fichier
    audio.pipe(writeStream);

		// Lorsque le flux d'audio se termine, le flux de fichier se ferme
    writeStream.on('finish', () => {
        console.log(`File written successfully`);
    });
    
    // En cas d'erreur
    writeStream.on('error', (error) => {
        console.error(`An error occurred while writing the file`);
    });
}

// Appel de la fonction principale pour déclencher le script
main();

Result

If everything went well, you should see an out.mp3 file appear in your project folder!

Try playing it to check that it does contain the audio of your text.

Warning: Generation can sometimes have slight bugs depending on the input sentence (especially in French), so you may need to run the generation several times in a row to get a flawless version!

Note

The SDK also offers a play method, as indicated in the official documentation.

It allows you to play the audio in real time directly from the stream, without having to save a file, which is very handy for many use cases.

However, this method requires having the MPV and FFmpeg packages installed on your machine.

Full code

Here's the complete code of the index.js file used in this tutorial:

const { ElevenLabsClient, play } = require("elevenlabs");
const fs = require("fs");
const dotenv = require("dotenv");
dotenv.config();

const client = new ElevenLabsClient({ apiKey: process.env.ELEVENLABS_API_KEY });
const voiceId = "a5n9pJUnAhX4fn7lx3uo";

// Fonction principale (pour utiliser async/await)
async function main() {
	
		// On génère le flux audio
    const audio = await client.generate({
        voice: voiceId,
        text: "Vous ne passerez pas !",
        model_id: "eleven_multilingual_v2",
        output_format: "mp3_44100_128"
    });

    // On créé un flux d'écriture vers un fichier
    const writeStream = fs.createWriteStream("out.mp3", { flush: true });
    
    // On redirige chaque paquet du flux audio, vers le flux d'écriture du fichier
    audio.pipe(writeStream);

		// Lorsque le flux d'audio se termine, le flux de fichier se ferme
    writeStream.on('finish', () => {
        console.log(`File written successfully`);
    });
    
    // En cas d'erreur
    writeStream.on('error', (error) => {
        console.error(`An error occurred while writing the file`);
    });
}

// Appel de la fonction principale pour déclencher le script
main();

And there you go, you now know how to use the ElevenLabs API in NodeJS!


Finished reading this article?
Our newsletter

No spam. Only free content, news, and ever more resources to level up your skills!

Join +1500 developers

Comments (0)

to leave a comment

No comments yet