Serve a public asset directory
Expose frontend assets such as HTML, CSS, JavaScript, and images from a public directory.
Express.js · Function
express.static serves static assets from a root directory through Express middleware. An optional options object controls file lookup, caching, dotfiles, ETags, and response headers.
express.static creates built-in middleware that maps request URLs to files below a chosen root directory. Mount it directly for ordinary paths or under a route prefix for a virtual URL path; optional settings control file lookup, caching, dotfiles, headers, and related serving behavior.
express.static(root, [options]);| Name | Type | Description |
|---|---|---|
root | String | Root directory from which static assets are served. |
options | Object | undefined | Optional settings controlling how files are served, including dotfiles, ETags, extensions, caching, and headers. |
Middleware function
const express = require('express');
const app = express();
app.use('/static', express.static('public'));
app.listen(3000);Run the app from the project directory, place a file such as public/style.css there, then request /static/style.css.
Expose frontend assets such as HTML, CSS, JavaScript, and images from a public directory.
Make assets available below a URL prefix such as /static without changing their filesystem location.
Search several asset directories in order, giving earlier registrations precedence.
It is Express's built-in middleware for serving static assets. It combines the request URL with the configured root directory to determine which file to serve.
Follow-up: How can the same middleware expose files below a different URL prefix? Mount it with app.use('/prefix', express.static(root)); the prefix is virtual and need not exist on disk.
The root argument identifies the directory containing the assets. The function resolves the requested file by combining req.url with that root.
Follow-up: What is a common way to avoid dependence on the launch directory? Pass an absolute root path, commonly constructed from the application's directory.
Pass an options object as the second argument. It can configure behavior such as dotfiles, ETags, extension fallbacks, immutable caching, and custom response headers.
Follow-up: How can multiple asset directories be searched? Register express.static more than once; earlier middleware gets precedence when it serves a matching file.
serve-staticapp.useexpress.Routerexpress