static-middleware Overview
The staticFiles middleware serves static assets -- CSS, JavaScript, images, fonts, and other files -- directly from a directory on disk. It handles caching, conditional requests, and range requests automatically, so you do not need a separate file server during development or for simple deployments.
What is Static File Serving?
A static file is any file that is sent to the client exactly as it is stored on disk, without any server-side processing. Examples include:
- CSS stylesheets (
style.css) - JavaScript bundles (
app.js) - Images (
logo.png,hero.jpg) - Fonts (
inter.woff2) - Downloadable files (
report.pdf)
A static file server maps URL paths to files in a directory. If you have a file at ./public/css/style.css, a request for /css/style.css returns that file.
Key Features
ETag Caching
An ETag (entity tag) is a fingerprint of a file's contents. When the browser requests a file it has seen before, it sends the ETag back in an If-None-Match header. If the file has not changed, the server responds with 304 Not Modified and an empty body, saving bandwidth.
The middleware generates ETags from a hash of the file contents, so:
- The same file always produces the same ETag, even across server restarts.
- Changed files produce a different ETag immediately.
Range Requests
The middleware supports the Range header for partial content delivery. This is important for:
- Video and audio streaming -- browsers request byte ranges to enable seeking.
- Resumable downloads -- clients can resume interrupted transfers.
Cache Control
You can set Cache-Control headers to control how long browsers and CDNs cache your files. Use a function to apply different policies based on file path -- for example, hashed asset filenames can be cached forever while HTML files get a short cache.
Extension Fallbacks
Serve clean URLs like /about instead of /about.html by configuring extension fallbacks.
Quick Example
import { createRouter } from 'remix/fetch-router'
import { staticFiles } from 'remix/static-middleware'
let router = createRouter({
middleware: [
staticFiles('./public'),
],
})Place your files in a public directory:
public/
css/style.css
js/app.js
images/logo.png
index.htmlRequests for /css/style.css, /js/app.js, and /images/logo.png are served directly. Requests that do not match a file pass through to your route handlers.
Next Steps
- Tutorial: Serve Static Files -- Step-by-step guide to configuring static file serving.
- API Reference -- Complete documentation of options and behavior.