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.
Create a project structure:
Add middleware in app.js:
Access files:
http://localhost:3000/index.html → Serves index.html
http://localhost:3000/style.css → Serves style.css
You can add a virtual path to serve files:
URL: /static/index.html → Serves public/index.html
This helps organize multiple static directories without exposing the real folder structure.
Express searches directories in the order they are declared.
If a file exists in both, the first directory takes precedence.
You can set caching options when serving static files:
maxAge can be in milliseconds (1000 * 60 * 60) or strings like '1d', '2h'.
Directory Structure:
app.js:
Access: http://localhost:3000/index.html
Access image: http://localhost:3000/images/logo.png
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.
Take quizzes related to this topic and see where you stand!
Start Quiz Now