How to provide preview channels on Firebase hosting with environment variables? - reactjs

I want to use preview channels on Firebase in order to share and test feature before they go live. Creating the preview channels has been simple but currently I am getting an error when using the preview channel url:
I currently use a .env file that store React environment variables that allow me to connect to firebase but when building and deploying for the preview channels these env variables can't seem to be accessed.
Any ideas on how I can get this to work please

The error is indeed due to your hosted app not having access to those environment variables specifying the Firebase project your app is supposed to connect to (e.g. to authenticate users, manage data etc.). Why they aren't accessible to your GitHub Actions' pipeline steps, I cannot tell without any insights into your setup of course.
However, one approach towards tackling the issue (without having to check your Firebase project configuration in into the version-controlled code) is to store all the required (environment) variables in GitHub so that they become available to the GitHub Actions associated with the GitHub repo you are working on. You can add them at https://github.com/<your-username>/<your-GitHub-repo-name>/settings/variables/actions. Assuming you had a React app, then shipping the environment variables alongside the code to be deployed on a preview channel can be achieved via a firebase-hosting-pull-request.yml script possibly looking similar to this one:
name: Deploy to Firebase Hosting on PR
'on': pull_request
jobs:
build_and_preview:
if: '${{ github.event.pull_request.head.repo.full_name == github.repository }}'
runs-on: ubuntu-latest
env:
REACT_APP_FIREBASE_API_KEY: ${{ vars.REACT_APP_FIREBASE_API_KEY }}
REACT_APP_FIREBASE_AUTH_DOMAIN: ${{ vars.REACT_APP_FIREBASE_AUTH_DOMAIN }}
REACT_APP_FIREBASE_PROJECT_ID: ${{ vars.REACT_APP_FIREBASE_PROJECT_ID }}
REACT_APP_FIREBASE_STORAGE_BUCKET: ${{ vars.REACT_APP_FIREBASE_STORAGE_BUCKET }}
REACT_APP_FIREBASE_MESSAGING_SENDER_ID: ${{ vars.REACT_APP_FIREBASE_MESSAGING_SENDER_ID }}
REACT_APP_FIREBASE_APP_ID: ${{ vars.REACT_APP_FIREBASE_APP_ID }}
steps:
- uses: actions/checkout#v2
- run: npm ci && npm run build
- uses: FirebaseExtended/action-hosting-deploy#v0
with:
repoToken: '${{ secrets.GITHUB_TOKEN }}'
firebaseServiceAccount: '${{ secrets.FIREBASE_SERVICE_ACCOUNT_XXX }}'
projectId: XXXXX
expires: 2d
This reads the variables stored for the repo's GitHub Actions and makes them available to all your pipeline steps being executed within the build_and_preview job.
Note: The level at which you define the environment variables inside the yaml-file has an impact on the scope of which parts of pipeline defined in the yaml-file may or may not access them. More on that in the documentation.
If you had more sensitive data to store, you could possibly store those in GitHub secrets (at https://github.com/<your-username>/<your-GitHub-repo-name>/settings/secrets/actions) available to your GitHub Actions as well and then make them available to your deployed code in a similar fashion as we did with variables.

Related

GitHub autodeploy node js app in Google cloud

I have successfully started my nodejs app (discord bot) in Google App engine and Google Compute Engine but i couldn't auto deploy the commits made on github
Is there and way to do those, so that if i commit a change the it should be updated in Google Cloud Programs
I tried Google open cloud source repositories but didn't work
I tried GitHub Actions as mentioned by #Ismail and it worked for me
# This is a basic workflow to help you get started with Actions
name: Upload to Google Cloud App Engine
# Controls when the action will run.
on:
# Triggers the workflow on push or pull request events but only for the master branch
push:
branches: [ master ]
pull_request:
branches: [ master ]
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build:
# The type of runner that the job will run on
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout#v2
- name: Set up Cloud SDK
uses: google-github-actions/setup-gcloud#master
with:
project_id: myid
service_account_key: ${{ secrets.GCP_AUTHCode }}
export_default_credentials: true
- id: Deploy
name: Deploy to App Engine
uses: google-github-actions/deploy-appengine#main
with:
project_id: myid
- uses: actions/setup-node#v1
with:
node-version: 12
- run: npm install
- run: npm install pm2 -g
- run: pm2 start index.js --watch
You can automate App Engine deployments with Cloud Build. Study and follow this GitHub App trigger guide.
With regards to build configuration, you can use this sample build config file (cloudbuild.yaml):
steps:
- name: "gcr.io/cloud-builders/gcloud"
args: ["app", "deploy"]
timeout: "1600s"
This configuration will make Cloud Build run gcloud app deploy on your repo whenever you push commits. The step will timeout if the deployment takes 27 minutes but you're free to change it.
As additional reference, here's another guide on how to automate app deployment with Cloud Source Repositories.
To summarize, you need to enable Cloud Build on your project to use its trigger feature and it will build your app from source then deploy based on your build config.

How to set .env for react app deployed with azure devops pipeline on app service

I developed a pipeline with CI/CD on azure Devops for deploying a React app on Azure web app service. Locally I'm using a .env file and this file is on .gitignore. I want to know how can i set the .env for reading it on production.
You can check the documentation below:
https://create-react-app.dev/docs/adding-custom-environment-variables/#adding-development-environment-variables-in-env
.env files should be checked into source control (with the exclusion of .env*.local ).
If you don't want to check in the .env files to DevOps, you could add the variables in the pipeline variables:
In addition, you can refer to the following case for more suggestions:
How to use environment variables in React app hosted in Azure
Many of the proposed solutions related to this issue may not work but I solved it the following way. However, first let me explain why other solutions may not (should not) work (please correct me if I am wrong)
Adding pipeline variables (even though they are environment variables) should not work since a react app is run on the client side and there is no server side code that can inject environment variables to the react app.
Installing environment variable task on the classic pipeline should not work for the same reason.
Adding to Application Settings in azure app service should not work for the same reason.
Having .env or .env.development or .env.production file in a git repo should not be a good practice as it may compromise api keys and other sensitive information.
So here is my solution -
Step1: Add all those .env files to azure devops library as secure files. You can download these secure files in the build machine using a DownloadSecureFile#1 pipeline task (yml). This way we are making sure the correct .env file is provided in the build machine before the task yarn build --mode development in the pipeline.
Step2:
Add the following task in your azure yml pipeline in appropriate place. I have created a github repo https://github.com/mail4hafij/react-yarn-azure-pipeline if you want to see a complete example.
# Download secure file from azure library
- task: DownloadSecureFile#1
inputs:
secureFile: '.env.development'
# Copy the .env file
- task: CopyFiles#2
inputs:
sourceFolder: '$(Agent.TempDirectory)'
contents: '**/*.env.development'
targetFolder: '$(YOUR_DEFINED_PROJECT_ROOT_FOLDER_VARIABLE)'
cleanTargetFolder: false
Keep note, secure files can't be edited but you can always re-upload.

NODE_ENV not getting passed from ECS Fargate to React Application

I have a React application that was built using Create-React-App. I have set up a deployment pipeline using GitHub Actions so that when I commit to branch 'pre-production' it will trigger a Docker Build and then put the build to AWS.
Here is part of the GitHub Actions .yml:
- name: Build and push image to Amazon ECR
id: build-image
env:
ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
ECR_REPOSITORY: application
IMAGE_TAG: latest
run: |
# Build a docker container and
# push it to ECR so that it can
# be deployed to ECS.
docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
echo "::set-output name=image::$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG"
Then inside my ECS Service, I have my task running which points to this build, and inside that container, I pass in the environement variables, like below:
I then console log out the NODE_ENV in the application which for some reason keeps saying production instead of development.
console.log(process.env.NODE_ENV);
check if environment variable is hard-coded somewhere, also worth trying with a different environment variable value to validate.
I'm pretty sure all the node documentation says you can't modify NODE_ENV in any way, especially the way you are attempting to do it, it's only able to be set by the build process

Successive build/releases to azure web app through DevOps pushes new build one directory deeper

I'm trying to deploy a ReactJS app to my Azure Web App through Azure DevOps. I've created a project on DevOps for it, and I'm attempting to set up a continuous integration pipeline so that every commit to master triggers a new build and deploys it to the web app. The azure-pipelines.yml file that specifies the build instructions is as below:
# Node.js with React
# Build a Node.js project that uses React.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://learn.microsoft.com/azure/devops/pipelines/languages/javascript
pool:
vmImage: 'Ubuntu 16.04'
trigger:
- master
steps:
- task: NodeTool#0
inputs:
versionSpec: '8.x'
displayName: 'Install Node.js'
- script: |
npm install
npm run build
displayName: 'npm install and build'
- task: ArchiveFiles#2
inputs:
rootFolderOrFile: '$(System.DefaultWorkingDirectory)'
includeRootFolder: false
- task: PublishBuildArtifacts#1
I created this file using the instructions provided at Build, test, and deploy Javascript Apps in Azure Pipelines
The build succeeds just fine, and I then created a release for the build using the following settings:
Azure release pipeline task setup
(Deploy Azure App Service > App Type: Web App > Package/Folder:$(System.DefaultWorkingDirectory)/**/*.zip)
I've also configured the physical path for the web app on azure to be site\wwwroot\build
The first time I create the build and release it, it gets deployed fine, and I see the changes reflected on the web app. However, every subsequent build does not automatically get updated to show on the web app. Using the diagnostic console on Kudu, I see that new builds are going one directory deeper, eg the next build will have the physical path of site\wwwroot\build\build. To see the new build, I have to manually change the path for the web app each time.
Edit: Here are some snapshots of the Azure Web App settings, and of the console on Kudu.
My question is this: How can I set up this entire process so that new builds REPLACE old builds on web app, and avoid them instead being nested inside the old build?

How to use environment variables in Github Page?

I want to deploy my create-react-app project to GitHub Pages. But I have a few secret keys. How can I manage these keys inside my React app?
Edited June 2020
Reference #alicia-jasmine
"React is purely a front-end framework. Everything accessible to React (even if you embed it through a build step) will later be visible in the front-end code and someone relatively basic to find. To really keep them secret you MUST have something server side!"
The following answer will actually expose the key in the gh-page branch on GitHub, also the keys will be accessible through the network tab in the developer console.
Original Answer
I'm also using create-react-app, and I found that this can be done by customizing your CI script with GitHub secret settings. (After the setting, you can use environment variables like this in your project.)
const apiKey = process.env.REACT_APP_APIKey
const apiSecret = process.env.REACT_APP_APISecret
To add a secret to your repository, go to your repository's Setting > Secrets, click on Add a new secret. In the screenshot below, I added 2 env variables: REACT_APP_APIKey and REACT_APP_APISecret.
Notice: All the environment variable you want to access with create-react-app need to be prefixed with REACT_APP.
After you have your secret ready, you can take a look at this post, it's about how to add your own Action upon push.
To setup your action script, go to your repository > Actions, an click on Setup workflow your self, and paste in the script provided in the post or take a look at mine script below.
I use the following script to access the 2 environment variables I set on GitHub secret. (You can access the secret you set in the script by ${{ secrets.REACT_APP_APIKey }}.)
name: CI
on:
push:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout#v1
- name: Build
run: |
npm install
npm run-script build
env:
REACT_APP_APIKey: ${{ secrets.REACT_APP_APIKey }}
REACT_APP_APISecret: ${{ secrets.REACT_APP_APISecret }}
- name: Deploy
uses: JamesIves/github-pages-deploy-action#releases/v3
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BRANCH: gh-pages
FOLDER: build
After you setup the script, the action will be triggered by any push to master
branch. After you push any commits, you can take a look at the deployment status at actions status.
You can see how hard it is for me to figure it out... so many fail attempts lol. Anyway, hope this will help :)
name: Deploy to GitHub Pages
on:
push:
branches:
- master
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout#v1
- name: Build
run: |
npm install
npm run-script build
env:
REACT_APP_INSTAGRAM_ACCESS_TOKEN: ${{ secrets.REACT_APP_INSTAGRAM_ACCESS_TOKEN }}
REACT_APP_SMTP_SECURE_TOKEN: ${{ secrets.REACT_APP_SMTP_SECURE_TOKEN }}
- name: Deploy
uses: JamesIves/github-pages-deploy-action#releases/v3
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN_KEY }}
BRANCH: gh-pages
FOLDER: dist
You can use like this to add your environment variables from GitHub secrets. This solved my problem.
I support this answer (above)
But I advice to update the gh-pages YML to version 4
Also take a look at environment variables solution because i spent hours to find out the solution
- name: Deploy
uses: JamesIves/github-pages-deploy-action#4.0.0
with:
branch: gh-pages
folder: front-app/dist
To use environment variables, the general approach which is followed is to:
Not expose them to the public
Keep it local at the time of development/production and ignore in .gitignore file.
Make the
static build out of your application Then deploy it to either github
pages or any other static website host.
While working with create-react-app you have their benefits, you can create .env in your root folder.
The structure for the .env file should follow below key-value structure:-
REACT_APP_SECRET_CODE1=dev123
REACT_APP_SECRET_CODE2=prod456
Keys in the file should be prefixed with REACT_APP and you can use these keys to access the variable in your application. For eg. process.env.REACT_APP_SECRET_CODE, this will have the value dev123
If they are truly secret, and so should not be in a repository, then there isn't a way to manage that with github-pages.
If you are okay with having them in a repository, then put them in .env and access via process.env
You can deploy your project on Heroku where you can set up your secret key.

Resources