configure-env-exposure

Configure Environment Variable Exposure

Control which environment variables are exposed to the frontend via env.js.

Prefix and allowlist

Only OS variables starting with JSENV_ are considered. You can allowlist specific names (without the JSENV_ prefix):

1
2
3
4
5
handler, err := servejs.NewDir(
		"./dist",
		servejs.WithEnvAllowlist("API_URL", "FEATURE_FLAG"), // exposes JSENV_API_URL, JSENV_FEATURE_FLAG
)
if err != nil { /* handle err */ }

If you don’t provide an allowlist, all JSENV_* variables are exposed by default.

Exposure modes

Choose how variables appear in env.js:

  • EnvModeGlobals (default): each variable as window.NAME = "value".
  • EnvModeObject: a single object window.__ENV__ = { NAME: "value" }.
  • EnvModeBoth: emit both forms.
1
2
3
4
5
handler, err := servejs.NewDir(
		"./dist",
		servejs.WithEnvExposure(servejs.EnvModeObject),
		servejs.WithEnvObjectName("ENV"), // optional, default is __ENV__
)

Tip: If you use the object form, you can freeze it in app code to avoid accidental mutation:

1
2
3
4
5
<script src="/env.js"></script>
<script>
	Object.freeze(window.ENV); // or window.__ENV__ if using the default name
	// use window.ENV.API_URL
}</script>