static-middleware
Static file serving middleware for Remix. Serves static files from a directory with support for ETags, range requests, and conditional requests.
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
Installation
npm i remixUsage
Static middleware is useful for serving static files from a directory.
import { createRouter } from 'remix/fetch-router'
import { staticFiles } from 'remix/static-middleware'
let router = createRouter({
middleware: [staticFiles('./public')],
})
router.get('/', () => new Response('Home'))With Cache Control
Internally, the staticFiles() middleware uses the createFileResponse() helper from remix/response to send files with full HTTP semantics. This means it also accepts the same options as the createFileResponse() helper.
let router = createRouter({
middleware: [
staticFiles('./public', {
cacheControl: 'public, max-age=31536000, immutable', // 1 year
}),
],
})Filter Files
let router = createRouter({
middleware: [
staticFiles('./public', {
filter(path) {
// Don't serve hidden files
return !path.startsWith('.')
},
}),
],
})Multiple Directories
let router = createRouter({
middleware: [
staticFiles('./public'),
staticFiles('./assets', {
cacheControl: 'public, max-age=31536000',
}),
],
})Security
- Prevents path traversal attacks (e.g.,
../../../etc/passwd) - Only serves files with GET and HEAD requests
- Respects the configured root directory boundary
Related Packages
fetch-router- Router for the web Fetch APIlazy-file- Used internally for streaming file contents
License
See LICENSE