Serve a public asset directory
Expose browser assets such as HTML, CSS, JavaScript, images, or fonts from a directory.
Express.js · Function
express.static(root, [options]) returns built-in Express middleware for serving static assets from a directory. Mount it directly or under a URL prefix, and use options to control file lookup, caching, dotfiles, and response headers.
express.static creates middleware that maps request URLs to files beneath a root directory and serves matching static assets. The optional options object changes behaviors such as dotfile handling, extension fallback, caching, and response headers.
express.static(root, [options]);| Name | Type | Description |
|---|---|---|
root | String | String path to the directory from which static assets are served. |
options | Object | undefined | Optional object configuring how files are served; documented options include dotfiles, etag, extensions, immutable, maxAge, redirect, setHeaders, and fallthrough. |
Middleware function that serves static files.
const express = require('express');
const path = require('path');
const app = express();
app.use('/static', express.static(path.join(__dirname, 'public')));
app.listen(3000);Run the server and request /static/style.css to serve public/style.css.
Expose browser assets such as HTML, CSS, JavaScript, images, or fonts from a directory.
Make assets available below a URL prefix such as /static without changing their filesystem location.
Provide fallback directories so a request can search more than one static asset location.
Apply custom response metadata to files as they are served.
It is built-in Express middleware for serving static assets. The root identifies the directory, and the middleware combines the request URL with that root to determine the file.
Follow-up: How would you expose the same files beneath a prefix? Mount the middleware with app.use('/prefix', express.static(root)); the mount path provides the virtual URL prefix.
The required root is the directory from which assets are served. The optional options object controls file-serving behavior, including dotfiles, ETags, extension fallbacks, and headers.
Follow-up: How can you add a response header for served files? Supply setHeaders in the options object and set the header from its response argument.
A relative root is interpreted from the directory where the Node process was launched. Multiple static directories can be registered by calling express.static repeatedly.
Follow-up: Which directory wins when several contain the requested file? The middleware registered first gets precedence because it is evaluated first.
app.useserve-staticexpress