2

We have a react application which is bundled using npm run build and deployed in nginx container. Other users just get the docker image and env file.

We want to keep the env variables configurable. Since the npm run build command has generated minified files and then they are added to nginx deployement directory; I was not able to find a way to update those environments.

In React app there is environments directory which has environment.ts and in code they are accessed using ${process.env.REACT_APP_API_BASE_URL}.

Below is sample Dockerfile which we use.

FROM node:14 as build-stage

WORKDIR /app
COPY package.json .
RUN npm install
COPY . .

ARG REACT_APP_API_BASE_URL
ENV REACT_APP_API_BASE_URL=$REACT_APP_API_BASE_URL

RUN npm run build

# Stage 2
FROM nginx:1.17.0-alpine

COPY --from=build-stage /app/build /usr/share/nginx/html
EXPOSE $REACT_DOCKER_PORT

CMD nginx -g 'daemon off;'

How to make env variables available to bundled javascript code ? Any suggestions would help a lot.

1 Answer 1

2

As you said, in the code you mentioned, you have to provide the REACT_APP_API_BASE_URL environment variable before running npm run build when building the docker image, and before Stage 2 process.env.REACT_APP_API_BASE_URL has been replaced with $REACT_APP_API_BASE_URL, so we don't have any opportunity to read it.


I solved this problem in two steps:

  1. During production (i.e., npm run build), replace environment variables (i.e., process.env) with a special placeholder.

  2. Then replace the placeholders with environment variables by a script before serving my application.

This way, you can pass environment variables to the docker image when running it or set environment variables on your system (e.g., in k8s' config map):

docker run -d -p 8080:80 --env REACT_APP_API_BASE_URL=base-url app

I have published this solution as a package to the npm registry.

(With this package, you will need to change process.env to import.meta.env too.)

Here is a working docker example: https://github.com/iendeavor/import-meta-env/tree/main/packages/examples/docker-starter-example .

You can find the documentation here: https://iendeavor.github.io/import-meta-env/ .

Hope this helps you! If you have any questions, please feel free to send an issue to the GitHub repository or comment below.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.