DEV Community

Cover image for How To Stream Mp3 With NodeJS To HTML Audio Tag

Posted on • Originally published at

How To Stream Mp3 With NodeJS To HTML Audio Tag

In this article we are going to make a simple nodejs API endpoint that streams an mp3 file hosted on publicly anywhere example:

  • Amazon S3
  • Cloudinary
  • Megaphone
  • Public mp3 file


  • Nodejs Basics
  • Used Axios request library
  • Express basics
  • Hosted audio

Note: This is not a scalable way to stream audio, there are better ways by handling the streaming using HLS and FFmpeg on a server somewhere. You can use this script to stream and binge your favorite podcast.

Let's get started

First, we need to setup our project:

yarn init
Enter fullscreen mode Exit fullscreen mode

Fill out the prompts or just work with the default values by adding -y argument at the end.

Next, we need to install relevant npm packages

yarn add express axios
Enter fullscreen mode Exit fullscreen mode

Let's create our endpoint

// We will use this to make HTTP request to the mp3 link
const axios = require("axios");
// adapters are axios modules that handle dispatching a request and settling a returned Promise once a response is received.
const httpAdapter = require("axios/lib/adapters/http");
// express is lightweight web framework
const express = require("express");

// Initialize express and assign to variable app
const app = express();

const INPUT =

app.get("/audio", (req, res) => {
    .get(INPUT, { responseType: "stream", adapter: httpAdapter, 'Content-Range': 'bytes 16561-8065611'  })
    .then((Response) => {
      const stream =;

      res.set("content-type", "audio/mp3");
      res.set("accept-ranges", "bytes");
      res.set("content-length", Response.headers["content-length"]);

      stream.on("data", (chunk) => {

      stream.on("error", (err) => {

      stream.on("end", () => {
    .catch((Err) => {

app.listen(4000, () => {
  console.log("Server is running");
Enter fullscreen mode Exit fullscreen mode

Continue here

Top comments (2)

marcellothearcane profile image

Rather than a "continue here" link, it would be better to have all the information here too :)

wchr profile image

My blog has pretty dead for a while, but I will soon move them here