Express res.sendFile() Method

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

What you’ll learn

  • How to serve files with res.sendFile().
  • How to use safe path handling and root constraints.
  • How to send file responses with options and custom headers.
  • How to handle missing file errors cleanly.

Syntax

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

Send a static file with absolute path

javascript
var path = require('path');

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

Use root option for controlled file access

javascript
app.get('/images/:name', function (req, res) {
  res.sendFile(req.params.name, {
    root: __dirname + '/public/images',
    maxAge: '1h'
  });
});
3

Handle file send errors with callback

javascript
app.get('/terms', function (req, res) {
  res.sendFile(__dirname + '/files/terms.txt', function (err) {
    if (err && !res.headersSent) return res.status(404).send('File not found');
  });
});

⚠️ Common pitfalls

  • Do not pass unvalidated user-controlled paths directly.
  • Prefer absolute paths or root option to avoid traversal issues.
  • Check res.headersSent before sending fallback errors in callbacks.

❓ FAQ

It transfers a file from the server filesystem to the client as the HTTP response body.
Yes, unless you use the root option. Using resolved absolute paths is safer and clearer.
res.sendFile() serves a file directly, while res.download() adds attachment behavior for download prompts.
Yes, provide a callback and handle missing files or permission issues there.
Never pass unvalidated user input directly; use trusted path joins and root constraints.
Did you know?

res.sendFile() sends files from disk and supports options like root, maxAge, and headers.

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