In this blog post I want to show you how you can inject environment variables into a React application.
Separating config from code is a good practice for designing applications. For example you need to add config to your front end application, when you have it deployed in different environments, e.g. a staging and a production environment.
Baking the configuration into the code or the Docker image both violates the principle of separating config from code.
The solution is to pass as environment variables, e.g. the API URL of the back end, to React when the Docker container starts up.
This blog post shows you how you nonetheless can do it:
Inject environment variables into a React application on runtime
The Create React App documentation gives a hint how to inject configuration into a React application: On the server side, you can set global variables on the window object inside your HTML.
Here is a step-by-step guide of how what you need to do:
window.API_URL = "localhost:8080";
Next, you add a bash script that picks up the environment variables and writes them to the
env_vars.js file. After that the bash script it starts to serve the front end.
cat <<EOF > /usr/src/app/build/env_vars.js window.API_URL="$API_URL"; EOF serve -s ./build/ -l 8080
Finally, set the Dockerfile’s entry point to the bash script:
RUN chmod +x docker-entrypoint.sh ENTRYPOINT ["/usr/src/app/docker-entrypoint.sh"]
Run it in Docker
Now when you start up the Docker container, you can pass a environment variable to React:
docker run -e API_URL=test.myapp.com docker-inject-env-react-runtime