How to serve static files in Express
Serving static files is fundamental for delivering CSS, JavaScript, images, and other assets in Express applications without writing custom route handlers. With over 25 years of backend development experience and as the creator of CoreUI, I’ve configured static file serving for countless web applications. The most efficient approach is using Express’s built-in express.static middleware to serve files from designated directories. This provides automatic MIME type detection, caching headers, and security features for optimal asset delivery.
Use express.static middleware to automatically serve static files from specified directories with proper caching and security.
const express = require('express')
const path = require('path')
const app = express()
// Serve static files from 'public' directory
app.use(express.static('public'))
// Serve static files with custom route prefix
app.use('/assets', express.static('public'))
// Multiple static directories
app.use(express.static('public'))
app.use(express.static('uploads'))
// Static files with options
app.use('/static', express.static('public', {
maxAge: '1d',
etag: true,
lastModified: true,
setHeaders: (res, filePath) => {
if (path.extname(filePath) === '.html') {
res.setHeader('Cache-Control', 'no-cache')
}
}
}))
// Serve SPA (Single Page Application)
app.use(express.static('dist'))
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'))
})
app.listen(3000, () => {
console.log('Server running on port 3000')
})
This setup demonstrates various static file serving patterns: basic static serving from a public directory, custom route prefixes, multiple directories, and advanced options for caching control. The SPA configuration serves static assets and falls back to index.html for client-side routing. Options like maxAge set cache headers, and setHeaders allows custom header configuration per file type.
Best Practice Note:
This static file serving pattern is used in CoreUI’s Node.js templates for efficient asset delivery. Always set appropriate cache headers for different file types and consider using a CDN or reverse proxy for production static file serving to improve performance.



