How to Implement File Download in NextJS using an API Route ?
Last Updated :
13 May, 2024
In web development, facilitating file downloads is a common requirement, whether it's providing users with documents, images, or other media files. NextJS, with its versatile API routes and server-side capabilities, offers an elegant solution for implementing file downloads. In this article, we'll explore how to leverage NextJS API routes to enable seamless file downloads in your applications.
Why Use API Routes for File Download?
NextJS API routes provide a server-side environment where you can execute custom logic, making them an ideal choice for handling file downloads. By using an API route, you can:
- Access server-side resources securely.
- Dynamically generate files on the fly.
- Implement authentication and authorization logic if necessary.
- Ensure consistent behavior across different client environments.
Steps to Setup a NextJS App
Step 1: Create a NextJS application using the following command.
npx create-next-app@latest <foldername>
Step 2: It will ask you some questions, so choose the following.
√ Would you like to use TypeScript? ... No
√ Would you like to use ESLint? ... Yes
√ Would you like to use Tailwind CSS? ... No
√ Would you like to use `src/` directory? ... Yes
√ Would you like to use App Router? ... Yes
√ Would you like to customize the default import alias (@/*)? ... No
Step 3: After creating your project folder, move to it using the following command.
cd <foldername>
Steps to Implement File Download in NextJS
Let's walk through a step-by-step process to implement file downloads in NextJS using an API route:
Step 1: Create an API Route
First, create an API route in your NextJS project where you'll handle the file download logic. This route will be responsible for fetching the file from the server and sending it as a response to the client. for instance we will use the images in our project itself like NexJs.svg or favicon.ico to be able to download by the client.
JavaScript
// pages/api/download.js
const fs = require("fs");
const path = require("path");
export default function handler(req, res) {
const filePath = path.join(process.cwd(),
"public", "next.svg"); // Path to your file
// Filename for the downloaded file
const fileName = "gfgNextJs.svg";
// Check if the file exists
if (!fs.existsSync(filePath)) {
return res.status(404).send("File not found");
}
// Define a mapping of file extensions to content types
const contentTypeMap = {
svg: "image/svg+xml",
ico: "image/x-icon",
png: "image/png",
jpg: "image/jpeg",
pdf: "application/pdf",
// Add more mappings as needed for other file types
};
// Get the file extension
const fileExtension = fileName.split(".").pop().toLowerCase();
// Determine the content type based on the file extension
const contentType =
contentTypeMap[fileExtension] || "application/octet-stream";
// Set headers to force download
res.setHeader("Content-Disposition",
`attachment; filename="${fileName}"`);
res.setHeader("Content-Type", contentType);
// Stream the file
const fileStream = fs.createReadStream(filePath);
fileStream.pipe(res);
}
Step 2: Call the API Route from Client-Side
Next, you'll need to trigger the file download from your client-side components. You can use a simple HTTP request or a library like Axios to fetch the file from the API route. this results in the download of the required file.
JavaScript
// pages/index.js
import Head from "next/head";
import { useState } from "react";
import axios from "axios";
export default function Home() {
const [downloadStatus, setDownloadStatus] = useState("");
const downloadFavicon = async () => {
try {
const response = await axios.get("/api/download", {
responseType: "blob", // Important for binary data
});
// Extract filename from content-disposition header
const contentDisposition = response.headers["content-disposition"];
const fileNameMatch = contentDisposition.match(/filename="(.+)"/);
const fileName = fileNameMatch ? fileNameMatch[1] : "downloadedFile";
// Create a temporary anchor element to trigger the download
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement("a");
link.href = url;
// Setting filename received in response
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
setDownloadStatus("Downloaded");
} catch (error) {
console.error("Error downloading file:", error);
setDownloadStatus("Error downloading");
}
};
return (
<>
<Head>
<title>Create Next App</title>
<meta name="description"
content="Generated by create next app" />
<meta name="viewport"
content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<div style={{ height: "100vh", backgroundColor: "white" }}>
<button style={{ fontSize: "25px" }}
onClick={downloadFavicon}>
Download gfgNextJS
</button>
<p>{downloadStatus}</p>
</div>
</main>
</>
);
}
Start your application using the following command:
npm run dev
Output:
Download Files in NextJS using an API Route
downloaded svg imageStep 3: Customize the Downloadable files as needed
Adjust the filePath variable to point to the actual location of your file in the public directory. Also, set the appropriate fileName and Content-Type headers.
- For SVG files, use "image/svg+xml" as the content type.
- For ICO (icon) files, use "image/x-icon" as the content type.
- For PDF set Content-Type header to application/pdf
Step 4: Customizing React Home Component
In the React component, customize the user interface to provide a user-friendly way to trigger the PDF download. This may include designing a button or a link with appropriate text and styling. Consider adding informative messages or visual cues to indicate the download status to the user.
Step 5: Testing
Once you've made changes to the component, make sure to test the PDF download. Click the download button to get the PDF file. Check that the file you downloaded is indeed a PDF and has the right content. Also, keep an eye out for any errors or weird things that might happen during the download.
Conclusion
Setting up file downloads in NextJS using an API route is simple. Just follow the steps in this guide, and you'll be able to let users download files from your NextJS app easily. Whether you're serving static files or creating content on the fly, NextJS API routes make it easy to handle file downloads, giving your users a smooth experience.
Similar Reads
How to Download a File Using Node.js?
Downloading files from the internet is a common task in many Node.js applications, whether it's fetching images, videos, documents, or any other type of file. In this article, we'll explore various methods for downloading files using Node.js, ranging from built-in modules to external libraries. Usin
3 min read
How to download File Using JavaScript/jQuery ?
The ability to download files directly from a website is an essential feature for many web applications. Whether you're providing documents, images, or other data, enabling users to download files seamlessly enhances their experience and ensures they can access the content offline. This article prov
2 min read
How to use R to download file from internet ?
In this article, we will be looking at the approach to download any type of file from the internet using R Programming Language. To download any type of file from the Internet download.file() function is used. This function can be used to download a file from the Internet. Syntax: download.file(url,
2 min read
How to implement file uploading and downloading with Express ?
File uploading and downloading are important features of a web app. Here we are going to handle file upload using express-fileupload npm package, and the download is handled using res.download() function of the express. The express-fileupload is passed to the app as the middleware. Approach: First,
3 min read
How to send one or more files to an API using axios in ReactJS?
Assuming that you want to send multiple files from the front-end, i.e., the React app, to the server using Axios. For that, there are two approaches as shown below: Send multiple requests while attaching a single file in each request.Send a single request while attaching multiple files in that reque
3 min read
How to convert a file to zip file and download it using Node.js ?
The Zip files are a common way of storing compressed files and folders. In this article, I'll demonstrate how to convert the file to zip format by using the adm-zip module (NPM PACKAGE). Uses of ADM-ZIP compress the original file and change them to zip format.update/delete the existing files(.zip fo
3 min read
How to Implement PWA in the Next-13 Application?
A progressive web app (PWA) is a website that functions like a mobile app but is built with web technologies like HTML, CSS, JavaScript, and WebAssembly. PWAs are designed to work on any device with a modern web browser, including mobile and desktop devices. They can also operate offline and in the
3 min read
How to Download a File using Express.js ?
Express.js is a routing and middleware framework for handling the different routing of the webpage and it works between the request and response cycle and works on the top of the node.js server. In this article, we will discuss how to download a file using express.js. ApproachTo download a file usin
3 min read
How To Implement MongoDB Authentication In NextJS Using NextAuth.Js?
MongoDB authentication integration in Next.js with NextAuth.js enhances the security of web applications. Integrating authentication in a Next.js application using MongoDB as the database can be efficiently achieved with the NextAuth.js library. NextAuth.js is a complete open-source authentication s
3 min read
How to Get Information About a File using Node.js ?
Node.js is an open-source and cross-platform runtime environment built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. You need to recollect that NodeJS isnât a framework, and itâs not a programming language. In this article, we will discuss how to get informatio
3 min read