Thuta Learning
Node.js
IntermediateWeb DevelopmentBeginner

Serving Static Files

Node.jsLesson 1320 min

What you'll walk away with

  • Explain how express.static(folder) maps a URL path to a file in that folder
  • Point the static folder at an absolute path from __dirname and mount it under a prefix such as /static
  • Order static files and API routes so they work together in one app
  • Know what the maxAge, index and dotfiles options do, and keep secret files out of reach

Explain it simply

Explain it simply

A website serves two kinds of content. One kind is computed fresh for every request, such as a user's order list. The other kind is the same file no matter who asks: the logo, the CSS file, the JavaScript that runs in the browser. The second kind is called static files.

You do not write a route for each static file. Say express.static('public') and Express opens the public folder like a shop window: whenever the browser asks for /css/site.css, it looks for public/css/site.css and sends it back. Everything in the window is visible to everyone, so be careful what you put there.

Problem → Why → Solution

The problem: a route for every file

Before knowing about static middleware, a developer reads each file with readFile and writes one route per file. Every new picture needs a new route, and the Content-Type has to be guessed by hand; get it wrong and the browser refuses to apply the CSS. Worse, taking the file name from req.params and reading it lets a request like ../server.js leak your source code.

manual-files.js
app.get('/style.css', async (req, res) => {
  res.type('text/plain');                              // wrong type: CSS ignored
  res.send(await readFile('public/style.css', 'utf8'));
});
app.get('/logo.png', /* ...another route... */);       // one route per file

app.get('/files/:name', async (req, res) => {
  res.send(await readFile('public/' + req.params.name)); // traversal risk
});

Why is express.static() better?

express.static() maps URLs to files in a folder automatically and sets the right Content-Type from each file's extension. It rejects paths that try to climb out of the root with .., and adds caching headers such as ETag, Last-Modified and Cache-Control. Your own code shrinks to a single line pointing at a folder.

Core concept: URL path equals file path inside the folder

With app.use(express.static(dir)), the request path is appended to dir to find a file. /css/site.css becomes dir/css/site.css, and a directory path ending in /, such as /, looks for index.html by default. The folder name public does not appear in the URL: requesting /public/css/site.css looks for dir/public/css/site.css and finds nothing. If the file exists, the middleware sends it and the chain stops; if not, it calls next() and the request continues to the routes below.

A relative path such as express.static('public') is resolved from the folder the process was started in, the cwd. Run the app from outside the project folder and every file returns 404. So always pass an absolute path: path.join(__dirname, 'public'), or path.join(import.meta.dirname, 'public') in ESM.

Mounting with a prefix, app.use('/static', express.static(dir)), makes /static/app.js return dir/app.js. A prefix avoids name clashes with API routes and lets you apply caching rules to static files only. Registered above your routes, the static middleware checks the disk first; below them, routes go first. When a file and a route share a name, this order decides which one wins.

On the security side, the static middleware does some work for you. It joins the path to the root folder, normalizes it, and refuses requests that try to climb out of the root with ... Files and folders whose names start with a dot are treated as missing by default. Every other file you put in the folder, though, is handed out with no further checks.

OptionDefaultWhat it does
index'index.html'File shown for a directory; false turns it off
maxAge0How long browsers may cache ('1d' = 86400 seconds)
dotfiles'ignore'Files such as .env get a 404 as if missing
fallthroughtrueMissing file calls next() instead of erroring
Mental model: check the disk, else move on
  1. Strip the prefix, keep the path
  2. Look for root + path on disk
  3. Found: send with type + cache headers
  4. Missing: next() to routes or 404

Treat every file in the static folder as public; keep server code and secrets outside it.

General pattern

javascript
const dir = path.join(__dirname, 'public');   // absolute, not cwd-relative

app.use(express.static(dir));                 // /file.ext -> dir/file.ext
app.use('/prefix', express.static(dir, {      // /prefix/file.ext -> dir/file.ext
  maxAge: '1d',                               // Cache-Control max-age
  index: false,                               // no index.html for folders
}));

The first form opens the folder at the site root; the second opens it under a prefix with options. You can mount several folders, and Express searches them in registration order.

