env-exposure
How Environment Exposure Works
When a browser requests /env.js, servejs serves a small JavaScript snippet containing selected environment variables.
- Source of truth: only variables from the host environment with the
JSENV_prefix are considered (e.g.,JSENV_API_URL). - Snapshot timing: variables are snapshotted when the handler is constructed and remain constant until you recreate the handler or restart the process;
env.jsis not regenerated per-request with fresh OS env reads. - Allowlist: you can optionally allowlist specific variable names (without the
JSENV_prefix), e.g.,WithEnvAllowlist("API_URL", "FEATURE_FLAG")will includeJSENV_API_URLandJSENV_FEATURE_FLAG. - Exposure modes: variables can be exposed as individual global assignments, as a single object, or both:
- Global assignments (default):
window.NAME = "value"for each name - Object:
window.__ENV__ = { NAME: "value" }(object name is configurable viaWithEnvObjectName) - Both: emits both forms
- Global assignments (default):
Tip: If you use the object mode, you may optionally freeze it in your app code to avoid accidental mutation, e.g., Object.freeze(window.__ENV__).
Using variables in JavaScript
First, make sure your HTML references the generated script:
Then, depending on your exposure mode:
-
Global assignments (default):
-
Object mode (default object name ENV):
If you configured a custom object name (e.g., WithEnvObjectName("ENV")), use window.ENV instead of window.__ENV__.
Tip (TypeScript): add a minimal global type so window.__ENV__ is typed in your project.