@remix-run/static-middleware
v0.4.0
Published
Middleware for serving static files from the filesystem
Readme
static-middleware
Middleware for serving static files from the filesystem for use with @remix-run/fetch-router.
Serves static files from a directory with support for ETags, range requests, and conditional requests.
Features
- ETag support (weak and strong)
- Range request support (HTTP 206 Partial Content)
- Conditional request support (If-None-Match, If-Modified-Since)
- Path traversal protection
- Automatic fall through to next middleware/handler if file not found
Installation
npm install @remix-run/static-middlewareUsage
Static middleware is useful for serving static files from a directory.
import { createRouter } from '@remix-run/fetch-router'
import { staticFiles } from '@remix-run/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-run/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
