Middleware for serving static files from the filesystem
npm install @remix-run/static-middlewareMiddleware 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.
- 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
``sh`
npm install @remix-run/static-middleware
Static middleware is useful for serving static files from a directory.
`ts
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'))
`
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.
`ts`
let router = createRouter({
middleware: [
staticFiles('./public', {
cacheControl: 'public, max-age=31536000, immutable', // 1 year
}),
],
})
`ts`
let router = createRouter({
middleware: [
staticFiles('./public', {
filter(path) {
// Don't serve hidden files
return !path.startsWith('.')
},
}),
],
})
`ts`
let router = createRouter({
middleware: [
staticFiles('./public'),
staticFiles('./assets', {
cacheControl: 'public, max-age=31536000',
}),
],
})
- Prevents path traversal attacks (e.g., ../../../etc/passwd)
- Only serves files with GET and HEAD requests
- Respects the configured root directory boundary
- fetch-router - Router for the web Fetch API
- lazy-file` - Used internally for streaming file contents
See LICENSE