Serving Static Files in Express
β± Estimated reading time: 2 min
Static files include assets like HTML, CSS, JavaScript, images, fonts, or any file that doesnβt change dynamically.
Express provides a built-in middleware, express.static, to serve these files easily.
1. Basic Setup
-
Create a project structure:
-
Add middleware in
app.js:
-
Access files:
-
http://localhost:3000/index.htmlβ Servesindex.html -
http://localhost:3000/style.cssβ Servesstyle.css
2. Serving Static Files from a Virtual Path Prefix
You can add a virtual path to serve files:
-
URL:
/static/index.htmlβ Servespublic/index.html -
This helps organize multiple static directories without exposing the real folder structure.
3. Serving Multiple Static Directories
-
Express searches directories in the order they are declared.
-
If a file exists in both, the first directory takes precedence.
4. Customizing Cache-Control
You can set caching options when serving static files:
-
maxAgecan be in milliseconds (1000 * 60 * 60) or strings like'1d','2h'.
5. Example Project
Directory Structure:
app.js:
-
Access:
http://localhost:3000/index.html -
Access image:
http://localhost:3000/images/logo.png
6. Key Points
-
Static middleware automatically handles caching and file types.
-
Use virtual paths to avoid exposing the actual folder.
-
Ideal for front-end assets, images, CSS, and JavaScript files.
Register Now
Share this Post
β Back to Tutorials