How to Get and Process a Stream Response with Axios
Jasser Mark Arioste
Hello, hustler! In this tutorial, you'll learn how to get and process a stream response from axios. We'll use NextJS and Express to demonstrate how to pass the stream from axios to the browser.
Getting a stream response from axios #
If you're familiar with axios, the default response you get is usually in application/json
format. However, If you're trying to retrieve a file or an image from a URL, you can't use application/json
as the response type. It turns out that axios has this covered by using the { responseType: "stream" }
option.
import { Readable } from "stream"; import fs from "fs" // external file URL const DUMMY_URL = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"; // use axios to get a Readable stream response const { data } = await axios.get<Readable>(DUMMY_URL, { responseType: "stream", }); // now, you can process or transform the data as a Readable type. const writeStream = createWriteStream("dummy.pdf"); data.pipe(writeStream); // save file to local file system
123456789101112
In line 5, we use the { responseType: "stream" }
option and we also assign a generic type parameter of Readable as the data
.
In line 12, we use the .pipe()
method to dump all the data into a WritableStream
which writes the data into a file called dummy.pdf.
Streaming Responses to The Browser #
Suppose, you have an API to download certain files from specific URLs and return them as a streamed response. You can use { responseType:'stream' }
for this purpose as well.
Below are three different examples of how to get the stream response from axios and return it as a stream.
Express Application #
// router.ts import axios, { AxiosError } from "axios"; import { Response, Request, Router } from "express"; const router = Router(); router.get("/api/download/", (req: Request, res: Response)=> { // external file URL const DUMMY_URL = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"; // use axios to get a Readable stream response const { data } = await axios.get<Readable>(DUMMY_URL, { responseType: "stream", }); res.setHeader("content-disposition", `attachment; filename="dummy.pdf`); // pipe the data to the res object data.pipe(res); })
12345678910111213141516171819
NextJS /pages/api
folder
#
// pages/api/download/[filename].ts import axios from "axios"; import { NextApiRequest, NextApiResponse } from "next"; import { Readable } from "stream"; async function handler(req: NextApiRequest, res: NextApiResponse) { // get the filename for the file that the user is trying to download const filename = req.query.filename; // external file URL const DUMMY_URL = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"; // use axios to get a Readable stream response const { data } = await axios.get<Readable>(DUMMY_URL, { responseType: "stream", }); res.setHeader("content-disposition", `attachment; filename="${filename}"`); // pipe the data to the res object data.pipe(res); } export default handler;
123456789101112131415161718192021222324
NextJS /app
router
#
// app/api/download/[filename]/route.ts import axios from "axios"; type GetParams = { params: { filename: string; }; }; // export an async GET function. This is a convention in NextJS export async function GET(req: Request, { params }: GetParams) { // filename for the file that the user is trying to download const filename = params.filename; // external file URL const DUMMY_URL = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"; // use fetch to get a response const response = await axios.get<ReadableStream>(DUMMY_URL, { responseType: "stream", }); // return a new response but use 'content-disposition' to suggest saving the file to the user's computer return new Response(response.data, { headers: { "content-disposition": `attachment; filename="${filename}"`, }, }); }
123456789101112131415161718192021222324252627282930
Conclusion #
You learned how to get a stream response from axios and how to return it in different types of applications such as Express and NextJS.
If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter or follow me on GitHub.
Credits: Image by Alfred Grupstra from Pixabay