Search code examples
node.jsexpressnext.jshttpresponsenext.js13

Send a downloadable CSV as response in Next.js


With the following code, I can get a downloadable file when requested.

const csv = converter.json2csv(data);
return new Response(csv, {
  headers: {
    'Content-type': 'text/csv',
    'Content-Disposition': 'attachment',
  }
});

But the downloaded file name is "download.csv". How do I make it download with my desired file name? E.g. "data.csv"


Solution

  • On the link they click to download the file, you can set the HTML5 download attribute. This will allow you to set a default file name.

    <a href="path/to/file" download="renamed.txt">Download</a>
    

    Note that the download attribute only works for same origin urls