Express.js res.sendFile() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Response

Definition

res.sendFile() transfers a file from disk as the HTTP response body. Express sets Content-Type from the filename extension. Unless you set root, path must be absolute.

Use it when a route should return a specific file (PDF, image, HTML page). For a forced Save dialog, prefer res.download(). For many public assets, static middleware is usually simpler than one route per file.

Syntax

Call res.sendFile in your Express.js app. Start with this line.

Express
res.sendFile(path [, options] [, fn])
res.sendFile('/absolute/path/to/index.html');
res.sendFile('photo.jpg', {
root: path.join(__dirname, 'public'),
maxAge: '1d'
}, (err) => {
if (err) {
}
});
CallWhat it does
res.sendFile(path [, options] [, fn])Primary signature.
res.sendFile('/absolute/path/to/index.html');Related call form.
res.sendFile('photo.jpg', {Related call form.
root: path.join(__dirname, 'public'),Related call form.

Install with npm install express. Create the app with const app = express() before you use this API in an Express.js tutorial project.

Library declarations
Express
const express = require("express");
const app = express();

res.sendFile(path [, options] [, fn])
res.sendFile('/absolute/path/to/index.html');
res.sendFile('photo.jpg', {
root: path.join(__dirname, 'public'),
maxAge: '1d'
}, (err) => {
if (err) {
}
});

Parameters

ParameterDescription
pathRequired. File to transfer. Absolute unless options.root is set.
optionsOptional. Serving options (root, maxAge, headers, and more).
fnRequired. fn(err) on complete or error. On error you must finish the response or call next.
rootRequired. Absolute directory; relative path must resolve inside it.
maxAgeRequired. Cache-Control max-age (ms number or ms string like '1h').
lastModifiedRequired. Set false to omit the Last-Modified header.
headersRequired. Extra response headers object.
dotfilesRequired. "allow" | "deny" | "ignore".
acceptRangesRequired. Enable or disable ranged requests.
cacheControlRequired. Enable or disable the Cache-Control header.
immutableRequired. Add immutable to Cache-Control; also set maxAge.

Return Value

res.sendFile() transfers a file from disk and finishes the response (unless you pass an error callback you must handle). Keep paths absolute or use root.

Express
res.sendFile(path.join(__dirname, 'files/a.txt'));

res.sendFile('a.txt', { root: path.join(__dirname, 'files') }, (err) => {
  if (err && !res.headersSent) res.status(404).end();
});

Express.js Examples

Example 1 — Send a File with an Absolute Path

Resolve a path next to your app, then stream the file. Matches the common absolute-path pattern from the docs.

Express
const express = require('express');
const path = require('path');
const app = express();

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

app.listen(3000);

How It Works

  1. Build an absolute path. path.join(__dirname, …) does not depend on the process working directory.
  2. sendFile streams the file. Express reads from disk and writes the response body.
  3. Content-Type from extension. .pdf maps to a PDF media type.
  4. No attachment by default. Many browsers display the file inline; use res.download() for a Save prompt.

Example 2 — root, dotfiles, and Custom Headers

Serve a named file under a fixed folder — same pattern as the official docs example with options.

Express
const express = require('express');
const path = require('path');
const app = express();

app.get('/file/:name', (req, res, next) => {
  const options = {
    root: path.join(__dirname, 'public'),
    dotfiles: 'deny',
    maxAge: '1h',
    headers: {
      'x-timestamp': Date.now(),
      'x-sent': true
    }
  };

  const fileName = path.basename(req.params.name);

  res.sendFile(fileName, options, (err) => {
    if (err) {
      next(err);
    } else {
      console.log('Sent:', fileName);
    }
  });
});

app.listen(3000);

How It Works

  1. root is absolute. Relative fileName resolves only inside public/.
  2. basename first. Strips directory segments so user input cannot smuggle ../ paths.
  3. dotfiles: ‘deny’. Blocks hidden files like .env under that root.
  4. Callback on finish/error. Official rule: on error, end the cycle or call next(err).

Example 3 — Handle Missing Files in the Callback

When you pass a callback, you own error responses. Check headersSent before writing a new body.

Express
const express = require('express');
const path = require('path');
const app = express();

app.get('/terms', (req, res) => {
  const filePath = path.join(__dirname, 'files', 'terms.txt');

  res.sendFile(filePath, (err) => {
    if (err) {
      if (!res.headersSent) {
        res.status(404).send('File not found');
      }
      return;
    }
    console.log('Terms sent');
  });
});

// Custom 404 page pattern from the docs:
// res.status(404).sendFile(path.join(__dirname, 'public', '404.html'));

app.listen(3000);

How It Works

  1. Absolute path again. No root here — the full path must be absolute.
  2. Callback receives err. Missing files typically surface as an error (for example ENOENT).
  3. You must respond. Docs: if a callback is provided and an error occurs, you finish the cycle yourself.
  4. Check headersSent. Mid-stream failures may have already flushed headers — then avoid a second body.

Runtime Support

res.sendFile() is an Express.js response method. It runs on a Node.js server (Express 5 needs Node.js 18+) and reads the local filesystem. Browsers only receive the file bytes.

✓ Server · Express 4.8+ & 5

res.sendFile()

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.

Server Node.js runtime API
Node.js 18+ for Express 5 · Express 4.8+ for sendFile
Supported
Bun Express-compatible server apps
Supported
Deno Via npm compatibility / adapters
Supported
res.sendFile() Express on Node.js

Bottom line: Study and run these examples with Node.js and the express package. Place sample files on disk before testing.

Frequently Asked Questions

It transfers a file from the server filesystem as the response body and sets Content-Type from the filename extension.
Yes, unless you set the root option. With root, path may be relative (even with ..); Express validates it stays inside that directory.
Both stream a disk file. res.download() also sets Content-Disposition to attachment so browsers usually prompt to save. sendFile often opens inline.
End the request-response cycle yourself or pass control with next(err). If you supply a callback, Express does not auto-finish the error for you.
No. That was the Express 3 name. Use camelCase res.sendFile() in Express 4 and 5.

Next: res.sendStatus()

Set an HTTP status and send its standard reason-phrase body in one call.

res.sendStatus() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

8 people found this page helpful