How to serve static files in Node.js
Serving static files is essential for delivering frontend assets, images, stylesheets, and JavaScript files in Node.js web applications and API servers. As the creator of CoreUI, a widely used open-source UI library, I’ve configured static file serving in numerous Node.js applications for delivering CoreUI assets, documentation sites, and enterprise dashboard frontends. From my expertise, the most efficient approach is to use Express.js built-in static middleware. This method provides optimized file serving, proper caching headers, and security features while handling common web server tasks automatically.
Use Express.js express.static()
middleware to serve static files from specified directories.
const express = require('express')
const path = require('path')
const app = express()
// Serve static files from 'public' directory
app.use(express.static('public'))
// Serve files with virtual path prefix
app.use('/assets', express.static('public'))
// Serve files from absolute path
app.use(express.static(path.join(__dirname, 'public')))
// Multiple static directories
app.use(express.static('public'))
app.use(express.static('uploads'))
The express.static()
middleware serves files from a specified directory. Files are accessible at the root URL by default: files in public/css/style.css
become available at /css/style.css
. Use a virtual path prefix like /assets
to serve files under a different URL structure. Express automatically handles MIME types, caching headers, and security measures like preventing directory traversal. The middleware serves index.html files for directory requests and handles 404 errors for missing files.
Best Practice Note:
This is the same approach we use for serving CoreUI assets and documentation in Node.js applications.
Use absolute paths with path.join(__dirname, 'directory')
for reliable file serving across different environments, enable compression with compression
middleware, and consider CDN integration for production applications with high traffic.