frontend11/7/2025
frontend

Runtime Environment Variables in Frontend App

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:

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 withouth rebuilding the application.

Build Time vs. Runtime Environment Variables

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"]

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

// App.js
console.log(window.env.API_URL);
console.log(window.env.FEATURE_FLAG_A);

Environment Variables via .env File

# .env
API_URL=http://my-api-prod.com
FEATURE_FLAG_A=true