Skip to content

Serving Static Files

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.

A cyberpunk roadside kiosk/gift shop with neon signs 'OPEN 24/7' and 'FREE DOWNLOADS'. Glass displays show icons for images, css, and scripts.

Fig 1: Self-service downloads.

// Open the 'public' folder to the world
app.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.

Professor Solo’s Warning:

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.

Notice the URL doesn’t include /public. Express looks inside that folder. The folder itself is the root of the static server.

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.png

Can 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).


Express Static Resources - Demo Repo

Express: Serving Static Files

⏭ The Pit Stop

You’ve learned the rules of the road. Now pull over. It’s time to test your skills in the Lab.