How to serve static files in Express
· Category: Node.js
Short answer
Use the built-in express.static middleware to serve files from a directory such as public.
Steps
- Create a directory named
publicin your project root. - Add the middleware:
app.use(express.static('public'));. - Place files like
style.cssinsidepublic. - Access them via
http://localhost:3000/style.css. - Use a virtual path prefix:
app.use('/static', express.static('public'));.
Tips
- Use an absolute path with
path.join(__dirname, 'public')to avoid issues when the working directory changes. - Place the static middleware early so it can short-circuit requests before they hit route handlers.
Common issues
- If a requested file does not exist, static middleware passes to the next handler instead of sending a 404 by default.
- MIME types are inferred from file extensions; missing extensions may cause incorrect Content-Type headers.