Example: static files and an API together

The example builds a tiny project in a temporary folder: public/ holds index.html, css/site.css and a mistakenly placed .env file, while secret.txt sits outside public. It then sends five requests, prints what was and was not served, closes the server and deletes the temp folder.

static-demo.mjs
import express from 'express';
import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';

// Build a tiny project in a temp folder: public/ is served, secret.txt is not
const root = await mkdtemp(path.join(tmpdir(), 'static-demo-'));
const publicDir = path.join(root, 'public');
await mkdir(path.join(publicDir, 'css'), { recursive: true });
await writeFile(path.join(publicDir, 'index.html'), '<h1>Shop</h1>');
await writeFile(path.join(publicDir, 'css', 'site.css'), 'h1 { color: teal; }');
await writeFile(path.join(publicDir, '.env'), 'API_KEY=oops');
await writeFile(path.join(root, 'secret.txt'), 'database password');

const app = express();
app.use(express.static(publicDir));
app.get('/api/message', (req, res) => {
  res.json({ message: 'API and static files can work together.' });
});

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  for (const url of ['/', '/css/site.css', '/api/message', '/.env', '/secret.txt']) {
    const res = await fetch(base + url);
    const type = res.headers.get('content-type');
    const body = res.ok ? await res.text() : '(not served)';
    console.log(`${url.padEnd(13)} ${res.status} ${type?.split(';')[0]} ${body}`);
  }
  server.close();
  await rm(root, { recursive: true, force: true });
});

