How to Serve Static Files in Node.js Using Express
To serve static files in
Node.js, use the express.static middleware from the Express framework. This middleware lets you specify a folder where your static files like images, CSS, and JavaScript are stored, and Express will serve them automatically.Syntax
Use the express.static middleware function to serve static files. Pass the folder path containing your static files as an argument.
express.static(root, [options]): Middleware to serve files fromrootfolder.root: The folder path where static files are stored.options: Optional settings like caching and index file.
javascript
const express = require('express'); const app = express(); app.use(express.static('public'));
Example
This example creates a simple Express server that serves static files from a folder named public. Any file inside public can be accessed directly via the browser.
javascript
const express = require('express'); const app = express(); const port = 3000; // Serve static files from 'public' folder app.use(express.static('public')); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
Output
Server running at http://localhost:3000
Common Pitfalls
1. Wrong folder path: Make sure the folder path you pass to express.static is correct relative to your project root.
2. Order of middleware: Place express.static before other routes to ensure static files are served first.
3. Missing files: If files are not found, check the folder contents and file names carefully.
javascript
/* Wrong way: static middleware after routes - static files won't be served */ app.get('/', (req, res) => { res.send('Home page'); }); app.use(express.static('public')); /* Right way: static middleware before routes */ app.use(express.static('public')); app.get('/', (req, res) => { res.send('Home page'); });
Quick Reference
| Feature | Description | Example |
|---|---|---|
| Serve static folder | Serve files from a folder | app.use(express.static('public')) |
| Custom path | Serve static files under a URL path | app.use('/static', express.static('public')) |
| Set cache control | Control browser caching | app.use(express.static('public', { maxAge: '1d' })) |
| Serve index file | Serve index.html by default | Default behavior of express.static |
Key Takeaways
Use express.static middleware to serve static files easily in Node.js.
Place express.static before other routes to avoid conflicts.
Ensure the folder path is correct and contains the files you want to serve.
You can customize the URL path and caching options with express.static.
Static files like images, CSS, and JS become accessible directly via browser URLs.