How to Serve Static Files in Express: Simple Guide
In Express, you serve static files using the built-in
express.static middleware. You specify the folder containing your static files by calling app.use(express.static('folderName')), and Express will automatically serve files from that folder.Syntax
Use express.static middleware to serve static files. You pass the folder path containing your files as an argument. Then, use app.use() to add this middleware to your Express app.
express.static('folderName'): Middleware to serve files from the folder.app.use(): 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 directly via the browser.
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 in
express.static. - Placing static files outside the specified folder.
- Forgetting to use
app.use()to add the middleware. - Trying to serve static files before setting up the middleware.
Always ensure your static files are inside the folder you specify and that the middleware is added before routes that might conflict.
javascript
import express from 'express'; const app = express(); // Wrong: static folder path typo app.use(express.static('publc')); // Misspelled folder name // Correct: // app.use(express.static('public'));
Quick Reference
| Concept | Description |
|---|---|
| express.static('folder') | Middleware to serve static files from the folder |
| app.use() | Adds middleware to Express app |
| Folder path | Relative to where you run your Node.js app |
| File access | Files are accessed by their path inside the folder |
| Order matters | Add static middleware before other routes |
Key Takeaways
Use express.static middleware with app.use() to serve static files.
Place your static files inside the folder you specify in express.static.
Ensure the folder path is correct and middleware is added before routes.
Access static files by their relative path inside the folder via browser.
Common errors come from typos in folder names or missing middleware setup.