Runtime environment variables in Frontend Apps
In this note, i will show you how I to setup runtime environment variables in my Frontend projects according to 12-factor app principle which tells us:
Third 12 factor app principle: Store configuration in the environment.
In other words, you need to have single, immutable build artifact that can be deployed to any environment (dev, staging, production) by simply changing the external configuration without rebuilding the application.
Table of Contents
Open Table of Contents
Build Time vs. Runtime Environment Variables
In most cases, you will set environment variables during the build time. For example, in React app you will set environment variables in the .env file and use them in the app by accessing the process.env object.
It works for most of the cases, but if you want to follow the principle:
Build once, deploy anywhere
you need to set environment variables at runtime.
Key idea
There are several approaches how to set environment variables in your frontend app, but in this post we will focus on the approach with storing runtime-config.js file in the nginx html directory and injecting the environment variables into it.
Then we will load this file in the index.html file and use the environment variables in the app by accessing the window.env object.
Window Injection via index.html
// runtime-config.js
window.env = {
API_URL: "http://my-api-prod.com",
FEATURE_FLAG_A: true,
};
<!-- index.html -->
<head>
<script src="./runtime-config.js"></script>
</head>
Usage in App:
So instead of using process.env object, we will use window.env object to access the environment variables:
// App.js
console.log(window.env.API_URL);
console.log(window.env.FEATURE_FLAG_A);
Set env variables while building app in Docker
For containerized apps, you can inject configuration at runtime:
File: entrypoint.sh:
#!/bin/sh
cat <<EOF > /usr/share/nginx/html/runtime-config.js
window.APP_CONFIG = {
API_URL: "${API_URL}",
APP_NAME: "${APP_NAME}",
FEATURE_FLAGS: ${FEATURE_FLAGS}
};
EOF
nginx -g "daemon off;"
This command will create a runtime-config.js file in the nginx html directory and inject the environment variables into it.
You need to run this command when you build your app in Docker, e.g.
FROM nginx:stable-alpine
COPY entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
Summary
- We can set environment variables at runtime by injecting them into the
runtime-config.jsfile in the nginx html directory. - We can load this file in the
index.htmlfile and use the environment variables in the app by accessing thewindow.envobject.