Serving Static Files
The Gift Shop
Section titled “The Gift Shop”Sometimes you just want to let people grab a soda (HTML), a map (CSS), or a postcard (Image) without a customized route handler for every single file. Express has a built-in middleware for this: express.static.
Fig 1: Self-service downloads.
Opening the Doors
Section titled “Opening the Doors”// Open the 'public' folder to the worldapp.use(express.static('public'));Now, if a file exists at public/images/logo.png, the user can access it at http://localhost:3000/images/logo.png.
express.static opens the whole directory. If you put your
server.js or .env file in there, anyone can download it and steal your
secrets. Only put safe, public assets in this folder.
The Invisible Root
Section titled “The Invisible Root”Notice the URL doesn’t include /public. Express looks inside that folder. The folder itself is the root of the static server.
Folder Organization
Section titled “Folder Organization”How should you organize this?
It is standard practice to map a single directory (usually public) and then branch inside it. This keeps your middleware stack clean (one check per request) and your project root tidy.
/public /css - style.css /js - app.js /img - logo.pngCan I map multiple folders?
Yes. You can call express.static multiple times. Express will look in the first folder, then the second, and so on.
app.use(express.static('public')); // Look here first (Site assets)app.use(express.static('uploads')); // Then look here (User profile pics)This is useful for separating “app code” (which is committed to Git) from “user uploads” (which are ignored by Git).
Extra Bits & Bytes
Section titled “Extra Bits & Bytes”Express Static Resources - Demo Repo
Express: Serving Static Files