Code breakdown

  1. Mounting the folderapp.use(express.static(publicDir));

    publicDir is an absolute path from mkdtemp; in a real project you pass path.join(__dirname, 'public') the same way.

  2. index.html for /await writeFile(path.join(publicDir, 'index.html'), '<h1>Shop</h1>');

    No route handles /, yet the default index option returns public/index.html for it.

  3. Correct typesconst type = res.headers.get('content-type');

    The output shows text/html for .html and text/css for .css: Express sets them from the file extensions.

  4. Falling through to the APIapp.get('/api/message', (req, res) => {

    There is no public/api/message file, so the static middleware calls next() and the request reaches this route.

  5. What stays privateawait writeFile(path.join(publicDir, '.env'), 'API_KEY=oops');

    .env gets a 404 thanks to the default dotfiles: 'ignore', and secret.txt sits outside the root, so no URL can reach it. Still, putting .env in public is the real mistake; do not rely on the default.

You should see
/             200 text/html <h1>Shop</h1>
/css/site.css 200 text/css h1 { color: teal; }
/api/message  200 application/json {"message":"API and static files can work together."}
/.env         404 text/html (not served)
/secret.txt   404 text/html (not served)

Browser caching and 304 Not Modified

express.static() sends an ETag (a fingerprint of the file) and a Last-Modified header with every file. When the browser asks for that file again, it sends the ETag back in an If-None-Match header, and if nothing changed the server answers 304 Not Modified with no body, which is fast because nothing is downloaded again. maxAge goes one step further: for that period the browser does not ask the server at all and uses its own cache.

text
First visit, revisit, and revisit within maxAge
-----------------------------------------------
visit 1:  GET /css/site.css            -> 200 + body + ETag "abc"
visit 2:  GET /css/site.css
          If-None-Match: "abc"         -> 304 (no body, file unchanged)
maxAge:   browser reuses its copy      -> no request sent at all

In real projects

Where this shows up in real projects

Server-rendered Express sites keep CSS, images, fonts and browser JavaScript in public/, and templates reference them with tags such as <link href="/css/site.css">. Another common setup builds a React or Vue app and serves the resulting dist/ folder with express.static(), with the API under /api. Build tools put a hash in file names such as app.3f9a1c.js, so those files get a long maxAge while index.html is not cached.

High-traffic production sites often serve static files from Nginx or a CDN such as Cloudflare or CloudFront instead of Node, leaving the Node process free for API requests. For small apps, internal tools and development, express.static() on its own is plenty. Even with a CDN in front, the same rules about what goes into the public folder apply, because the CDN copies whatever your server is willing to hand out. A file you would not want indexed by a search engine has no place in that folder.

Common mistakes

Common mistakes

1. Putting the folder name in the URL

With express.static(publicDir) mounted at the root, <link href="/public/css/site.css"> gets a 404. The folder name is not part of the URL: write /css/site.css, or mount the folder with a /public prefix.

2. Serving the whole project folder

express.static(__dirname) makes server.js, package.json and config files downloadable by URL. Keep a dedicated folder such as public/ for static files and serve only that.

3. Pointing at the folder with a relative path

express.static('public') only works when started from the project folder; launched by PM2, systemd or from another folder, every file returns 404. Use path.join(__dirname, 'public').

4. A long maxAge on files without a hash

Serve site.css with maxAge: '30d', then edit the CSS, and visitors' browsers keep using the old file for thirty days. Use long caching only for files whose names contain a content hash.

Best practices

Best practices

  • Serve hashed build output with a long maxAge and index.html without caching.
  • Keep user uploads in their own folder under their own prefix, never mixed with code.
  • If static middleware sits above the API routes, use a prefix so nothing collides with /api/... paths.

Mini challenge

Mini challenge: cached assets under /static

Create two asset files in a temp folder and write an Express app that serves them under /static with one day of caching and no index page. Check status, type and Cache-Control with four requests.

  • Create assets/app.js and assets/img/logo.svg inside a mkdtemp folder
  • Use app.use('/static', express.static(folder, { maxAge: '1d', index: false }))
  • Every other request gets a JSON 404
  • Delete the temp folder after closing the server
assets.mjs
import express from 'express';
import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';

// TODO: create a temp folder with app.js and img/logo.svg

const app = express();
// TODO: mount the folder at /static with maxAge '1d' and index false
// TODO: JSON 404 handler

// TODO: listen on port 0; fetch '/static/app.js', '/static/img/logo.svg',
//       '/app.js', '/static/'; print status, type and cache-control;
//       close the server and remove the temp folder

Expected: Expected output: /static/app.js 200 text/javascript public, max-age=86400 /static/img/logo.svg 200 image/svg+xml public, max-age=86400 /app.js 404 application/json no cache header /static/ 404 application/json no cache header

Show hint

maxAge: '1d' produces Cache-Control: public, max-age=86400. With index: false, /static/ is treated like a missing file, so next() passes it to your 404 handler.

Show solution
assets.mjs
import express from 'express';
import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';

const assets = await mkdtemp(path.join(tmpdir(), 'assets-'));
await mkdir(path.join(assets, 'img'));
await writeFile(path.join(assets, 'app.js'), "console.log('hi');");
const svg = '<svg xmlns="http://www.w3.org/2000/svg"/>';
await writeFile(path.join(assets, 'img', 'logo.svg'), svg);

const app = express();
app.use('/static', express.static(assets, { maxAge: '1d', index: false }));
app.use((req, res) => res.status(404).json({ error: 'Not found' }));

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  const urls = ['/static/app.js', '/static/img/logo.svg', '/app.js', '/static/'];
  for (const url of urls) {
    const res = await fetch(base + url);
    const type = res.headers.get('content-type')?.split(';')[0];
    const cache = res.headers.get('cache-control') ?? 'no cache header';
    console.log(`${url.padEnd(20)} ${res.status} ${type} ${cache}`);
  }
  server.close();
  await rm(assets, { recursive: true, force: true });
});

Quick quiz 1 / 3

With app.use('/assets', express.static(path.join(__dirname, 'public'))), which URL returns public/img/cat.png?

Quick quiz 2 / 3

express.static(publicDir) is mounted above app.get('/about'), and there is no public/about file. What happens to GET /about?

Quick quiz 3 / 3

A developer accidentally saves a database backup inside public/. What can happen?

What to remember

  • express.static(dir) maps URL paths to files in dir and adds Content-Type and caching headers.
  • Point at the folder with an absolute path such as path.join(__dirname, 'public'), and mount it under a prefix when useful.
  • A missing file calls next(), so static files and API routes coexist in one app.
  • Everything in the static folder is public: keep secrets, backups and server code outside it.

Serving static files — Express.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Serving Static Files | Thuta Learning