Next.js Discord

Discord Forum

Downloading from API in NextJS 13.4.13

Ojos Azules posted this in #help-forum
Open in Discord
Ojos AzulesOP
I've been making an app on NextJS 13.4.13, and I feel like I've run into a wall with my implementation somewhere. I have an api that works right now, and it returns a correct response to populate my page. The API basically gets a request with a JSON object, translates it, and returns the text formatted in a few different ways. That is all working. However, I want to write the text information to a file for the user to download, so that they don't have to copy/paste the text any time they need it. I've been searching online, and there are no examples of downloading in the most recent App Router.

I've tried middleware.ts
import { NextResponse } from 'next/server'

export function middleware() {
const response =

response.headers.set('Content-Disposition', 'attachment; filename=translated.txt')
response.headers.set('Content-Type', 'text/plain')

return response

This triggers downloading immediately when I go to the dev link (localhost://3000) and downloads the HTML site.

I've tried importing fs to create a file, but I get no output - I suspect it has to do with the serverless function aspect, but I'm not completely sure.

The closest implementation I have is
export async function GET(req, {params}) {

const DUMMY_URL =

// use fetch to get a response
const response = await fetch(DUMMY_URL);

return new Response(response.body, {
headers: {
"content-disposition": attachment; filename="transcript"

The issue with this is that it downloads from an external database, whereas I want to trigger a download of something that isn't a real file anywhere. I need to figure out how to store the file information, then download from that source.

Apologies for the long response, but I hope someone here can help!
Answered by Ojos Azules
Resolved myself by using downloadjs package (
View full answer

1 Reply

Ojos AzulesOP
Resolved myself by using downloadjs package (