- The problem
- The solution
- Step 1: generate
preprocessed.js(command line tool) - Step 2: load it before the bundle
- Step 3: read the variables in the browser (library)
- Demo
Sometimes we would like to have access to some env vars available in the browser - on the client side.
Obviously we have to be very careful with that, because we don't want to expose any sensitive information.
Anyway, it is often beneficial to just somehow expose some env vars to the browser, so we can use them in our browser code.
After working for few years with different frameworks I've noticed that most of the frameworks have builtin support for that:
The problem with all solutions above is that each of them allows you to expose only during build time. So it means you can't expose anything specific to PROD, STAGING or DEV environment because during build these environments are not available/visible yet.
Once build is done, exposed variables becomes part of the build itself - so in other words they are hardcoded in the bundle.
Another problem is that each of framwork seems to allow to expose only env vars prefixed with some specific prefix (e.g. VITE_ or REACT_APP_).
It would be nice to have more flexibility here and be able to pick exactly what we want to expose.
So let's try to find a solution to that.
Solution is based on the fact that for each of these framework we can modify the main HTML file and inject our custom (generated) script exposing env vars to the browser like:
// dist/preprocessed.js file
window.process = {
env: {
MY_ENV: "value",
ANOTHER_ENV_VAR: "1.99.2",
},
};It takes three steps, and envprocessor has a part for each of them:
| Step | When | What does it |
|---|---|---|
1. generate preprocessed.js |
just before the app starts in the final environment (pod, VM) | command line tool envprocessor: TypeScript or Rust |
| 2. load it before the bundle | in the main HTML file | one <script> tag |
| 3. read the variables in the browser | in your code | library envprocessor from npm: get(), getThrow(), getIntegerDefault()... |
Important thing to understand is that natural point where building/generating dist/preprocessed.js have to happen is just before launching the app in the final environment (e.g. in the container or in the K8S pod), because only there the final values of env vars are visible.
Normally our pod will be defined with entrypoint in Dockerfile something like:
FROM ...
... other stuff in Dockefile
ENTRYPOINT ["npm", "start"]
So we swap the entrypoint for a shell script which first generates the file and then starts the app as before:
# start.sh file
set -e
# this is actually important to forward errors
set -x
# we can also add debug mode (optional)
# that will print every command before executing in the pod log
envprocessor --mask "^PUBLIC_" dist/preprocessed.js
# every env var with the name starting with PUBLIC_ lands in dist/preprocessed.js
# add --debug and --verbose flags to command above if you need more details
# then we can just run our app as before
npm run startENTRYPOINT ["sh", "start.sh"]
Variables in the generated file are ordered by name (plain comparison of characters: uppercase letters first, then _, then lowercase), no matter in what order they are defined in the environment. The same environment always gives the same file.
The command line tool envprocessor exists in two implementations. They take the same options and the same mask, and for the same environment generate byte for byte the same file, so pick the one which fits the place where the file has to be generated:
| TypeScript version | Rust version | |
|---|---|---|
| Documentation | README_TS.md | README_RUST.md |
| Installation | npm install envprocessor |
one binary downloaded from the release page |
| Needs at runtime | node | nothing |
| Pick it when | there is node where the app starts (a node server) | there is no node where the app starts (nginx serving static files, Go, Python, PHP... server) |
| Adding synthetic env vars | --enrichModule (JavaScript module) |
--enrichCommand (shell command) |
| Usable as a library | yes: import ... from "envprocessor/preprocessor" |
no |
The library for the browser (step 3) is the same in both cases, it only reads what the generated file defines.
npm install envprocessor
node node_modules/.bin/envprocessor --mask "^PUBLIC_" --verbose dist/preprocessed.jsInstallation, all use cases and options: README_TS.md
# after downloading the binary for your platform from the release page
envprocessor --mask "^PUBLIC_" --verbose dist/preprocessed.jsInstallation (also in a Docker image), all use cases and options: README_RUST.md
The mask is the same in both implementations: a regex tested against the name of each env var. Variables with matching names are exposed, nothing else is.
--mask "^PUBLIC_" # every env var starting with PUBLIC_
--mask "/^public_/i" # wrapped in slashes, with flags
--mask "^(PROJECT_NAME|MY_API_KEY)<dollar>" # only env vars with exactly these namesRules:
-
The dollar character is not allowed in the mask (the tool stops with an error), because the shell would try to expand it. Use
<dollar>instead, it is replaced with the dollar character during processing. -
It can be wrapped in slashes with flags:
/^TERM_.*<dollar>/i. -
Recommended shape - one group of prefixes and one group of exact names:
/(^(PUBLIC_|FIREBASE_)|^(PROJECT_NAME|MY_API_KEY)<dollar>)/^(PUBLIC_|FIREBASE_)- every env var starting with one of these prefixes^(PROJECT_NAME|MY_API_KEY)<dollar>- only env vars with exactly these names
-
Be careful to not leave a prefix inside of the group closed with
<dollar>-^(A<dollar>|^PROD_)<dollar>will never matchPROD_HOSTNAME. -
The mask can also come from an env var injected into the pod (
--maskEnv NAME_OF_THE_ENV_VAR), so what is exposed is decided by the environment, not by the image.
Everything matching the mask is public: anybody who opens the page can read it. Be careful with broad masks.
The generated script have to be loaded before our bundled code assembled by given framework during build time, so like (just example):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My app...</title>
</head>
<body>
<script src="/dist/preprocessed.js"></script>
<!-- just make sure to load that before bundled code -->
<script src="/dist/bundle.js"></script>
<!-- generated by our framework Vite or Next.js-->
</body>
</html>In our code we can use library envprocessor which will pick up window.process.env and provide set of method to work with exported env vars in the browser.
npm install envprocessor
yarn add envprocessor
The library is needed no matter which implementation of the command line tool generated the file. It is safe to import into our bundled code.
// ESM
import {
all,
get,
has,
getDefault,
getThrow,
getTrimmedThrow,
getValidatedThrow,
getDefaultIfInvalid,
getIntegerDefault,
getIntegerThrow,
} from "envprocessor";
// CJS
const {
all,
get,
has,
getDefault,
getThrow,
getTrimmedThrow,
getValidatedThrow,
getDefaultIfInvalid,
getIntegerDefault,
getIntegerThrow,
} = require("envprocessor");
if (has("MY_ENV")) {
console.log(getThrow("MY_ENV"));
} else {
console.log("MY_ENV not found");
}
console.log(`get('USER') >${get("USER")}<`);The same import works in node (there it reads process.env), so code shared between the server and the browser can use one way of reading env vars.
all(): Returns a complete object containing all environment variables.get(key): Retrieves an environment variable if it exists, otherwise returnsundefined.has(key): Checks if an environment variable exists.getDefault(key, defaultValue): Retrieves an environment variable or returns the specifieddefaultValueif not found.getThrow(key, msg?): Retrieves an environment variable or throws an error if it doesn't exist (optionally with custom error message).getTrimmedThrow(key): Retrieves, trims, and throws an error if the variable is missing or empty after trimming.getValidatedThrow(key, validator): Retrieves and validates using aRegExpor a custom function. The validator function should return an error messagestringon failure, ornull/undefinedon success. It can also throw an error directly.getDefaultIfInvalid(key, defaultValue, validator): Retrieves and validates using aRegExpor a custom function. If validation fails (regex mismatch, function returns anything other thannull/undefined, or function throws) or the variable is not found, it returns the specifieddefaultValue.getIntegerDefault(key, defaultValue): Retrieves as an integer, or returnsdefaultValueif not found or invalid.getIntegerThrow(key): Retrieves as an integer, throws if missing or invalid.mockEnv(map): Substitutes the env vars with a custom object, for tests.
from "envprocessor" works only in code processed by a bundler (esbuild, vite ...) or executed by node.
Files loaded by the browser directly as native ESM (<script type="module">, no bundling) can't resolve bare envprocessor specifier.
For these copy node_modules/envprocessor/dist/esm/env.js to publicly served directory (e.g. public/env.js) during build and import the same functions using relative path:
<script src="/public/preprocessed.js"></script>
<script type="module">
import { get } from "/public/env.js";
console.log(get("MY_ENV"));
</script>web example /envprocessor/examples/index.html loading preprocessed.js into the browser context - just inspect it with chrome developer tools