How to Access Environment Variables in React Production Build
I’ve been transitioning my React app from development to production and ran into issues regarding environment variables.
Development generally involves running
npm start, or
Production generally involves running
npm run build, or
Suppose I had a single
environment variable in my
In development, this
REACT_APP_URI is available in my React application.
# docker-compose.yml version: "3" services: client: build: context: . dockerfile: Dockerfile environment: - REACT_APP_URI=http://localhost:5000 ports: - 3000:3000
However, when I bundle my React app into production-ready static files with
npm run build, this
REACT_APP_URI is not available as an environment variable.
# Dockerfile FROM node:14.16.0-alpine3.10 as builder WORKDIR /usr/app COPY package*.json . RUN npm install --only=prod COPY . . RUN npm run build
The issue here is that environment variables are only available after the container starts up.
In development, the application is running on
webpack-dev-server after the container is started.
In production, our React application needs this variable during the build itself. In order to fix this, we can use build arguments in our
Let’s move our
build.args, and for clarity, let’s rename it to
# docker-compose.yml version: "3" services: client: build: context: . dockerfile: Dockerfile args: - URI=http://localhost:5000 ports: - 3000:3000
We can pull these values inside our
We’ll then be setting a new environment variable
REACT_APP_URI equal to our
# Dockerfile FROM node:14.16.0-alpine3.10 as builder WORKDIR /usr/app COPY package*.json . RUN npm install --only=prod COPY . . # Get build argument and set environment variable ARG URI ENV REACT_APP_URI=$URI # Continue with rest of script RUN npm run build
REACT_APP_URI is now available in our production-ready React bundle.
This, of course, can also be achieved with a
docker build command using
More Docker Articles
- How to Execute a Shell Command Immediately Inside a Docker Container
- How to Remove All Docker Images Locally
- How to Fix "Port is already allocated" Error in Docker
- How to Develop with TypeScript in Docker with Hot Reloading
- How to Build TypeScript for Production in Docker
- How to Secure a Docker Container with Distroless Images
- How to Dockerize the MERN Stack for Development
- How to Dockerize a Node.js/Mongo App with Live Reload (nodemon)
- How to Update Docker Containers on File Change