Static asset hosting
Serve browser assets such as HTML, CSS, JavaScript, and images from a public directory.
Express.js · Function
serveStatic(root, options) creates middleware that serves files from a root directory based on the request URL. Missing files fall through to next(), allowing fallback middleware or multiple static directories.
Calling serveStatic with a root directory creates middleware that maps the request URL onto that directory and serves a matching file. If no file matches, it calls next() rather than ending the request, so multiple static directories or fallback handlers can be composed.
serveStatic(root, options)| Name | Type | Description |
|---|---|---|
root | string | Filesystem root directory from which requested files are served. |
options | object | Optional configuration, including index, extensions, and setHeaders behavior. |
A middleware function that serves files from the specified root and calls next() when a file is not found.
const express = require('express');
const path = require('path');
const serveStatic = require('serve-static');
const app = express();
app.use(serveStatic(path.join(__dirname, 'public')));
app.listen(3000);Serves files from the absolute public directory and lets later middleware handle requests for missing files.
Serve browser assets such as HTML, CSS, JavaScript, and images from a public directory.
Try a second directory or route handler after the first static location has no matching file.
Apply cache-control or other response headers while serving files.
serveStatic(root, options) returns middleware that serves files below root. It combines the request URL with root, and calls next() when no file is found.
Follow-up: How can static fallbacks be composed? Mount multiple serveStatic instances in sequence; a miss in one allows the next middleware to try.
The root directory is the base used to locate requested files. The middleware uses the request URL together with that root to determine which file to send.
Follow-up: How should an application serve a directory reliably regardless of its launch directory? Resolve or construct an absolute root path before passing it to serveStatic.
The index option controls directory requests. By default index.html is sent; false disables index serving, while a string or ordered array selects alternative names.
Follow-up: How could different default documents be tried in order? Pass an array such as ['default.html', 'default.htm'] as index.
express.staticserve-indexexpress