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.
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(3000);GET /style.css -> serves public/style.cssAny file placed in 'public' becomes accessible directly by its filename.
app.use('/assets', express.static('uploads'));GET /assets/photo.png -> serves uploads/photo.pngThe 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.
