How to Use Express res.sendFile() to Serve Files

An Express route may need to return a stored document instead of text or JSON. The res.sendFile() method transfers a file from the server’s filesystem in the HTTP response.

I’ll show how to build the route and choose a path that points to the file.

TL;DR

Use res.sendFile() in an Express route to transfer a file, giving it an absolute path or a relative filename with an absolute root option.

  • Use path.join(__dirname, ‘public’, ‘index.html’) for a fixed file.
  • Use root to contain a request-selected filename within a directory.
  • Pass errors to Express with next(err) when using a callback.

What does Express res.sendFile() do?

The response sends the file’s bytes, while headers tell the client how to interpret and store them. Check the status and response headers in the browser’s network panel when client behavior is unexpected.

The method accepts a path, an optional options object and an optional callback. Its path must be absolute unless an absolute root option is set.

How to serve a file with res.sendFile()

Build a small Express route around a known HTML file, then check the path and response behavior before adding user-selected filenames.

Step 1: Create the file and project

Create public/index.html and put a simple HTML page in it. Initialize a Node.js project and install Express with the package manager used for the project. Keep application source separate from public files so the route has a clear asset directory.

npm init -y
npm install express

npm install express records Express as a project dependency in package.json. Keep that manifest with the source so the deployment process can install the same direct dependency when building the application.

Step 2: Resolve the file path from the server file

Use Node’s path module to build the location from the directory containing the server file. This avoids depending on the folder from which node was launched.

This example uses CommonJS syntax with require imports, while ES modules use import declarations. Node does not provide __dirname in ES modules. For local file modules, current Node releases provide import.meta.dirname, and earlier runtimes can derive it from import.meta.url with fileURLToPath and path.dirname.

const express = require('express');
const path = require('node:path');

const app = express();

app.get('/', (req, res, next) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'), (err) => {
    if (err) next(err);
  });
});

app.listen(3000);

The callback can pass a transfer error to the app’s error-handling middleware with next(err).

The demo uses a local HTML fixture so you can compare a known file with the returned body. I ran node sendfile_demo.js with a local Express app and a sample HTML file to check the response fields:

const express = require('express');
const path = require('node:path');
const app = express();
app.get('/', (req, res, next) => {
  const file = 'index.html';
  console.log(`File exists: ${require('node:fs').existsSync(path.join(__dirname, 'public', file))}`);
  res.sendFile(file, { root: path.join(__dirname, 'public') }, (err) => {
    if (err) next(err);
  });
});
const server = app.listen(0, async () => {
  const address = server.address();
  try {
    const response = await fetch(`http://127.0.0.1:${address.port}/`);
    const html = await response.text();
    console.log(`HTTP ${response.status}`);
    console.log(`Content-Type: ${response.headers.get('content-type')}`);
    console.log(html.trim());
    server.close();
  } catch (error) {
    console.error(error.message);
    server.close(() => process.exitCode = 1);
  }
});

The exact output was:

File exists: true
HTTP 200
Content-Type: text/html; charset=utf-8
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>File response</title></head><body><p>Served by Express</p></body></html>
Express sendFile response showing HTTP 200 and HTML

The status confirms that the route found and transferred the file. The HTML body is the file’s markup, so a page that needs server-side variables should use a template renderer. The response header shows that Express selected an HTML media type from the file extension.

The browser requests referenced assets separately from index.html. Inspect failed asset requests when the page loads without its expected appearance.

Step 3: Use root for a relative filename

The root option bounds lookup to its directory while allowing a relative route filename.

const path = require('node:path');

app.get('/documents/:name', (req, res, next) => {
  res.sendFile(req.params.name, {
    root: path.join(__dirname, 'public', 'documents'),
    dotfiles: 'deny'
  }, (err) => {
    if (err) next(err);
  });
});

Use dotfiles: ‘deny’ when this route should reject hidden filenames. Express also supports allow and ignore, so choose the option that matches the directory’s purpose.

Step 4: Decide what the route is allowed to send

Before serving private records, check the signed-in user’s permission for the selected record. Authentication identifies the requester, while authorization decides whether that person may retrieve this record. The in-memory map keeps the lookup example small and visible.

const documents = new Map([
  ['guide', 'getting-started.pdf'],
  ['terms', 'terms.pdf']
]);

app.get('/files/:id', (req, res, next) => {
  const filename = documents.get(req.params.id);
  if (!filename) return res.sendStatus(404);
  res.sendFile(filename, {
    root: path.join(__dirname, 'private-documents'),
    dotfiles: 'deny'
  }, next);
});

