1. Use the express.static middleware:
This is the built-in middleware provided by Express to serve static files from a specified directory.
const express = require('express');
const app = express();
// Serve static files from the 'public' directory
app.use(express.static('public'));
// Example usage:
// http://localhost:3000/style.css will serve the file 'public/style.css'
2. Set up a proper directory structure:
Organize your static assets (images, CSS, JavaScript, etc.) in a dedicated directory, typically named public.
3. Consider using a reverse proxy:
For production environments, use a reverse proxy like Nginx or Apache to handle static file serving. This offloads the task from Node.js and can significantly improve performance.
4. Cache static files:
Set appropriate cache headers to instruct the browser to cache static files for a specified duration. This reduces the number of requests to your server.
app.use(express.static('public', {
maxAge: '1d' // Cache for 1 day
}));