Express express.static() Middleware
What you’ll learn
- How to serve static assets using
express.static(). - How to mount static folders with path prefixes.
- How to use caching-related static options safely.
- How to avoid common static asset serving mistakes.
Syntax
javascript
app.use(express.static(root, [options]))
app.use('/assets', express.static(root, [options]))1
Serve files from public folder
javascript
const path = require('path');
app.use(express.static(path.join(__dirname, 'public')));2
Serve with URL prefix
javascript
app.use('/assets', express.static('public'));❓ FAQ
It creates middleware that serves static files from a specified directory.
Commonly in a folder like public, then mounted with app.use(express.static('public')).
Yes. Use app.use('/assets', express.static('public')) to serve files under /assets URLs.
Yes. It supports cache-related options such as maxAge and etag behavior.
No. Static middleware handles file responses directly if files exist in the configured directory.
Did you know?
express.static(root) serves files directly from a folder, making CSS, JS, images, and other assets accessible without manual route handlers.
4 people found this page helpful
