I have built my react files with a .env file containing various base URLs and API keys, using env-cmd -f .env.production craco build when .env.production being my env file.
After building I want to serve these files using PM2 command pm2 server <build location> <port>
I am successfully able to host my my static files at my desired port, but my static files are not able to read any values from .env.production file. Can anyone guide me how to use environment variables pm2 from my env file?
Also I tried to create an ecosystem.config.js for pm2 to serve my static files and store the env values inside it too. Here is the file:
module.exports = {
script: "serve",
env: {
PM2_SERVE_PATH: '.',
PM2_SERVE_PORT: 3011,
REACT_APP_MAPBOX_API_KEY : 'mykey',
REACT_APP_COG_URL : 'http://localhost:8000',
REACT_APP_LIVE_URL : 'https://something.com',
REACT_APP_RTMP_URL : 'rtmp://something.com/stream',
REACT_APP_BASE_URL : 'http://localhost:5011',
REACT_APP_SERVER_URL : 'https://something.com'
}
}
But the above config file only works the script and port part. Nothing else works
Thanking you in advance
Related
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.
I have a containerized React app that I'm trying to test out building with webpack and serving the static generated files with the NGINX image, but it's not being displayed on the port I want locally. My WebPack file is outputting files in to a directory called dist so as you can see in my Dockerfile I'm going in to that directory and copying my files to the usr/share/nginx/html directory. Is there something else I'm missing in this file?
Nginx serves on port 80, so when you run your container you'll want to do is map that port to port 3000 in your docker run command:
docker run -d -p 3000:80 app-image
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 .