design
Design Rationale
servejs is designed to provide a secure, idiomatic, and configurable way to serve static SPAs with runtime environment variable injection. Key design goals:
- Security-first: Only environment variables explicitly intended for the browser are considered (those prefixed with
JSENV_). By default, allJSENV_*variables are exposed; you can further restrict this set with an allowlist. - SPA support: When enabled, requests that don’t match a static file and don’t start with an excluded prefix (e.g.,
/api,/docby default) fall back toindex.html. Otherwise, they 404. Exclusions and the fallback itself are configurable. - Configurability: Functional options for all major behaviors.
- Performance: ETag support and efficient file serving.
- Idiomatic Go: Follows Go best practices for handlers and configuration.
Request routing at a glance
flowchart TD
A[Request] --> C{Inside mount?}
C -- Yes --> D{env.js?}
D -- Yes --> E[Serve env.js]
D -- No --> F{/ or /index.html?}
F -- Yes --> G[Serve index.html]
F -- No --> H{Static exists?}
H -- Yes --> I[Serve file]
H -- No --> J{SPAFallback && not excluded?}
J -- Yes --> G
J -- No --> Z
C -- No --> Z[404]