ReactJS + Docker — Environment Variables

Jason Campos
The Startup
Published in
4 min readMar 24, 2020

React Environment Variables

Packaging your ReactJS application as a Docker container provides all of the usual Docker benefits: portability, ease of maintenance, cloud support, standardization, and on and on and on.

One pitfall of using client-side rendering with React is with the use of environment variables. Lets look at a quick example:

// Use environment vars for DOMAIN and API_KEY 
const DOMAIN = process.env.REACT_APP_DOMAIN;
const API_KEY = process.env.REACT_APP_API_KEY;
fetch(`${DOMAIN}/api?key=${API_KEY}).then(r => console.log(r.json()))

In this example, environment variables are used to set the domain and key for some imaginary service. Most software engineers experienced writing server-side software in languages like Java, NodeJS, or Python might think that if we build this application and deploy it on a server with environment variables REACT_APP_DOMAIN=http://mysite.com and REACT_APP_API_KEY=ABC12, that the variables would be set to these values.

However, since client-side rendered (CSR) ReactJS applications, this is not the case! Why? CSR applications are static javascript files. These files are compiled at build time. In order for our environment variables to be set, we need to specify them at build time.

One way we can achieve this is to set the environment variables in the build environment prior to running our build commands. For example:

export REACT_APP_DOMAIN='http://mysite.com' 
export REACT_APP_API_KEY='ABC123' npm run build

My preferred approach is to set the environment variables as a part of the build command.

REACT_APP_DOMAIN=http://mysite.com \
REACT_APP_API_KEY='ABC123' \
npm run build

CSR ReactJS Apps with Docker

By now, you might be wondering what this might mean about how we build our application to run with Docker. I build all of my CSR ReactJS applications using a multi-stage build process with two stages:

Build Stage

  • Requires node
  • Runs the build commands

Jason Campos
The Startup

Silicon Valley Software Engineer and Amazon Certified Cloud Practitioner