Static Middleware
Static file serving middleware that serves files from a directory with support for ETags, range requests, and conditional requests.Installation
Function
staticFiles()
Creates middleware that serves static files from the filesystem.
Signature:
root- The root directory to serve files from (absolute or relative to cwd)options- Optional configuration for file responses
Options
StaticFilesOptions
filter
Filter function to determine which files should be served.
- Type:
(path: string) => boolean - Default:
undefined(all files)
acceptRanges
Whether to support HTTP Range requests for partial content.
- Type:
boolean | AcceptRangesFunction - Default: Enables ranges only for non-compressible MIME types
Accept-Ranges: bytes is present, the compression middleware will not compress the response.
index
Files to try and serve as the index file when the request path targets a directory.
- Type:
boolean | string[] - Default:
true(uses['index.html', 'index.htm']) - Values:
true- Use default index filesfalse- Disable index file servingstring[]- Custom list of index files to try in order
listFiles
Whether to return an HTML page listing the files in a directory when the request path targets a directory.
- Type:
boolean - Default:
false
listFiles and index are set, index takes precedence.
cacheControl
Cache-Control header value for responses.
- Type:
string - Default:
undefined
etag
Whether to generate ETags for responses.
- Type:
boolean | 'strong' | 'weak' - Default:
'weak'
Basic Usage
With Cache Control
Filter Files
Multiple Directories
Custom Index Files
Disable Index Files
Directory Listing
Range Requests
Strong ETags
Disable ETags
Security
- Prevents path traversal attacks (e.g.,
../../../etc/passwd) - Only serves files with GET and HEAD requests
- Respects the configured root directory boundary
Features
- ETag support (weak and strong)
- Range requests support (HTTP 206 Partial Content)
- Conditional request support (If-None-Match, If-Modified-Since)
- Path traversal protection
- Automatic fallback to next middleware/handler if file not found
Related
- fetch-router - Router for the web Fetch API
- fs - File system utilities
- lazy-file - Used internally for streaming file contents