Express res.attachment() Method
What you’ll learn
- How
res.attachment()controls browser download behavior. - How filename affects download name and content type inference.
- When to use
res.attachment()versusres.download(). - How to avoid common header ordering mistakes.
Syntax
javascript
res.attachment()
res.attachment(filename)1
Send generated text as a download
javascript
app.get('/report', function (req, res) {
res.attachment('report.txt');
res.send('Daily report content');
});2
Download JSON export with custom name
javascript
app.get('/export', function (req, res) {
var payload = JSON.stringify({ ok: true, generatedAt: Date.now() }, null, 2);
res.attachment('export.json');
res.send(payload);
});3
Set attachment header before sending a file
javascript
var path = require('path');
app.get('/guide', function (req, res) {
res.attachment('user-guide.pdf');
res.sendFile(path.join(__dirname, 'files', 'user-guide.pdf'));
});⚠️ Common pitfalls
- Set attachment headers before sending body/file; headers cannot change after response starts.
res.attachment()does not read files by itself, it only sets headers.- Use safe, user-friendly filenames and avoid unsanitized user input in download names.
❓ FAQ
It sets Content-Disposition to attachment so browsers treat the response as a downloadable file.
Yes. Passing a filename sets it in the Content-Disposition header and helps clients name the download.
No. res.attachment() sets headers only, while res.download() also sends a file.
When a filename is provided, Express can infer and set Content-Type based on the file extension.
Yes. Set attachment headers first, then send the response body with res.send() or res.end().
Did you know?
res.attachment(filename) sets a download-friendly Content-Disposition header and can infer a matching Content-Type.
4 people found this page helpful
