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.

Hack

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">
  <head>
    <meta charset="utf-8" />
    <title>ReactApp</title>
    <base href="/" />

    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/x-icon" href="favicon.ico" />
    <script>
      window.env = {};
      /*ENV_BEGIN*/`
      `/*ENV_END*/
        .split('\n')
        .map((kv) => kv.split('='))
        .forEach(([key, value]) => {
          window.env[key] = value;
        });
    </script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
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\
}\n" > /etc/nginx/conf.d/default.conf

EXPOSE 80

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)