Serving Static Files
express.static serves CSS, images and client scripts from a folder.
Syntax
app.use(express.static('public'))Websites need to serve static assets like images, stylesheets and browser JavaScript. The built-in express.static() middleware serves everything in a folder directly.
If you put a file at public/style.css, it becomes available at /style.css. You can also mount static files under a URL prefix.
Example
// Files in ./public are served at the root URL
app.use(express.static('public'));
// Or under a prefix: /assets/logo.png -> public/logo.png
app.use('/assets', express.static('public'));
app.listen(3000);When to use it
- A single-page application is built with React and the compiled dist/ folder is served as static files by Express in production.
- A developer serves favicon.ico, robots.txt, and a sitemap.xml from a public/ directory without writing dedicated routes.
- A media server uses express.static() with a maxAge option to cache images and CSS in the browser for 7 days.
More examples
Serve public directory
Mounts the public/ folder so files like public/style.css are accessible at /style.css.
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000);Cache-Control with maxAge
Serves files from dist/ under the /assets prefix with a 7-day browser cache, suitable for content-hashed assets.
app.use('/assets', express.static(
path.join(__dirname, 'dist'),
{ maxAge: '7d', immutable: true }
));Serve SPA catch-all
Combines express.static() for assets with a wildcard GET route to send the SPA's index.html for every unknown path.
app.use(express.static(path.join(__dirname, 'dist')));
// API routes
app.use('/api', require('./routes/api'));
// Catch-all: send index.html for any non-asset path
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
app.listen(3000);
Discussion