Express res.download() Method

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 3 Code Examples

What you’ll learn

  • How to send downloadable files with res.download().
  • How to set custom download filenames.
  • How to handle download errors with callbacks.
  • How to avoid insecure file path patterns.

Syntax

javascript
res.download(path [, filename] [, options] [, fn])
1

Download a static file

javascript
var path = require('path');

app.get('/download-manual', function (req, res) {
  var filePath = path.join(__dirname, 'files', 'manual.pdf');
  res.download(filePath);
});
2

Set custom name for downloaded file

javascript
app.get('/download-report', function (req, res) {
  res.download('reports/monthly.csv', 'sales-report.csv');
});
3

Handle errors using callback

javascript
app.get('/download-safe', function (req, res) {
  res.download('files/guide.pdf', function (err) {
    if (err) {
      if (!res.headersSent) res.status(404).send('File not found');
      return;
    }
    console.log('Download completed');
  });
});

⚠️ Common pitfalls

  • Never pass unvalidated user paths directly to res.download().
  • Check res.headersSent before writing error responses in callbacks.
  • Use absolute/safe resolved paths to avoid accidental directory traversal issues.

❓ FAQ

It transfers a file and sets response headers so browsers download it as an attachment.
res.sendFile() displays/sends files directly, while res.download() is optimized for download behavior.
Yes, pass a second argument filename to set a custom name for the downloaded file.
Yes, callbacks are useful for handling file-not-found or stream errors.
Yes, use safe absolute paths and options like root to avoid unsafe path traversal patterns.
Did you know?

res.download() combines file sending with download headers and supports an optional callback for transfer errors.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

4 people found this page helpful