Skip to content
jshacks.dev
Node.js

How to Serve Static Files in Node.js

Serve static files with node:http by mapping URLs to a root folder, blocking path traversal, setting content types and cache headers, and streaming the bytes.

7 min read
Summarize in AI
Flat illustration of folders syncing with a cloud bucket, with the Node.js, DigitalOcean, Linux and Cloudflare logos.

Serving a folder of files over HTTP sounds like a ten line job, and it is, until the first request for /../../etc/passwd. A static file server has to map a URL to a path, refuse paths that escape the root, choose a content type, handle missing files and directories, stream the bytes without loading them into memory, and say how long a browser may cache them. This post builds that server with node:http, node:fs and node:path on Node.js 26, shows the security check that matters most, and explains the headers that make repeat visits cheap. For production traffic you will usually put a web server or a CDN in front, and the last section says when to do that. The module references are the http and path documentation.

Mapping a URL to a file

Start with the safe version of the path logic, because everything else depends on it. The server has a root directory. A request path is resolved against it, and the result is accepted only if it is still inside the root.

safe-path.jsJavaScript
import { resolve, sep } from "node:path";

const ROOT = resolve("public");

export function toFilePath(urlPath) {
  const decoded = decodeURIComponent(urlPath);
  if (decoded.includes("\0")) return null;
  const full = resolve(ROOT, "." + decoded);
  return full === ROOT || full.startsWith(ROOT + sep) ? full : null;
}

console.log(toFilePath("/css/site.css") !== null);
console.log(toFilePath("/../secret.txt"));
console.log(toFilePath("/%2e%2e/secret.txt"));

If the working directory is /srv/app, so the root is /srv/app/public, the output is:

Text
true
null
null

The check has three parts. decodeURIComponent runs first, so an encoded %2e%2e becomes .. before the test and is caught. A null byte is refused because some APIs treat it as the end of a string. And resolve collapses every .., after which the test startsWith(ROOT + sep) confirms the result is inside the root. The + sep matters: without it, a sibling folder named public-secrets would pass the prefix test for public. A malformed escape such as %E0%A4%A makes decodeURIComponent throw, so the server wraps the call in a try and answers 400.

A complete server

Now the full handler. It resolves the path, checks the file with stat, picks a content type from the extension and streams the file.

static-server.jsJavaScript
import { createServer } from "node:http";
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { extname, join, resolve, sep } from "node:path";
import { pipeline } from "node:stream/promises";

const ROOT = resolve("public");

const TYPES = {
  ".html": "text/html; charset=utf-8",
  ".css": "text/css; charset=utf-8",
  ".js": "text/javascript; charset=utf-8",
  ".json": "application/json; charset=utf-8",
  ".svg": "image/svg+xml",
  ".png": "image/png",
  ".jpg": "image/jpeg",
  ".txt": "text/plain; charset=utf-8",
};

function resolveSafe(urlPath) {
  let decoded;
  try {
    decoded = decodeURIComponent(urlPath);
  } catch {
    return null;
  }
  if (decoded.includes("\0")) return null;
  const full = resolve(ROOT, "." + decoded);
  return full === ROOT || full.startsWith(ROOT + sep) ? full : null;
}

const server = createServer(async (req, res) => {
  if (req.method !== "GET" && req.method !== "HEAD") {
    res.writeHead(405, { allow: "GET, HEAD" }).end();
    return;
  }

  const { pathname } = new URL(req.url, "http://localhost");
  let file = resolveSafe(pathname);
  if (!file) {
    res.writeHead(400).end("bad request");
    return;
  }

  try {
    let info = await stat(file);
    if (info.isDirectory()) {
      file = join(file, "index.html");
      info = await stat(file);
    }
    res.writeHead(200, {
      "content-type": TYPES[extname(file).toLowerCase()] ?? "application/octet-stream",
      "content-length": info.size,
      "last-modified": info.mtime.toUTCString(),
      "cache-control": "public, max-age=3600",
    });
    if (req.method === "HEAD") return res.end();
    await pipeline(createReadStream(file), res);
  } catch (err) {
    if (err.code === "ENOENT" || err.code === "ENOTDIR") {
      res.writeHead(404, { "content-type": "text/plain" }).end("not found");
    } else if (!res.headersSent) {
      res.writeHead(500).end("server error");
    }
  }
});

server.listen(3000, () => console.log("serving ./public on :3000"));
Text
serving ./public on :3000

With public/index.html and public/css/site.css on disk, the requests behave like this.

Shell
curl -s -o /dev/null -w "%{http_code} %{content_type}\n" localhost:3000/
curl -s -o /dev/null -w "%{http_code} %{content_type}\n" localhost:3000/css/site.css
curl -s -o /dev/null -w "%{http_code}\n" localhost:3000/missing.png
curl -s -o /dev/null -w "%{http_code}\n" --path-as-is localhost:3000/../server.js
Text
200 text/html; charset=utf-8
200 text/css; charset=utf-8
404
400

