ConfigMaps for Environment Variables in a React App: Stop Rebuilding, Start Injecting
TL;DR: Create React App builds bake environment variables at build time. ConfigMaps let you inject runtime configs into your container. Here’s how to bridge them so the same Docker image works across dev, staging, and production. The Problem You’ve built a React app with Create React App (CRA), Vite, or Next.js. You use .env files: js // api.js const API_URL = process.env.REACT_APP_API_URL; You build your Docker image: dockerfile FROM node:18 AS builder COPY . . RUN npm run build # REACT_APP_API_URL gets baked here FROM nginx:alpine COPY --from=builder /build /usr/share/nginx/html Then you deploy to Kubernetes. But now you want different API URLs for staging vs production. You could rebuild the image for each environment (bad – slow, wasteful). Or you could use a ConfigMap to inject values at runtime. ConfigMap to the Rescue A ConfigMap stores key-value pairs. Kubernetes can mount it as a file inside your pod. But React runs in the browser, not in the container’s filesystem. So how does the browser read a file from a ConfigMap? Simple: You serve a dynamic env-config.js file from your web server. Step-by-Step Solution Create a ConfigMap with your environment variables yaml # configmap.yaml apiVersion: v1 kind: ConfigMap metadata: name: react-env-config data: env-config.js: | window.__env = { REACT_APP_API_URL: " https://api.production.com ", REACT_APP_FEATURE_FLAG: "true" }; Apply it: bash kubectl apply -f configmap.yaml Modify your React app to read from window.__env Instead of reading process.env directly, use a runtime config: js // config.js export function getEnvVar(name) { // Runtime injection from window. env (provided by ConfigMap) if (window. env && window. env[name] !== undefined) { return window. env[name]; } // Fallback to build-time env vars (for local dev) return process.env[name]; } Use it in your components: js // api.js import { getEnvVar } from './config'; const API_URL = getEnvVar('REACT_APP_API_URL'); Serve the ConfigMap file via your web server U