How to Use express.static Middleware in Express.js
Use
express.static middleware to serve static files like images, CSS, and JavaScript in Express.js by passing the folder path to express.static() and adding it to your app with app.use(). This middleware automatically handles requests for files in the specified folder.Syntax
The express.static middleware is used by calling express.static(root, [options]), where root is the folder path containing your static files. You then add it to your Express app using app.use() to serve those files.
- root: The folder path to serve files from.
- options (optional): Configuration like caching and index file settings.
javascript
app.use(express.static('public'))
Example
This example shows how to serve static files from a folder named public. When you visit http://localhost:3000/image.png, Express will look for image.png inside the public folder and serve it automatically.
javascript
import express from '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
Common mistakes include:
- Not specifying the correct folder path, so files are not found.
- Placing
express.staticafter routes that handle the same paths, causing static files not to be served. - Forgetting to create the static folder or put files inside it.
Always add express.static middleware before other route handlers for static files.
javascript
import express from 'express'; const app = express(); // Wrong: static middleware after route app.get('/image.png', (req, res) => { res.send('This blocks static file'); }); app.use(express.static('public')); // This won't serve files if route matches first // Correct: static middleware before routes // app.use(express.static('public')); // app.get('/image.png', (req, res) => { // res.send('This route will not block static files'); // });
Quick Reference
- express.static(root): Serve static files from
rootfolder. - app.use(): Add middleware to Express app.
- Place static middleware before other routes.
- Static files are served relative to the folder path.
Key Takeaways
Use express.static with app.use to serve static files from a folder.
Place express.static middleware before other routes to avoid blocking static files.
Provide the correct folder path to express.static for your static assets.
Static files like images, CSS, and JS are served automatically from the specified folder.
Check that your static folder and files exist to avoid 404 errors.