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 makes files in that folder accessible via HTTP requests.Syntax
The express.static function takes one required argument: the path to the folder containing static files. You add it to your Express app using app.use(). This tells Express to serve files from that folder when requested.
express.static(root): Middleware to serve static files from therootfolder.app.use(middleware): Adds the middleware to your app.
javascript
app.use(express.static('public'))
Example
This example shows a simple Express server serving static files from a folder named public. Any file inside public can be accessed by its name in the browser.
javascript
import express from 'express'; const app = express(); const PORT = 3000; // Serve static files from the '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: If the folder path is incorrect or missing, static files won't be served.
2. Order of middleware: Place express.static before other routes that might block access.
3. Missing files: Requests for files not in the folder return 404 errors.
javascript
import express from 'express'; const app = express(); // Wrong: static middleware after other routes blocks access app.get('/', (req, res) => { res.send('Home page'); }); app.use(express.static('public')); // Correct: static middleware before other routes // app.use(express.static('public')); // app.get('/', (req, res) => { // res.send('Home page'); // });
Quick Reference
express.static('folder'): Serve static files fromfolder.app.use(express.static('folder')): Add static middleware to app.- Place static middleware before other routes.
- Use absolute or relative paths carefully.
Key Takeaways
Use express.static with app.use to serve static files from a folder.
Ensure the folder path is correct and accessible.
Place express.static middleware before other routes to avoid blocking.
Requests for missing files return 404 errors automatically.
Static files become accessible by their relative path in the folder.