How do you serve static files such as images and CSS in Express?
Use the built-in express.static middleware with a folder path. Files inside that folder are served directly by URL, and you can add a prefix and caching options.
Explain it simply
Some files never change per user: logos, stylesheets, a PDF syllabus. Rather than writing a route for each, you tell Express, "This folder is public. Anything inside can be fetched by its filename." It works like a notice board in the corridor: anyone can read what is pinned there.
Example
const express = require("express");
const path = require("path");
const app = express();
// public/logo.png is served at GET /logo.png
app.use(express.static(path.join(__dirname, "public")));
// add a URL prefix: public/logo.png at GET /assets/logo.png
app.use("/assets", express.static(path.join(__dirname, "public"), {
maxAge: "7d", // browser cache hint
index: false, // do not serve index.html for directory URLs
}));
app.listen(3000);Details:
- Use an absolute path built with
path.join(__dirname, ...). A relative path depends on where you started the process. - Only put public files in that folder. Never place
.envor database dumps there. - If a file is not found,
express.staticcallsnext(), so later routes still run. - In production, a reverse proxy such as Nginx or a CDN often serves static files faster than Node does.
What to say in the interview
"express.static serves a directory as public files. I give it an absolute path, optionally a URL prefix and cache headers, keep secrets out of the folder, and in production let Nginx or a CDN handle heavy static traffic."
Common mistakes
- Using a relative folder path that breaks when started from another directory.
- Exposing a folder that includes config or backup files.