Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 43 ยท Request and Response

Static Files, Downloads and Streaming

Serve static files with express.static, send single files with res.sendFile and res.download, stream big responses, and see how range requests and dotfiles work.

Not every response is generated by code. Stylesheets, images, scripts and PDFs already exist as files, and Express can serve them with a single line. This lesson covers express.static for whole folders, res.sendFile and res.download for individual files, and streaming for responses that are too big to build in memory.

The real Express code here is read-only, since the browser has no disk or npm. The runnable examples serve files from an in-memory object using the mini Express stand-in, and they copy the real behavior for content types, dotfiles, downloads and range requests.

Serving a folder with express.static

JavaScript
import express from 'express';
import path from 'node:path';

const app = express();
const publicDir = path.join(import.meta.dirname, 'public');

app.use(express.static(publicDir));

A request for /css/site.css now returns public/css/site.css, and / returns public/index.html if it exists. If no file matches, the request falls through to the next layer, so your own routes and 404 handler still work. Mount it under a prefix with app.use('/assets', express.static(publicDir)).

Put express.static before routes that could shadow it, and after middleware that must see every request, such as a logger.

The options you will use

JavaScript
app.use(express.static(publicDir, {
  maxAge: '1d',          // Cache-Control: public, max-age=86400
  immutable: true,       // add "immutable" (only for fingerprinted file names)
  index: 'index.html',   // or false to disable directory indexes
  extensions: ['html'],  // /about also finds about.html
  dotfiles: 'ignore',    // 'allow' | 'deny' | 'ignore'
  etag: true,
  fallthrough: true,     // false: send the 404 error right away
  setHeaders(res, filePath) {
    if (filePath.endsWith('.html')) res.set('Cache-Control', 'no-cache');
  },
}));

Use a long maxAge with immutable only for files whose names change when their content changes, such as app.3f9c1a.js. HTML pages should revalidate, as the setHeaders hook above shows.

What express.static does for you

Find the file Maps the URL onto your folder.
Set headers Content-Type, ETag, Cache-Control.
Support ranges Partial downloads and video seeking.
Stay inside Blocks ../ path tricks.

All of it comes from the file-sending library Express uses.

1 / 2

Dotfiles

Files and folders whose names begin with a dot (.env, .git, .htaccess) often hold secrets. The file-sending code in Express treats dotfiles as not found by default (dotfiles: 'ignore'), so a stray .env in your public folder is not served. Do not rely on that alone: keep secrets out of the public folder. When you really need a dot-folder, such as /.well-known/ for domain verification, mount it separately:

JavaScript
app.use('/.well-known', express.static(path.join(publicDir, '.well-known'), {
  dotfiles: 'allow',
}));

A runnable static server

The stand-in below has the same ideas in about twenty lines: a lookup in a folder of files, a content type from the extension, a refusal of dotfiles and .., and a Cache-Control header. Real Express reads from disk and does much more, but the decisions are the same.

Node.js A tiny express.static

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at what happens to /.env and /missing.txt: the static layer calls next(), so they fall through to the stand-in's own 404. And /api/ping is not a file, so it also falls through and reaches the route. That is the real fall-through behavior.

One file: sendFile and download

Use res.sendFile when a route decides which file to send, for example a page behind a login:

JavaScript
app.get('/report', (req, res) => {
  res.sendFile('report.html', { root: path.join(import.meta.dirname, 'private') });
});

The path must be absolute, or relative with a root option. Never pass a path built from user input without a root, because ../../etc/passwd style input can escape your folder. With root, Express rejects paths that climb out of it. Add a callback or res.sendFile(...) error handling for missing files, which would otherwise produce an error response.

res.download(path, filename) is sendFile plus a Content-Disposition: attachment header, which tells the browser to save the file instead of showing it:

JavaScript
app.get('/invoice/:id', (req, res) => {
  const file = path.join(invoiceDir, `${Number(req.params.id)}.pdf`);
  res.download(file, 'invoice.pdf');
});

Here Number(...) also protects the path: only digits can get through. See Route Parameters for validating parameters.

Range requests

When a browser plays a video or resumes a download, it asks for part of a file with Range: bytes=0-99. A server that supports it answers 206 Partial Content with a Content-Range header. express.static, res.sendFile and res.download all do this for you and advertise it with Accept-Ranges: bytes. The stand-in below shows the mechanics for both a download header and a range.

Node.js Content-Disposition and 206 Partial Content

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The download route only adds a header; the browser does the saving. The range routes return exactly the requested slice with status 206, and an out-of-range start gets 416.

Streaming responses

res is a Node writable stream. For a large file or a long-running export, send it in chunks instead of loading everything into memory. With a real file, the standard pattern is pipeline:

JavaScript
import { createReadStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';

app.get('/export.csv', async (req, res) => {
  res.type('text/csv');
  await pipeline(createReadStream('big.csv'), res);
});

pipeline handles back-pressure (it pauses the file when the client reads slowly) and cleans up if the client disconnects. In Express 5, a rejected promise from the async handler is passed to your error handler, but once the headers are sent the best that can happen is the connection closing. Streams are covered in depth in the Node.js lessons; here we only need res.write and res.end.

Node.js Streaming a response in chunks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Because the length is unknown up front, Node uses Transfer-Encoding: chunked, and the client receives each piece as it is written. The same idea powers CSV exports and Server-Sent Events.

Static files and downloads are a common source of path traversal bugs. Never join user input into a file path unchecked. Use root, whitelist file names or look files up by id in a database.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when express.static finds no matching file?

    By default fallthrough is true, so the request continues to the next layer. Set fallthrough to false to send the error right away.
  2. 2. Which option is best for a fingerprinted file such as app.3f9c1a.js?

    A new content gets a new file name, so the old URL never changes and can be cached for a long time.
  3. 3. What is the difference between res.sendFile and res.download?

    Both send the file; download also asks the browser to save it, optionally under a different file name.
  4. 4. Which status does a successful range request get?

    206 Partial Content comes with a Content-Range header that tells the client which bytes it received.
  5. 5. Why use pipeline(createReadStream(file), res) for a big file?

    Streaming keeps memory use small, and pipeline pauses the source when the client is slow.

Summary

  • express.static(dir) serves a folder, sets cache headers, supports ranges and falls through when nothing matches.
  • Use maxAge and immutable only for fingerprinted file names; dotfiles are ignored unless you allow them.
  • res.sendFile needs an absolute path or a root; res.download adds Content-Disposition: attachment.
  • Range requests return 206 with Content-Range; the real helpers handle them automatically.
  • Stream big or slow responses with pipeline or res.write, and never trust user input in file paths.

Next: Template Engines and Server-Side Rendering.