CPCODELAB
Express

Serving Static Files

5 min read

Serving Static Files

Express can serve static assets — HTML, CSS, JavaScript, images — using the built-in express.static() middleware. Point it at a directory and every file inside becomes directly accessible over HTTP.

js
import path from "path";
import express from "express";

const app = express();

// Serve everything in the "public" folder at the root URL
app.use(express.static(path.join(__dirname, "public")));

// API routes still work alongside static files
app.get("/api/status", (req, res) => {
  res.json({ ok: true });
});

When a request URL matches a file in the static directory, express.static() streams it and ends the request without calling next(). If the file does not exist, it calls next() and Express continues to the next middleware.

In production, serve static assets from a CDN or let Nginx handle them upstream. Keep Express focused on dynamic API responses where it excels.

Ready to test yourself?
Practice Express— quiz & coding exercises