19 KiB
HttpStaticFiles: Static File Serving Module
Overview
Add a new HttpStaticFiles module to packages/effect/src/unstable/http/ that
provides a static file server as an HttpApp. It serves files from a directory
using the existing FileSystem, Path, and HttpPlatform services.
Designed to be used as a route handler mounted at a specific path via the
router's wildcard + prefix pattern. Uses a dedicated module rather than living
inside HttpMiddleware to keep the scope isolated, consistent with how the
codebase separates concerns (e.g., Etag, HttpBody, HttpPlatform).
Module Location
packages/effect/src/unstable/http/HttpStaticFiles.ts
Public API
HttpStaticFiles.make
export const make: (options: {
readonly root: string
readonly index?: string | undefined
readonly spa?: boolean | undefined
readonly cacheControl?: string | undefined
readonly mimeTypes?: Record<string, string> | undefined
}) => Effect.Effect<
Effect.Effect<HttpServerResponse, RouteNotFound, HttpServerRequest>,
PlatformError,
FileSystem | Path | HttpPlatform
>
Uses Effect.fnUntraced per codebase conventions.
Parameters:
| Option | Type | Default | Description |
|---|---|---|---|
root |
string |
(required) | Absolute or relative path to the directory to serve |
index |
string | undefined |
"index.html" |
Index file name served when a directory is requested. Set to undefined to disable |
spa |
boolean | undefined |
false |
When true and a file is not found, serves the index file for requests that accept text/html (only when the request path has no file extension) |
cacheControl |
string | undefined |
undefined |
Value for the Cache-Control response header. Not set if undefined |
mimeTypes |
Record<string, string> | undefined |
undefined |
Extension-to-content-type mapping merged with (and overriding) built-in defaults. Keys are extensions without the dot (e.g., { "wasm": "application/wasm" }) |
Return type: An Effect that acquires FileSystem, Path, and
HttpPlatform services once at construction time, resolving to an HttpApp
(Effect<HttpServerResponse, RouteNotFound, HttpServerRequest>). The returned
HttpApp is a pure function that does not require additional services.
Error handling: The inner HttpApp fails with RouteNotFound when:
- The resolved path escapes the root directory (directory traversal)
- The file does not exist and SPA fallback is not applicable
- The file is not a regular file (e.g., a directory without a matching index)
decodeURIComponentfails on malformed URI sequences
PlatformError from FileSystem.stat() or HttpPlatform.fileResponse() is
handled internally:
PlatformErrorwithreason._tag === "NotFound"is converted toRouteNotFound- Other
PlatformErrorvalues (e.g., permission denied) are propagated as defects (unexpected errors) since the file was confirmed to exist via stat
HttpStaticFiles.layer
export const layer: (options: {
readonly root: string
readonly prefix?: string | undefined
readonly index?: string | undefined
readonly spa?: boolean | undefined
readonly cacheControl?: string | undefined
readonly mimeTypes?: Record<string, string> | undefined
}) => Layer.Layer<never, PlatformError, HttpRouter | FileSystem | Path | HttpPlatform>
Convenience layer that constructs the static file handler and mounts it on the
router. Internally does yield* HttpRouter to access the router instance
directly. When prefix is provided, uses router.prefixed(prefix).add("GET", "/*", handler) which registers the route at {prefix}/* and automatically
strips the prefix from request.url before the handler sees it. When no prefix,
calls router.add("GET", "/*", handler) directly.
| Option | Type | Default | Description |
|---|---|---|---|
prefix |
string | undefined |
undefined |
URL path prefix to mount the static handler at (e.g., "/static" registers the route at /static/*) |
All other options are forwarded to make. The route is registered as GET
only. The router's built-in HEAD fallback (which tries GET when HEAD is not
found) handles HEAD requests automatically.
Usage Examples
Basic static file serving with router
import { Effect, Layer } from "effect"
import { HttpRouter, HttpStaticFiles, HttpServerResponse } from "effect/unstable/http"
const ApiRoutes = HttpRouter.add(
"GET", "/api/health",
HttpServerResponse.text("ok")
)
// Mount static files at /static/*
const StaticFilesLayer = HttpStaticFiles.layer({
root: "./public",
prefix: "/static",
cacheControl: "public, max-age=3600"
})
const AppLayer = Layer.mergeAll(ApiRoutes, StaticFilesLayer)
SPA mode
// Mount at root — serves index.html for all unmatched HTML requests
const SpaLayer = HttpStaticFiles.layer({
root: "./dist",
spa: true,
cacheControl: "public, max-age=3600"
})
Manual construction
const program = Effect.gen(function*() {
const staticApp = yield* HttpStaticFiles.make({ root: "./public" })
// staticApp is now an HttpApp — Effect<HttpServerResponse, RouteNotFound, HttpServerRequest>
})
Behavior
Request-to-File Resolution
- Extract
request.url(the pathname portion — already prefix-stripped by the router when usingprefixed()) - Strip the query string: take everything before the first
? - Call
decodeURIComponent. If this throws (malformed URI), return 404 - Reject paths containing null bytes (
\0) — return 404 - Strip the leading
/from the path - Use
Path.normalize()to collapse..and.segments - Pre-join traversal check: After normalization, reject if the path starts
with
..(would escape root after join) - Use
Path.join(resolvedRoot, normalizedPath)to get the absolute file path - Post-join traversal check: Verify the joined path starts with
resolvedRoot + path.sep(or equalsresolvedRoot). If not, return 404 - Call
FileSystem.stat()on the resolved path
The root is resolved to an absolute path at construction time using
Path.resolve().
File Serving Flow
-
If stat succeeds and file type is
"File":- Resolve MIME type from extension
- Check for range request (see below)
- Call
HttpPlatform.fileResponse(path, options)to create the response (handles ETag, Last-Modified, platform-optimized streaming) - Set
Content-Typeheader based on MIME type - Set
Accept-Ranges: bytesheader - Add
Cache-Controlheader if configured - Check conditional request headers (see below) — may convert to 304
- Return the response
-
If stat succeeds and file type is
"Directory":- If
indexis configured, try to servepath/{index}(recurse to step 1) - Otherwise return 404 via
RouteNotFound
- If
-
If stat fails (file not found):
- If
spaistrueAND requestAcceptheader includestext/htmlAND the request path has no file extension: serveroot/{index} - Otherwise return 404 via
RouteNotFound
- If
Method Handling
The route should be registered with method "GET". The router's built-in HEAD
fallback automatically handles HEAD requests by trying the GET handler. No
explicit HEAD handling is needed.
For any other methods, the router returns 404 (the route simply doesn't match).
Conditional Requests (304 Not Modified)
After building the response via HttpPlatform.fileResponse() (which sets ETag
and Last-Modified headers automatically):
If-None-Match: If request hasif-none-matchheader:- Split the header value by
,and trim each entry - Compare each entry against the response
ETagusing weak comparison (stripW/prefix from both sides before comparing) - If any entry matches (or the header value is
*), return 304
- Split the header value by
If-Modified-Since: If request hasif-modified-sinceheader and noif-none-matchheader:- Parse the date using
new Date(value) - Compare with the response
Last-Modifiedheader - If the file has not been modified since, return 304
- Parse the date using
The 304 response:
- Uses
HttpServerResponse.empty({ status: 304 }) - Preserves
ETag,Cache-Control, andLast-Modifiedheaders from the original response - Does not include
Content-LengthorContent-Type
Note: The current implementation calls HttpPlatform.fileResponse() before
checking conditionals, which means the file is statted twice (once internally by
fileResponse, once earlier for our own stat). This is a simplicity tradeoff —
fileResponse handles ETag generation and platform-specific response creation.
A future optimization could stat once and pass info through, but this would
require changes to the HttpPlatform API.
Range Requests (206 Partial Content)
Single-range requests only. When the request includes a Range header:
- Parse the
Rangeheader. Supported formats:bytes=start-end— specific byte range (inclusive)bytes=start-— from start to end of filebytes=-suffix— last N bytes of file
- Validate the range against the file size (from stat)
- If the range is valid:
- Use
HttpPlatform.fileResponse()withoffsetandbytesToReadoptions - Set response status to
206 - Set
Content-Range: bytes start-end/totalheader - Set
Accept-Ranges: bytesheader - Set
Content-Typeheader
- Use
- If the range is not satisfiable:
- Return
416 Range Not Satisfiable - Set
Content-Range: bytes */totalheader
- Return
- If the
Rangeheader is malformed or contains multiple ranges:- Ignore it and serve the full file (200)
Range requests are only processed for GET requests. The 304 check takes precedence over range handling — if the conditional check results in 304, the range header is ignored.
All successful (200) responses include Accept-Ranges: bytes header to
advertise range support.
Built-in MIME Type Map
A default mapping of common file extensions to content types:
const defaultMimeTypes: Record<string, string> = {
// Text
html: "text/html; charset=utf-8",
htm: "text/html; charset=utf-8",
css: "text/css; charset=utf-8",
js: "text/javascript; charset=utf-8",
mjs: "text/javascript; charset=utf-8",
json: "application/json; charset=utf-8",
xml: "application/xml; charset=utf-8",
txt: "text/plain; charset=utf-8",
csv: "text/csv; charset=utf-8",
md: "text/markdown; charset=utf-8",
yaml: "text/yaml; charset=utf-8",
yml: "text/yaml; charset=utf-8",
// Images
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
gif: "image/gif",
svg: "image/svg+xml; charset=utf-8",
ico: "image/x-icon",
webp: "image/webp",
avif: "image/avif",
// Fonts
woff: "font/woff",
woff2: "font/woff2",
ttf: "font/ttf",
otf: "font/otf",
eot: "application/vnd.ms-fontobject",
// Media
mp3: "audio/mpeg",
mp4: "video/mp4",
webm: "video/webm",
ogg: "audio/ogg",
wav: "audio/wav",
flac: "audio/flac",
aac: "audio/aac",
// Other
pdf: "application/pdf",
zip: "application/zip",
gz: "application/gzip",
wasm: "application/wasm",
map: "application/json",
webmanifest: "application/manifest+json"
}
Unknown extensions default to "application/octet-stream".
User-provided mimeTypes are merged on top of defaults:
{ ...defaultMimeTypes, ...options.mimeTypes }.
MIME type is resolved from the file extension using Path.extname(), stripping
the leading dot, lowercased.
Directory Traversal Protection
Defense-in-depth approach using both pre-join and post-join validation:
- After
decodeURIComponent, reject paths containing null bytes (\0) - Strip leading
/from the decoded path Path.normalize()the path to collapse.and..segments- Pre-join check: Reject if normalized path starts with
..(relative escape) Path.join(resolvedRoot, normalizedPath)to get the absolute file path- Post-join check: Verify the joined path starts with
resolvedRoot + path.sepor equalsresolvedRoot
Both checks are needed because Path.normalize("/../../../etc/passwd") returns
"/../../../etc/passwd" (still starts with /), so the pre-join .. check
only catches relative escapes. The post-join prefix check catches all remaining
cases.
Security Considerations
-
Symlinks: The implementation follows symlinks (via
FileSystem.stat()). Symlinks pointing outside the root are caught by the post-join traversal check only if the symlink target path was resolved. SincePath.joindoes not resolve symlinks (it's a string operation), a symlink inside root pointing to/etc/passwdwould be served. This is acceptable for the initial implementation — users who need symlink restriction should handle it at the OS level. AfollowSymlinksoption could be added later. -
Hidden files (dotfiles): No special handling. Files starting with
.are served like any other file. Users can add path-based filtering via middleware if needed. -
decodeURIComponentthrowing: Malformed URI sequences (e.g.,%E0%A4%A) causedecodeURIComponentto throw. This is caught and returns 404.
Dependencies
The make function requires these services at construction time:
FileSystem— forstat()and file existence checksPath— forjoin(),normalize(),extname(),resolve()HttpPlatform— forfileResponse()which handles ETag generation, Last-Modified, and platform-optimized file streaming
The returned HttpApp does not require any additional services in its R type
(only HttpServerRequest, which is always provided by the router).
Implementation Plan
Task 1: Create the HttpStaticFiles module with full implementation
Create packages/effect/src/unstable/http/HttpStaticFiles.ts with:
- Top-level
/** @since 4.0.0 */JSDoc (required for barrel file generation viapnpm codegen) - The
defaultMimeTypesmap - A
resolveMimeType(path: Path, filePath: string, mimeTypes: Record<string, string>): stringhelper - A
resolveFilePath(path: Path, root: string, url: string): string | undefinedhelper that extracts the file path from the URL, handles decoding, normalization, and traversal checks. Returnsundefinedif the path is invalid. - The
makefunction usingEffect.fnUntraced:- Acquires
FileSystem,Path, andHttpPlatformfrom the service context - Resolves the
rootto an absolute path usingPath.resolve() - Merges user MIME types with defaults
- Returns an
HttpAppthat:- Extracts
request.url, callsresolveFilePath - Stats the file via
FileSystem.stat() - For regular files: calls
HttpPlatform.fileResponse(), setsContent-Type,Accept-Ranges: bytes, optionalCache-Control - For directories with index configured: tries
path/{index} - For not-found with
spa: true, request acceptingtext/html, and no file extension in path: servesroot/{index} - Catches
PlatformErrorwithreason._tag === "NotFound"and converts toRouteNotFound - Otherwise fails with
new RouteNotFound({ request })
- Extracts
- Acquires
- The
layerconvenience function:- Uses
yield* HttpRouterto access the router instance directly - When prefix is set:
router.prefixed(prefix).add("GET", "/*", handler) - When no prefix:
router.add("GET", "/*", handler)
- Uses
- JSDoc with
@since 4.0.0,@category, and@exampletags onmakeandlayer - Run
pnpm codegento generate barrel file export - Run
pnpm docgento verify JSDoc examples compile - A changeset in
.changeset/(package:effect, type:minor) - Ensure
pnpm check:tsgoandpnpm lint-fixpass
Task 2: Add conditional request handling (304 Not Modified)
Extend the file serving logic in HttpStaticFiles.make:
- After getting the response from
HttpPlatform.fileResponse(), check requestif-none-matchandif-modified-sinceheaders - For
if-none-match: split by,, trim, compare with weak comparison (stripW/prefix) against responseETag - For
if-modified-since(only when noif-none-match): parse date, compare with responseLast-Modified - Return
HttpServerResponse.empty({ status: 304 })with preservedETag,Cache-Control, andLast-Modifiedheaders when conditions match - Ensure
pnpm check:tsgoandpnpm lint-fixpass
Task 3: Add range request support (206 Partial Content)
Extend the file serving logic:
- Add a
parseRange(header: string, fileSize: number): { start: number; end: number } | undefinedhelper that handles:bytes=start-end(inclusive)bytes=start-(to end of file)bytes=-suffix(last N bytes)- Returns
undefinedfor malformed or multi-range headers
- Before calling
HttpPlatform.fileResponse(), check forRangeheader - For valid ranges: pass
offsetandbytesToReadtofileResponse, set response status to 206, addContent-Rangeheader - For unsatisfiable ranges: return 416 with
Content-Range: bytes */total - Add
Accept-Ranges: bytesto all 200 responses (may already be done in Task 1) - Range handling is skipped if the conditional check would return 304
- Ensure
pnpm check:tsgoandpnpm lint-fixpass
Task 4: Write tests
Create packages/effect/test/unstable/http/HttpStaticFiles.test.ts:
- Use
describe/testfrom@effect/vitestanddeepStrictEqual/strictEqualfrom@effect/vitest/utils - Use
HttpEffect.toWebHandlerLayerorHttpRouter.toWebHandlerto create test handlers - Set up real test files in a temp directory using
beforeAll/afterAllwith Node.jsfs(or use an in-memory FileSystem layer if available) - Test cases:
- Basic file serving: correct content type, response body matches file
- Index file fallback: directory path serves
index.html - Custom index file name
- Index disabled (
index: undefined) - 304 Not Modified via
If-None-Match(exact match, weak match,*) - 304 Not Modified via
If-Modified-Since - No 304 when file has been modified
- Range request:
bytes=0-10returns 206 with correct content - Range request:
bytes=5-(open-ended) - Range request:
bytes=-10(suffix) - Range request: invalid range returns 416
- Range request: malformed header serves full file (200)
- SPA fallback: missing path with
Accept: text/htmlserves index - SPA fallback: missing path with file extension returns 404
- SPA fallback: missing path without
text/htmlaccept returns 404 - Directory traversal:
../../../etc/passwdreturns 404 - Directory traversal: encoded
..%2F..%2Fetc%2Fpasswdreturns 404 - Null byte in path returns 404
- Malformed URI encoding returns 404
- Custom MIME type overrides
Cache-Controlheader is set when configured- Unknown file extension returns
application/octet-stream - Non-existent file returns 404
- Ensure tests pass with
pnpm test HttpStaticFiles - Run
pnpm check:tsgoandpnpm lint-fix