express.static() is built-in middleware that serves files — images, CSS, JS, HTML — from a
folder directly, without you writing a route for each file.
Syntax
app.use(express.static("directory_name"));
Serving a public folder
Put an index.html and any assets inside a public folder, then:
const express = require("express");
const app = express();
app.use(express.static("public"));
app.get("/", (req, res) => {
res.send("Bookstore website root route");
});
const PORT = process.env.PORT || 4500;
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
Any file inside public/ is now reachable directly, e.g. public/logo.png becomes
http://localhost:4500/logo.png.
How it works
express.static()is registered with a base directory.- When a request comes in, Express checks whether a matching file exists in that directory.
- If found, the file is sent with the correct content type.
- If not found, Express passes control along (eventually resulting in a 404 if nothing else matches).
Why it's useful
- Serves HTML, CSS, JS, and images without custom routes for each.
- Handles content-type headers and caching automatically.
- Keeps static assets in one predictable folder.
- Cuts down on repetitive routing code.