I have a docker container with a few environment variables setup. I know that in a typical use case, React is unable to read these variables as the process.env variables are replaced during transpiling.
I am trying to work around this without having to spin up a back-end server by using a plugin called react-env.
The core idea is to create a .env file which can be written to using a bash script. The bash script will copy any environmental variables to the .env file. The plugin will generate a env.js file which then will be consumed by the React application at runtime.
In my setup I created two sample environmental variables.
REACT_APP_SETUP="OK"- hardcoded in the.envfile.REACT_APP_GCP_PROJECT_ID="SOMEID"- to be written by the bash file.
.env
# .env
REACT_APP_SETUP="OK" //prewritten env for testing.
docker-entrypoint.sh
#!/bin/sh
printf "\n" >> /usr/app/.env
//env that is supposed to be copied.
printf 'REACT_APP_GCP_PROJECT_ID="%s"' SOMEID >> /usr/app/.env
serve build
Dockerfile
# Base version
FROM node:9
# Install yarn
RUN npm install yarn
# Install serve.js
RUN yarn global add serve
# Create app directory
WORKDIR /usr/app
# Copy all necessary files and grant permissions.
# - yarn.lock
# - package.json
# - .env
# - docker-entrypoint.sh
COPY . /usr/app/
COPY yarn.lock /usr/app
COPY package.json /usr/app
COPY .env /usr/app
COPY docker-entrypoint.sh /usr/app/docker-entrypoint.sh
RUN chmod 777 /usr/app/docker-entrypoint.sh
# Install dependencies.
RUN yarn
# Build application.
RUN yarn build
# Set entrypoint of application.
ENTRYPOINT [ "/usr/app/docker-entrypoint.sh" ]
App.jsx
...
console.log(env("SETUP"));
console.log(env("GCP_PROJECT_ID"));
...
Inspect Console
OK
undefined
In the example setup above, we can see the plugin works as the dockerized application does generate the env.js for the React app hence the OK console output.
However, I cannot seem to get the bash file to write to the .env file thus the undefined console output.
execing into the container also shows the .env file having both REACT_APP_GCP_PROJECT_ID="SOMEID" and REACT_APP_SETUP="OK" entries.
I suspect that the env.js is being generated before the bash file has a chance to write to the .env file.
How can i write to my .env file such that the plugin can generate a env.js file which my application can read environmental variables from?