In Express.js, res.attachment() sets the response Content-Disposition header to attachment. Browsers then treat the response as a download instead of showing it inline.
With a filename, Express also sets the filename= parameter and picks a Content-Type from the extension via res.type(). It only sets headers — you still send the body with res.send(), res.sendFile(), or similar.
Syntax
Call res.attachment in your Express.js app. Start with this line.
GET /report
→ Content-Disposition: attachment; filename="report.txt"
→ Content-Type: text/plain
→ Body: Daily report content
(Browser offers to save as report.txt)
How It Works
Mark as attachment.res.attachment('report.txt') sets Content-Disposition with that filename.
Type from extension..txt maps to text/plain through res.type().
Then send the body.res.send delivers the string; headers were already set.
Client saves the name. The download dialog typically suggests report.txt.
Example 2 — JSON Export with a Custom Name
Build JSON in memory and offer it as a named download.
GET /guide
→ Content-Disposition: attachment; filename="user-guide.pdf"
→ Content-Type: application/pdf
→ Body: (PDF bytes from disk)
Without res.attachment(), sendFile may open inline in the browser.
How It Works
Set download headers first.res.attachment('user-guide.pdf') marks the response as a PDF download.
Stream the file next.res.sendFile reads the path and writes the body.
Name can differ from disk. The attachment name is what the user sees; the path is where bytes come from.
Shorter path:res.download(filePath, 'user-guide.pdf') does attachment + transfer in one call.
Compatibility
Runtime Support
res.attachment() is an Express.js response method. It runs on a Node.js server (Express 5 needs Node.js 18+). Browsers only receive the headers; they do not execute this method.
✓ Server · Express 4 & 5
res.attachment()
Works wherever Express runs: Node.js is the primary target. Bun and Deno can run many Express apps with compatibility layers. Not available in the browser.
ServerNode.js runtime API
Node.js18+ for Express 5 · Express 4 supported
Supported
BunExpress-compatible server apps
Supported
DenoVia npm compatibility / adapters
Supported
res.attachment()Express on Node.js
Bottom line: Study and run these examples with Node.js and the express package. Copy a snippet into a local file and start the server with node.
Frequently Asked Questions
It sets the Content-Disposition response header to attachment so browsers treat the response as a download. It does not read or send a file by itself.
Express sets Content-Disposition’s filename parameter from the base name, and sets Content-Type from the extension via res.type().
res.attachment() only sets headers. res.download() sets attachment headers and transfers a file from disk in one call.
Yes. Call res.attachment() first, then send the body with res.send(), res.sendFile(), or similar.
No. It is a stable Express response method in Express 4 and Express 5.