Serving Static Assets with Express
By Flavio
Published · Updated
Tagged: Express.js
Learn how to serve static assets like images and CSS in Express with the express.static() middleware, exposing a public folder at the root URL of your app.
It’s common to have images, CSS and more in a public subfolder, and expose them to the root level:
const express = require('express')
const app = express()
app.use(express.static('public'))
/* ... */
app.listen(3000, () => console.log('Server ready'))
If you have an index.html file in public/, that will be served if you now hit the root domain URL (http://localhost:3000)
How files map to URLs
The folder name is not part of the URL. With this structure:
public/
index.html
about.html
css/style.css
images/logo.png
you get these URLs:
http://localhost:3000/
http://localhost:3000/about.html
http://localhost:3000/css/style.css
http://localhost:3000/images/logo.png
Express sets the Content-Type header from the file extension, so style.css is sent as text/css.
Use an absolute path
express.static('public') resolves public from the folder where you ran node, not from the folder of your script. If you start the app from another folder, for example node src/server.js from the project root, you get 404s on every file.
Build an absolute path instead. With CommonJS:
const path = require('node:path')
app.use(express.static(path.join(__dirname, 'public')))
With ES modules __dirname doesn’t exist. Use import.meta.dirname, available since Node 20.11:
import express from 'express'
import path from 'node:path'
const app = express()
app.use(express.static(path.join(import.meta.dirname, 'public')))
Serve files under a prefix
Pass a path as the first argument to app.use() to put all the files under a prefix:
app.use('/static', express.static('public'))
Now public/css/style.css is at /static/css/style.css.
Serve more than one folder
Call express.static() once per folder:
app.use(express.static('public'))
app.use(express.static('uploads'))
Express looks in the folders in the order you added them. If both have an about.html, the one in public wins.
Static files and routes: order matters
Middleware runs in the order you add it. If express.static() comes first and public/index.html exists, this route never runs for /:
app.use(express.static('public'))
app.get('/', (req, res) => {
res.send('Home') // never reached, index.html is served instead
})
Move the route above express.static() if the route should win, or rename the file.
Useful options
express.static() takes an options object as its second argument:
app.use(
express.static('public', {
extensions: ['html'],
index: 'index.html',
dotfiles: 'ignore',
})
)
extensions: when a file is not found, try these extensions. With['html'],/aboutservesabout.html, so you get URLs without.htmlindex: the file sent when a folder is requested. The default isindex.html. Set it tofalseto turn it offdotfiles: what to do with files starting with a dot, like.env. The default,'ignore', acts as if they don’t exist, and'allow'serves themredirect: on by default. A request for/docsredirects to/docs/whendocsis a folder
Caching
By default Express sends Cache-Control: public, max-age=0, along with an ETag and a Last-Modified header. The browser checks with the server on every request and gets a 304 Not Modified if the file didn’t change.
If your build tool puts a hash in the file names, like app.3f9a1c.js, the content of a given URL never changes, and you can tell the browser to cache it for a year:
app.use(
'/assets',
express.static('dist/assets', {
maxAge: '1y',
immutable: true,
})
)
This sends Cache-Control: public, max-age=31536000, immutable. Don’t do this for files whose name stays the same when the content changes, like index.html, or people will keep seeing the old version.
To set other headers, use setHeaders:
app.use(
express.static('public', {
setHeaders(res, filePath) {
if (filePath.endsWith('.pdf')) {
res.set('Content-Disposition', 'attachment')
}
},
})
)
Custom 404 page
When a file is not found, express.static() calls the next middleware. So add a handler at the end of your app to send your own 404 page:
app.use(express.static('public'))
// ...your routes
app.use((req, res) => {
res.status(404).sendFile(path.join(__dirname, 'public', '404.html'))
})
Single page apps: send index.html for every route
With a React or Vue app that does its own routing, a URL like /dashboard/settings must return index.html. Add a catch-all route after express.static() and your API routes:
app.use(express.static(path.join(__dirname, 'public')))
app.get('/api/hello', (req, res) => res.json({ hello: 'world' }))
app.get('/{*splat}', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'))
})
In Express 5 the old app.get('*', ...) throws Missing parameter name at index 1: * when the app starts. The wildcard needs a name, and /{*splat} also matches /.
See how to send files using Express for more on res.sendFile().
Never serve your project folder
Don’t do this:
app.use(express.static(__dirname))
Anyone can then download server.js, package.json and every other file in your project. Dotfiles like .env are hidden by default, but your source code is not. Keep the public files in their own folder and serve only that folder.
In production
express.static() is fine for small apps. For a busy site, the Express docs recommend putting a reverse proxy cache like Nginx, or a CDN, in front of your app, so static files don’t go through Node at all.
Want me to talk about your product? You can sponsor this site.