Node.js ยท Chapter 21 of 43

Serving Static Files

Express can serve static assets like HTML, CSS, images, and client-side JS directly from a folder using the built-in `express.static()` middleware.

This is commonly used to serve a frontend alongside an API, or to host uploaded files and assets.

Setting up static serving

Call `app.use(express.static('public'))` to serve every file inside the `public` folder automatically at the root URL.

Multiple static folders

You can mount multiple static directories, optionally under different URL prefixes using a path argument.

Example 1 (javascript)
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(3000);
Output
GET /style.css -> serves public/style.css

Any file placed in 'public' becomes accessible directly by its filename.

Example 2 (javascript)
app.use('/assets', express.static('uploads'));
Output
GET /assets/photo.png -> serves uploads/photo.png

The URL prefix '/assets' maps to files inside the 'uploads' folder.

Key points

  • express.static() serves files from a folder automatically.
  • Files are accessible by their relative path/filename.
  • You can mount static folders under a custom URL prefix.
  • Great for serving images, CSS, client JS, or a built frontend.
๐Ÿ’ก Note: Static file serving should generally be placed early in your middleware chain.

๐Ÿ“ Quick Quiz

1. Which middleware serves static files in Express?

2. If you use app.use(express.static('public')), where do files come from?

3. How can you mount static files under a URL prefix?