DEV Community

Mikayel Ohanjanyan
Mikayel Ohanjanyan

Posted on

React, Docker, Runtime Environment Variables

The Problem

Containerized react apps are most commonly using static serving nginx, hence, there is no way to directly pass environment variables to javascript at runtime.


Add <script> block to index.html that will be modified runtime, and loaded with environment variables.

So our index.html should look something like this

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8" />
    <base href="/" />

    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/x-icon" href="favicon.ico" />
      window.env = {};
        .map((kv) => kv.split('='))
        .forEach(([key, value]) => {
          window.env[key] = value;
    <div id="root"></div>
Enter fullscreen mode Exit fullscreen mode

this will load provided variables into window.env.

And here is an example Dockerfile that will provide environment variables prefixed with REACT_APP_

FROM nginx:alpine

WORKDIR /usr/share/nginx/html

COPY ./dist/apps/react-app .

RUN printf "server {\n\
        listen       80;\n\
        location / {\n\
                root   /usr/share/nginx/html;\n\
                try_files \$uri \$uri/ /index.html;\n\
                add_header Cache-Control \"no-store, no-cache, must-revalidate\";\n\
}\n" > /etc/nginx/conf.d/default.conf


CMD sed  -i '/\/\*ENV_BEGIN\*\/`/r '<(env | grep --color=never "^REACT_APP_") index.html; nginx '-g daemon off;'
Enter fullscreen mode Exit fullscreen mode

Working Example

You can find full working example with nx here

Top comments (0)