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

7.4k views Asked by At

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.

2

There are 2 answers

2
Cece Dong - MSFT On

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:

enter image description here

In addition, you can refer to the following case for more suggestions:

How to use environment variables in React app hosted in Azure

0
hafij On

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.

enter image description here

Step2: Add the following task in your azure yml pipeline in appropriate place. I have created a github repo https://github.com/mail4hafij/react_azure_devops_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.