devnotes.

res.attachment() Function

res.attachment() sets the Content-Disposition header to attachment, prompting the browser to download the response rather than display it.

Syntax

res.attachment([filename])

Example

const express = require("express");
const app = express();
const PORT = 4800;

app.get("/export", (req, res) => {
    res.attachment("sales-report.csv");
    console.log(res.get("Content-Disposition"));
    res.send("date,total\n2026-08-01,4500");
});

app.listen(PORT, () => console.log(`Listening on ${PORT}`));

The browser downloads the response as sales-report.csv instead of rendering it inline.

Use cases

  • Forcing a download for generated reports or exports.
  • Naming a downloaded file dynamically.
  • Serving CSV, PDF, or other document types as attachments.
res.attachment() Function | DevNotes