How to configure Environment Variables in Angular

How to configure Environment Variables in Angular

In this article, we will learn how we can configure environment variables for development, staging, and production environments.

Let's get started.

How to Configuring Environment Variables in Angular

Step 1: Edit environment.ts file

export const environment: {
  production: boolean;
  title: string;
  apiUrl: string;
} = {
  production: false,
  title: 'Local Environment',
  apiUrl: 'http://localhost:3000/',
};

Above we have declared 4 variables:  

1) Production  -  will be true only for the prod variables,

2) Title -  Provide a title to the environment group 

3) apiUrl -  Will point to another application server-side app for API uses.

In the same way, you can declare the variable as per your need.

  Now create the rest of our environment files within the environment folder.  

Step 2: Creating environment.dev.ts

export const environment: {
  production: boolean;
  title: string;
  apiUrl: string;
} = {
  production: false,
  title: 'Devlopment Environment',
  apiUrl: 'https://sample-dev.com/api/',
};

Step 3: Creating environment.prod.ts

export const environment: {
  production: boolean;
  title: string;
  apiUrl: string;
} = {
  production: true,
  title: 'ProductionEnvironment',
  apiUrl: 'https://sample-prod.com/api/',
};

Step 5: Update fileReplacements array in angular.json file

Now go to the angular.json file, where you will find a section of configuration where you have to mention the file replacements for different environments.

Update the fileReplacements array as shown below:


            "prod": {
              "budgets": [
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb"
                }
              ],
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
            },
            "dev": {
              "budgets": [
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb"
                }
              ],
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.dev.ts"
                }
              ]
            }

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment