Middleware Guide
Use this guide when you need to serve static files in a FaasJS application.
Applicable Scenarios
- Serving static assets (HTML, JS, CSS, images) from a FaasJS server
- Hosting a single-page application (SPA) with client-side routing fallback
- Stripping a URL prefix before resolving static file paths
Default Workflow
- Place static files in a directory (e.g.,
public/). - Create a handler with
staticHandler({ root })and export it viauseMiddleware. - For SPAs, set
notFound: 'index.html'to serve the SPA entry for missing paths. - Use
stripPrefixwhen the URL path includes a prefix not present in the filesystem.
staticHandler
staticHandler creates a middleware that serves files from a directory. It is used with useMiddleware to produce an exported handler.
import { staticHandler, useMiddleware } from '@faasjs/core'
export default useMiddleware(
staticHandler({
root: `${__dirname}/public`,
}),
)
Options
| Option | Type | Default | Description |
|---|---|---|---|
root |
string |
(required) | Directory root for resolving requested files |
notFound |
boolean | string | Middleware |
false |
Fallback when a file is missing |
cache |
boolean | string |
true |
Cache resolved file lookups by root directory |
stripPrefix |
string | RegExp |
— | URL prefix to remove before resolving file path |
notFound
false(default) — leave the response untouchedtrue— send a plain404 Not Found- A string — serve a fallback file (e.g.
'index.html'for SPA routing) - A
Middlewarefunction — delegate the miss to custom logic
cache
When enabled, resolved file paths and MIME types are cached by request URL so repeated lookups skip the filesystem.
Path traversal protection
staticHandler uses isPathInsideRoot to reject requests that escape the configured root directory. This prevents ../ traversal and symlink escape attacks.
Example: Serve a public directory with SPA fallback
import { staticHandler, useMiddleware } from '@faasjs/core'
export default useMiddleware(
staticHandler({
root: `${__dirname}/public`,
notFound: 'index.html',
stripPrefix: '/static',
}),
)
Files in public/ are served under the /static URL prefix. Requests for missing files receive public/index.html, making this pattern suitable for single-page application hosting.
Review Checklist
staticHandleris used withuseMiddleware, not as a standalone exportrootpoints to an absolute directory pathnotFoundis configured when the app needs SPA-style fallback routingstripPrefixmatches the URL prefix used in the frontend build- Path traversal protection is active by default (no additional configuration needed)