How to implement runtime environment variables with create-react-app, Docker, and Nginx

By Krunoslav Banovac

There are many ways to configure your React application. Let’s use an approach which respects Twelve-Factor App methodology. This means it enforces reconfiguration during runtime. Therefore no build per environment would be required.

We want to be able to run our React application as a Docker container that is built once. It runs everywhere by being configurable during runtime. The output should be a lightweight and performant container which serves our React application as static content, which we achieve by using Ngnix Alpine. Our application should allow configuration within docker-compose file such as this:

Our dream docker-compose file

We should be able to configure our React application using -e flag (environment variables) when using Docker run command.

On first glance, this approach may seem to bring too small of a benefit for the extra work it requires for initial setup. But once setup is done, environment specific configurations and deployment will be way easier to handle. So for anyone targeting dynamic environments or using orchestration systems, this approach is definitely something to consider.

First of all, it must be clear that there is no such thing as environment variables inside the browser environment. Whichever solution we use nowadays is nothing but a fake abstraction.

But, then you might ask, what about .env files and REACT_APP prefixed environment variables which come straight from documentation? Even inside the source code, these are used as process.env just like we use environment variables inside Node.js.

In reality, the object process does not exist inside the browser environment, it’s Node-specific. CRA by default doesn’t do server-side rendering. It can’t inject environment variables during content serving (like Next.js does). During transpiling, Webpack process replaces all occurrences of process.env with a string value that was given. This means it can only be configured during build time.

The specific moment when it is still possible to inject environment variables happens when we start our container. Then we can read environment variables from inside the container. We can write them into a file which can be served via Nginx (which also serves our React app). They are imported into our application using <script> tag inside the head section of index.html. So at that moment, we run a bash script which creates JavaScript file with environment variables assigned as properties of the global window object. Injected to be globally available within our application the browser way.

You will find a link to the GitHub repository at the end of the article.

Let’s start with a simple create-react-app project and create .env file with our first environment variable that we want to expose.

(1) Using CRA CLI to generate React app (2) Creating .env file within the root directory of the freshly generated project

Then let’s write a small bash script which will read.env file and extract environment variables that will be written into the file. If you set an environment variable inside the container, its value will be used, otherwise, it will fall back to the default value from .env file. It will create a JavaScript file which puts environment variable values as an object which is assigned as a property of window object.

(1) Removes the old file, and creates a new one. (2) writes JS code which opens object literal and assigns it to the global window object. (3) Reads each line of .env file and splits into key/value pair. (4) Look for the environment variable, if set, use its value, otherwise, use the default value from .env file. (5) Append it to object that we assigned to global window object (6) Close object literal

We need to add the following line to <head> element inside index.html which then imports the file created by our bash script.

index.html

Let’s display our environment variable within the application:

src/App.js

During development, if we don’t want to use Docker, we can run bash script via npm script runner by modifying package.json:

Running shell script, then react-script start

And if we run yarn dev we should see output like this:

Using default API_URL value from .env file

There are two ways to reconfigure environment variables within dev. Either change the default value inside .env file or override defaults by running yarn devcommand with environment variables prepended:

Using API_URL value which was passed via CLI

And finally, edit .gitignore so that we exclude environment configurations out of the source code:

Adding generated files to .gitignore

As for the development environment, that’s it! We are half-way there. We haven’t made a huge difference at this point compared to what CRA offered by default for the development environment. The true potential of this approach shines in production.

Now we are going to create minimal Nginx configuration so that we can build an optimized image which serves the production-ready application.

Creating a folder with Nginx configuration files

The main configuration file should look somewhat like this:

conf/conf.d/default.conf

It’s also useful to enable gzip compression so that our assets are more lightweight during network transition:

conf/conf.d/gzip.conf

Now that our Nginx configuration is ready, we can finally create Dockerfile and docker-compose files:

Creating Docker files

Initially, we use node:alpine image to create an optimized production build of our application. Then, we build a runtime image on top of nginx:alpine .

Now our container is ready. We can do all the standard stuff with it. We can build a container, run it with inline configurations and push it to a repository provided by services such as Dockerhub.

Example of build, run and push commands

The above docker run command should output application like so:

Using API_URL which was provided via environment variable flag to docker run command

Lastly, let’s create our docker-compose file. You will usually have different docker-compose files depending on the environment and you will use -f flag to select which file to use.

And if we do docker-compose up we should see output like so:

Using API_URL which was provided via docker-compose environment property

Great! We have now achieved our goal. We can reconfigure our application easily in both development and production environments in a very convenient way. We can now finally build only once and run everywhere!

If you got stuck or have additional ideas, access the source code on GitHub.

The current implementation of the shell script will print all variables included within the .env file. Most of the time we don’t want to expose all of them. You could implement filters for variables you don’t want to expose using prefixes or a similar technique.

As noted above, the build time configuration will satisfy most use cases. You can rely on the default approach using .env file per environment and build a container for each environment and inject values via CRA Webpack provided environment variables.

You could also have a look at this CRA GitHub repository issue which covers this problem. By now, there should be more posts and issues which cover this topic. Each offers a similar solution as above. It’s up to you to decide how are you going to implement specific details. You might use Node.js to serve your application which means that you can also replace shells script with Node.js script. Note that Nginx is more convenient to serve static content.

If you have any questions or want to offer feedback; feel free to open issue on GitHub. Optionally follow me for further posts related to web technologies.