I'm new to react development. I have created .env file(inside root) and got some url for my application. after publish my application to azure my application not getting url values. I have stored it new .env file inside my public folder also. But its not getting values.
.env file(inside root)
REACT_APP_SERVICE_BASE_URL = https://localhost:44385/
REACT_APP_CONFIG_BASE_URL = https://localhost:44354/
js Code
require('dotenv').config()
let SERVICE_BASE_URL = process.env.PUBLIC_URL.REACT_APP_SERVICE_BASE_URL;
Can anyone have an idea to fix my issue. localhost working fine. after publish and change url is not working.
my customers have different Urls. so they need to change with their variables. So I thought if i add .env file inside public folder they can change their Url and use it
Tried this way also. But this also not calling public folder .env Its also taking root folder .env
require('dotenv').config(process.env.PUBLIC_URL+ '/.env')
As mentioned, create-react-app creates a static app, so nothing can be read from environment variables dynamically after build. Instead values from your .env file are copied into the static website during build. Any change afterwards won't change your app.
If you're using Azure App Service: Rather than building the app locally, then publishing the pre-built app bundle, you can instead publish the source of the app and have Azure App Service build the app. This way the customer-specific environment variables (App Settings) are present during build and will be set appropriately in your app.
There's two approaches:
Use a custom build script that you publish with your source code to Azure App Service. The documentation on this isn't great, but it works if you prefer to deploy from git or from a zip file. Kudu is the engine behind both of these deployment scenarios, see the wiki for details. See this example deploy script.
(recommended) Deploy your app using containers, and use an entry point script to replace the environment variables' placeholders with the customer-specific App Service's environment variable values.
Example of #2 (recommended):
Some code examples below. You can also reference this project as a working example of using this approach.
React App code to get the environment variable:
export const getGitHubToken = () => {
if (process.env.NODE_ENV !== 'production') {
if (!process.env.REACT_APP_SERVICE_BASE_URL) throw new Error('Must set env variable $REACT_APP_SERVICE_BASE_URL');
return process.env.REACT_APP_SERVICE_BASE_URL;
}
return '__REACT_APP_SERVICE_BASE_URL__';
};
Entrypoint script run by container:
#!/usr/bin/env bash
# Get environment variables to show up in SSH session
eval $(printenv | sed -n "s/^\([^=]\+\)=\(.*\)$/export \1=\2/p" | sed 's/"/\\\"/g' | sed '/=/s//="/' | sed 's/$/"/' >> /etc/profile)
pushd /home/site/wwwroot/static/js > /dev/null
pattern="main.*.js"
files=( $(compgen -W "$pattern") )
mainFile=$files
sed -i 's|__REACT_APP_SERVICE_BASE_URL__|'"$REACT_APP_SERVICE_BASE_URL"'|g' "$mainFile"
sed -i 's|__REACT_APP_CONFIG_BASE_URL__|'"$REACT_APP_CONFIG_BASE_URL"'|g' "$mainFile"
popd > /dev/null
Dockerfile:
FROM nginx
RUN mkdir -p /home/LogFiles /opt/startup /home/site/wwwroot \
&& echo "root:Docker!" | chpasswd \
&& echo "cd /home" >> /etc/bash.bashrc \
&& apt-get update \
&& apt-get install --yes --no-install-recommends \
openssh-server \
openrc \
yarn \
net-tools \
dnsutils
# init_container.sh is in react app's deploy/startup folder
COPY deploy/startup /opt/startup
COPY build /home/site/wwwroot
RUN chmod -R +x /opt/startup
ENV PORT 8080
ENV SSH_PORT 2222
EXPOSE 2222 8080
ENV WEBSITE_ROLE_INSTANCE_ID localRoleInstance
ENV WEBSITE_INSTANCE_ID localInstance
ENV PATH ${PATH}:/home/site/wwwroot
WORKDIR /home/site/wwwroot
ENTRYPOINT ["/opt/startup/init_container.sh"]
let SERVICE_BASE_URL = process.env.REACT_APP_SERVICE_BASE_URL
As mentioned here https://create-react-app.dev/docs/adding-custom-environment-variables/ .env file is for development purpose.
I suppose you use create-react-app to build your application. In that case the environment variable is injected in your appication at build time.
When you develop locally .env variables are automatically injected to your code.
In the case of a deploy on azure you shoud define your environment variables in that environment and build you application there.
Related
I have an issue, where inside my docker container of the react app, my env variables are not working (got undefined).
My Dockerfile:
FROM <my nginx image>
COPY build/. /usr/share/nginx/html
COPY config/nginx.conf /etc/nginx/nginx.conf
EXPOSE 8080 80
My .env file (in the root of the project):
REACT_APP_VAR=HELLO
And in my code, I access that env variable through process.env.REACT_APP_VAR.
However, when I execute inside my production Linux server the command docker exec client -e, I do get all the env variables, including REACT_APP_VAR, PATH, HOSTNAME and etc.
Important to say, this issue is only in the docker (in the prod server), in my windows development station it works fine (without docker).
Also, I can't add ENV inside my Dockerfile, and I rather not use the docker yaml's files.
I'm following a build once, deploy everywhere process in my react code. That means for each environment type, the build is created once and first. Deployment is the next step. Now to define env variables what's suggested is to have three .js config files (which contain js env variables) inside the root/environment folder from which we select one file at the deployment script and somehow add the contents of this file to the root of the /build folder. So only one config file is used inside the build (the one which we specify during the deployment script).
Is there any useful command to follow in the script to achieve this? So a new file lets say called config_env.js is created inside the build which can then be used to set env variables in the build.
//Config (Env)
root/environment
>development.js
const env = 'development';
const apiUrl = 'https://heyn3rait4.execute-api.us-west-2.amazonaws.com/dev/';
>qa.js
const env = 'qa';
const apiUrl = 'https://heyn3rait4.execute-api.us-west-2.amazonaws.com/dev/';
>production.js
const env = 'production';
const apiUrl = 'https://heyn3rait4.execute-api.us-west-2.amazonaws.com/dev/';
//Pipeline code
build-static-pages:
stage: build
# image for running Docker in Docker
image: node
script:
# build the static pages with NPM
- npm ci --production
- npm run-script build
- echo `${CI_PROJECT_DIR}/get_component_version.py` > ${BUILD_DIR}/ver.txt
- ls -alF ${BUILD_DIR}
artifacts:
paths:
- ${BUILD_DIR}
expire_in: 2 weeks
.publish-s3-dev:
stage: deploy-dev
image: python:3
script:
# todo: consider using CloudFormation or the s3_website gem
# configure the build with env variables
# install AWS CLI
- pip install awscli
# push to S3
- aws s3 cp --recursive ${CI_PROJECT_DIR}/${BUILD_DIR} s3://${FORESIGHT_DEV_BUCKET}
environment:
name: dev
url: http://d2mo71maq8qx66.cloudfront.net
How I used to statically insert env variables before at deployment script.
echo "const baseURL = '${APIURL}';\n" >> ${BUILD_DIR}/env_config.js
The sed command will allow you to edit the contents of a file on a *nix system. For example, to change the text HELLO to WORLD everywhere it appears in the file example.txt:
sed -i "s/HELLO/WORLD/g" example.txt
Leave off the g at the end and add the line number before the s if you want to replace it at a specific line:
sed -i "34s/HELLO/WORLD/" example.txt
The -i is "inline", so it will edit the file you specify.
Here's how I use this in my pipelines:
I have an empty env file that has the structure you need, but without the values. For my use case, it looks something like this:
DB_HOST={{DB_HOST}}
DB_PORT=3306
DB_USER={{DB_USER}}
DB_PASSWORD={{DB_PASSWORD}}
In a qa job, it might look like this:
sed -i "s/{{DB_HOST}}/${QA_DB_HOST}/g" config.js
sed -i "s/{{DB_USER}}/${QA_DB_USER}/g" config.js
sed -i "s/{{DB_PASSWORD}}/${QA_DB_PASSWORD}/g" config.js
where the ${} values are Gitlab CI variables in your project's CI settings.
I am deploying a create-react-app Service onto Google Cloud Run using a Dockerfile, but I want to move away from declaring env variables in a .env file, and instead, declare them on Google Cloud Run's Dashboard like so:
However, when I call the env var using
console.log("REDIRECT", process.env.REACT_APP_REDIRECT_URI)
null is returned for any env variable I try to reference. Is there another step to access these variables that I am missing?
Here is my Dockerfile:
FROM node:10-alpine as react-build
WORKDIR /app
COPY . ./
RUN yarn
RUN yarn build
FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/configfile.template
ENV PORT 8080
ENV HOST 0.0.0.0
RUN sh -c "envsubst '\$PORT' < /etc/nginx/conf.d/configfile.template > /etc/nginx/conf.d/default.conf"
COPY --from=react-build /app/build /usr/share/nginx/html
EXPOSE 8080
CMD ["nginx", "-g", "daemon off;"]
Your container serve only static files (through NGINX) and no processing is performed on Cloud Run side.
Actually, you expose your static file to your users. The users get the files and load them in their browser. The users' browser execute the Javascript and read the Env Variable on the current environment: the users' browser.
Therefore, the Cloud Run env var aren't use in this use case. You have to perform a processing on Cloud Run to use the Cloud Run env variables.
I am trying to run gatsby on a different port, But the port had to come via .env file.
I tried to put env varibale in commandline
gatsby develop -p process.env.GATSBY_PORT
You can try:
. ./.env && gatsby develop -p $GATSBY_PORT
This will export the variables from the .env file .
On Win10/HyperV (not Toolbox), simple file sharing across volumes works fine, similar to this Youtube example.
However, when trying to set up volume sharing for a React dev environment, following Zach Silveira’s example to the letter, the volume sharing no longer seems to work.
c:> mkdir docker-test
c:> cd docker-test
# CRA here
# build the container here
c:\docker-test> docker build -t test-app .
# Run docker with the volume map
c:\docker-test> docker run --rm -it -v $pwd/src:/src -p 3000:3000 test-app
# load localhost:3000
# make a change to App.js and look for change in the browser
Changes in App.js DO NOT reflect in the browser window.
I’ve heard this worked with toolbox, but there may be issues with the new Win10 HyperV Docker. What’s the secret?
Zach Silveira’s example is done on a Mac, where $(pwd) would mean "current folder.
On a Windows shell, try for testing to replace $pwd with C:/path/to/folder
As mentioned in "Mount current directory as volume in Docker on Windows 10":
%cd% could work
${PWD} works in a Powershell session.