Serving Static Files in Express

πŸ“˜ Express.js πŸ‘ 42 views πŸ“… Nov 05, 2025
⏱ 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

  1. Create a project structure:

express-app/ β”‚ β”œβ”€ public/ β”‚ β”œβ”€ index.html β”‚ β”œβ”€ style.css β”‚ └─ script.js β”‚ └─ app.js
  1. Add middleware in app.js:

const express = require('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}`); });
  1. Access files:

  • http://localhost:3000/index.html β†’ Serves index.html

  • http://localhost:3000/style.css β†’ Serves style.css


2. Serving Static Files from a Virtual Path Prefix

You can add a virtual path to serve files:

app.use('/static', express.static('public'));
  • URL: /static/index.html β†’ Serves public/index.html

  • This helps organize multiple static directories without exposing the real folder structure.


3. Serving Multiple Static Directories

app.use(express.static('public')); app.use(express.static('assets'));
  • 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:

app.use(express.static('public', { maxAge: '1d', // Cache for 1 day }));
  • maxAge can be in milliseconds (1000 * 60 * 60) or strings like '1d', '2h'.


5. Example Project

Directory Structure:

express-app/ β”‚ β”œβ”€ public/ β”‚ β”œβ”€ index.html β”‚ └─ images/ β”‚ └─ logo.png β”‚ └─ app.js

app.js:

const express = require('express'); const app = express(); const port = 3000; app.use(express.static('public')); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
  • 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.


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes