Serve Multiple Static Directories in Express: Simple Guide
In Express, you can serve multiple static directories by calling
app.use(express.static('directory')) multiple times with different folder paths. Each call adds a new static folder that Express will serve files from when requested.Syntax
Use app.use(express.static('folderPath')) to serve static files from a folder. To serve multiple folders, call this line multiple times with different paths.
app.use: Adds middleware to Express.express.static: Middleware to serve static files.'folderPath': The folder you want to serve files from.
javascript
app.use(express.static('public')) app.use(express.static('assets'))
Example
This example shows how to serve two static directories named public and assets. Files in both folders can be accessed directly by their names in the browser.
javascript
import express from 'express' import path from 'path' const app = express() const port = 3000 // Serve static files from 'public' folder app.use(express.static(path.join(__dirname, 'public'))) // Serve static files from 'assets' folder app.use(express.static(path.join(__dirname, 'assets'))) app.listen(port, () => { console.log(`Server running at http://localhost:${port}`) })
Output
Server running at http://localhost:3000
Common Pitfalls
1. Overlapping file names: If both static folders have files with the same name, Express serves the file from the first folder it finds. Order matters.
2. Incorrect folder paths: Make sure the folder paths are correct relative to where you run the app, or use absolute paths.
3. Missing express.static middleware: Forgetting to use express.static will not serve files.
javascript
import express from 'express' const app = express() // Wrong: missing express.static middleware app.use('public') // This does NOT serve static files // Correct: app.use(express.static('public'))
Quick Reference
Tips for serving multiple static directories in Express:
- Use multiple
app.use(express.static('folder'))calls. - Order matters: first matching file is served.
- Use absolute paths if needed with
path.join(__dirname, 'folder'). - Test file access via browser or curl.
Key Takeaways
Use multiple app.use(express.static('folder')) calls to serve multiple static directories.
Express serves the first matching file found, so order of middleware matters.
Always verify folder paths are correct relative to your app's running directory.
Use express.static middleware; without it, static files won't be served.
Test your static file URLs in the browser to confirm they are accessible.