This example returns 404 for an unknown identifier and sends the mapped file.

Step 5: Choose sendFile options for the response

The options object controls lookup and response metadata. Your installed Express version determines the option contract, so check the matching API reference before relying on less common settings.

OptionPurposeDecision to make
rootBase directory for a relative pathSet a fixed absolute directory when the filename comes from a route
dotfilesControls handling of dotfilesChoose deny or ignore when hidden files must not be served
headersAdds response headersSet only metadata appropriate for this file
maxAgeSets a cache lifetimeUse a suitable lifetime for files that may change
acceptRangesEnables byte-range requestsKeep or disable based on whether clients need partial transfers
lastModifiedSets the Last-Modified response header from the fileUse the default when clients can revalidate by modification time
cacheControlControls whether sendFile sets Cache-ControlDisable only when the app sets a complete policy elsewhere
immutableAdds the immutable directive to Cache-ControlUse with maxAge for versioned files whose URL changes with content

res.sendFile() errors and choices

Use the failure symptom to identify which route input or response method needs attention. The table pairs common errors with a first check.

SituationWhat to checkResponse approach
Path must be absoluteRelative path passed without rootResolve it with path.join or set root
File not foundDirectory, filename, case and deployment contentsPass callback error to next(err)
sendFile method missingConfirm res is the Express response parameter and Express middleware created the routeUse res.sendFile with camel-case F
Need to send JSON or textResponse is data rather than a disk fileUse res.json or res.send
Need a browser downloadContent-Disposition should be attachmentUse res.download

The Node.js process needs read access to the file and search permission on its parent directories.

If an error arrives after the response headers are sent, do not try to replace the partial response with a second body. Check res.headersSent before writing any error response.

Production error middleware should return a controlled response and keep filesystem details out of messages sent to clients. Log enough server-side context to diagnose the failed route without exposing absolute paths or stack traces in a public response.

For a directory of public assets, Express static-file middleware is generally a better fit than writing one route per file. For route organization, see the Express Router tutorial.

Set status and response headers

Headers should match the file and intended client behavior. Check the extension before overriding Content-Type because a wrong media type can lead clients to interpret bytes incorrectly.

app.get('/report', (req, res, next) => {
  res.sendFile('report.csv', {
    root: path.join(__dirname, 'reports'),
    headers: { 'Content-Type': 'text/csv; charset=utf-8' }
  }, next);
});

Set cache and range behavior

Byte ranges let clients request part of a media file. Check that your supported clients need partial transfers before enabling them.

A file’s maxAge should match the way the asset is updated. A file replaced at a stable URL may remain cached after the server changes it, while a URL containing a content version naturally points to a different resource after an update. The example sets a one-hour maxAge, so use that value only when it fits the file’s update cycle.

res.sendFile('video.mp4', {
  root: path.join(__dirname, 'public', 'media'),
  maxAge: '1h',
  acceptRanges: true
}, next);

Choose between files and rendered responses

Use a template for HTML that changes with route data, and res.json for structured API data.

app.get('/profile', (req, res) => {
  res.render('profile', { name: req.user.name });
});

app.get('/api/profile', (req, res) => {
  res.json({ name: req.user.name });
});

Conclusion

Use res.sendFile() for a stored file response.

For the full option list and callback contract, read the Express 5 response API. The Express 4 response API documents the legacy version as well.

FAQ

These answers cover common path, response and method-name questions about serving a file from an Express route.

What is res.sendFile() used for?

It transfers a file from the server filesystem as the response to an Express request.

Why does Express say the path must be absolute?

The sendFile path must be absolute unless you provide an absolute root option for a relative filename.

What is the difference between res.send() and res.sendFile()?

res.send() sends a response body such as text, an object or a Buffer. res.sendFile() transfers a file from the server filesystem.

Should I use res.sendfile() or res.sendFile()?

Use the camel-case res.sendFile() spelling. Express documents the lower-case res.sendfile() as legacy and deprecated.

Pankaj Kumar
Pankaj Kumar

Pankaj Kumar is the founder and CEO of CodeForGeek, with more than 14 years in IT. He is an open-source enthusiast who enjoys sharing what he learns through CodeForGeek and YouTube, with a focus on Python, data analytics, machine learning, Angular, Node.js, and Kafka.

Articles: 337