Walk through the notable lines. A request for a directory falls through to index.html, so / works. stat before writeHead lets the server fail with a clean 404 before any header is sent, and it supplies Content-Length and Last-Modified for free. pipeline(createReadStream(file), res) streams the file and destroys the file stream if the client disconnects, which prevents leaked descriptors. HEAD requests get the same headers and no body.

Content types

The browser decides how to treat a response from its Content-Type, so a wrong one breaks pages: a stylesheet served as text/plain is ignored in standards mode, and a script with the wrong type may be blocked. The map above covers common cases. Add .woff2 as font/woff2, .webp as image/webp, .wasm as application/wasm and .map as application/json as you need them. The fallback application/octet-stream tells the browser to download unknown content instead of guessing, which is the safe default. Adding X-Content-Type-Options: nosniff stops browsers from guessing a type for you.

nosniff.jsJavaScript
res.setHeader("x-content-type-options", "nosniff");

Caching

Cache-Control: public, max-age=3600 lets a browser reuse a file for an hour without asking. That is good for fingerprinted assets, whose names change when the content does, and risky for index.html, which should be revalidated. A common split is long-lived caching for hashed files and a short or revalidating policy for pages.

cache-policy.jsJavaScript
import { basename } from "node:path";

export function cacheControl(file) {
  const hashed = /\.[0-9a-f]{8,}\./.test(basename(file));
  return hashed ? "public, max-age=31536000, immutable" : "no-cache";
}

console.log(cacheControl("/public/app.3f9a1c2b.js"));
console.log(cacheControl("/public/index.html"));
Text
public, max-age=31536000, immutable
no-cache

no-cache does not mean "do not store". It means the browser must revalidate before reuse, and revalidation is cheap when the server supports conditional requests. A simple form uses Last-Modified.

conditional.jsJavaScript
const since = req.headers["if-modified-since"];
if (since && new Date(since) >= new Date(info.mtime.toUTCString())) {
  res.writeHead(304).end();
  return;
}

When the browser sends If-Modified-Since with the date it received earlier and the file is unchanged, the server answers 304 Not Modified with no body. Compare the dates after truncating to seconds, because HTTP dates have no milliseconds, which is why the sample converts through toUTCString().

Range requests

Video and audio players ask for a slice of a file with a Range header. The server should answer 206 and send only those bytes, which createReadStream supports with start and end.

range.jsJavaScript
const range = /^bytes=(\d+)-(\d*)$/.exec(req.headers.range ?? "");
if (range) {
  const start = Number(range[1]);
  const end = range[2] ? Number(range[2]) : info.size - 1;
  res.writeHead(206, {
    "content-range": `bytes ${start}-${end}/${info.size}`,
    "content-length": end - start + 1,
    "accept-ranges": "bytes",
  });
  await pipeline(createReadStream(file, { start, end }), res);
  return;
}

For a 1,000 byte file and Range: bytes=0-99, the response header is:

Text
Content-Range: bytes 0-99/1000

A complete implementation also rejects a start beyond the file size with 416.

When not to do this yourself

A hand-written file server is good for a development tool, a small internal site or a learning exercise. For public traffic, a reverse proxy such as nginx, an object store with a CDN or a platform's static hosting does more, with better compression, caching, range handling and connection management, and keeps your Node.js process free for application work. If you must serve files from Node.js, the checks in this post are the minimum. Treat the path check as the one part you never skip.

Compression and single page apps

Text files compress well, and serving them compressed saves bandwidth. Node.js includes zlib, so a server can check the Accept-Encoding request header and, when the client accepts gzip or br, pipe the file through a compression stream and set Content-Encoding. Two things change when you do that. The Content-Length of the original no longer applies, so you must drop it and let the response use chunked transfer, and you must add Vary: Accept-Encoding so caches keep separate copies. Already compressed formats such as images, fonts in woff2 and archives gain nothing and should be skipped. Many teams compress ahead of time at build, store app.js.br beside app.js and have the server pick the matching file, which removes the CPU cost from the request path.

A single page application adds one more rule. Routes such as /settings/profile exist only in the browser, so a request for them finds no file. The usual fix is a fallback: if the path has no file extension and nothing matches, send index.html with a 200 and let the client router take over. Requests for a missing asset, such as /missing.js, should still return 404, which is why the check looks at the extension and not just at the miss.

Testing the server

A static server is easy to test because its behaviour is a mapping from request to response. Create a temporary directory with a few files, start the server on port 0 so the system picks a free port, read the assigned port from server.address(), and request each case with fetch. The cases worth covering are a normal file, a directory, a missing file, an encoded traversal attempt and a request with a wrong method. A test for the traversal case is the most valuable, because it guards the one bug that has security consequences.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.