Properly defining environment variables in Cloud Run for my React App

Viewed 668

I am currently deploying a react application (front-end only) using Cloud Run, I have created a trigger for a cloud build to run which deploys the app using Cloud Run.

However, when I'm trying to create some environment variables to access in my components using cloud run UI I cannot access them due to the fact (from my understanding) that the environments are defined within the instance of the app and not the user's browser.

So my question is - How should I properly approach this issue? I've tried perhaps building sort of "config.json", but I wasn't able to find a proper way to mount the files in different environments.

2 Answers

You'll want to do the following. First, install https://www.npmjs.com/package/env-cmd

Next, you can specify the .env to be used depending upon your environment as so. The below code allows you to specify configuration declaratively rather than imperatively. Now, when you say process.env.REACT_APP_ENV1 process.env.REACT_APP_ENV2 process.env.REACT_APP_ENV3, then depending on env the correct values will be transparently picked up.

"scripts": {
    "start": "env-cmd -f env_anotherenv.env react-scripts start",
    "start_vscode": "env-cmd -f env_vscode.env react-scripts start",
    "build_staging": "env-cmd -f env_staging.env react-scripts build --profile",
    "build_production": "env-cmd -f env_production.env react-scripts build --profile"
}

Example of env_production.env will be

REACT_APP_ENV1 = someenv1
REACT_APP_ENV2 = someenv2
REACT_APP_ENV3 = someenv3

Example of env_staging.env will be

REACT_APP_ENV1 = someotherenv1
REACT_APP_ENV2 = someotherenv2
REACT_APP_ENV3 = someotherenv3

I would suggest you bake in your environment variables in your build artifacts which you then access using process.env.VARIABLE_1 as described here.

Use a multi-stage docker build. In your build stage populate a .env file from build-args (e.g using envsubst) before running npm run build. Here is a sample using a template that you can push to your git repo.

ARG VARIABLE_1
ARG VARIABLE_2
COPY .env.template .
RUN /bin/sh -c "envsubst '\$VARIABLE_1 \$VARIABLE_2' < .env.template > .env"

.env.template

VARIABLE_1=${VARIABLE_1}
VARIABLE_2=${VARIABLE_2}

Depending on how your cloud build triggers are set up, the values for the build args can be sourced from substitution variables. The final stage can be based on the nginx image, here you copy the built static files bundle and serve using nginx. See a full docker example here

This way you do not expose a .env file and there is no environment variables configuration to be done from the cloud run end.

Related