// Tutorial //

How To Use Environment Variables in Angular

Published on June 29, 2017 · Updated on June 14, 2021
Default avatar
By Alligator.io
Developer and author at DigitalOcean.
How To Use Environment Variables in Angular

Introduction

If you’re building an app that uses an API, you’ll want to use your API key for testing environments during development and your API key for live environments during production. In Angular, you can create environment variables with the environment.ts file.

Note: This post applies to Angular 2+ apps.

In this tutorial, you will learn how to use environment variables in Angular.

Prerequisites

If you would like to follow along with this article, you will need:

This tutorial was verified with Node v16.2.0, npm v7.15.1, and @angular/core v12.0.3.

Detecting the Environment

Angular CLI projects already use a production environment variable to enable production mode when in the production environment:

src/main.ts
// ...

if (environment.production) {
  enableProdMode();
}

Angular also provides us with an utility function called isDevMode that makes it possible to check if the app in running in dev mode:

src/app/app.component.ts
import { Component, OnInit, isDevMode } from '@angular/core';

@Component({ ... })
export class AppComponent implements OnInit {
  ngOnInit() {
    if (isDevMode()) {
      console.log('Development!');
    } else {
      console.log('Production!');
    }
  }
}

This example code will log out the message 'Development! in development mode and log out the message Production! in production mode.

Adding Development and Production Variables

And you’ll also notice that by default in the /src/environment folder you have an environment file for development and one for production.

Let’s say we want to use a different key depending on if we’re in development or production mode:

For development settings in environment.ts:

src/environment/environment.ts
export const environment = {
  production: false,
  apiKey: 'devKey'
};

For production settings in environment.prod.ts:

src/environment/environment.prod.ts
export const environment = {
  production: true,
  apiKey: 'prodKey'
};

And in our component all we have to do in order to access the variable is the following:

src/app/app.component.ts
import { Component } from '@angular/core';
import { environment } from '../environments/environment';

Angular takes care of swapping the environment file for the correct one.

Run development mode with:

  1. ng serve

The apiKey variable resolves to devKey.

Run production mode with:

  1. ng serve --configuration=production

Note: Previously, the --prod option was recommended but this has been deprecated for --configuration=production.

The apiKey variable resolves to prodKey.

Adding Staging Variables

Add new environments in Angular CLI projects by adding new entries to the configurations field in the angular.json file.

Note: Previously, this configuration was set in .angular-cli.json.

Let’s add a staging environment based on the configuration used by production:

angular.json
{
  // ...
  "projects": {
    "angular-environment-example": {
      // ...
      "prefix": "app",
        "build": {
          // ...
          "configurations": {
            "staging": {
              // ...
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.stage.ts"
                }
              ],
              // ...
            },
            // ...
          },
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "staging": {
              "browserTarget": "angular-environment-example:build:staging"
            },
          }
        },
      }
    }
  }
}

And now we can add a staging environment file:

src/environments/environment.stage.ts
export const environment = {
  production: true,
  apiKey: 'stagingKey'
};

Run development mode with:

  1. ng serve --configuration=staging

Note: Previously, the --env=staging option was recommended but this has been replaced with --configuration=staging.

The apiKey variable will resolve to stagingKey.

Conclusion

In this tutorial, you learned how to use environment variables in Angular.

If you’d like to learn more about Angular, check out our Angular topic page for exercises and programming projects.

If you’ve enjoyed this tutorial and our broader community, consider checking out our DigitalOcean products which can also help you achieve your development goals.

Learn more here


About the authors
Default avatar
Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?
1 Comments

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Step 1: Install Angular App: Here, we will simply create new angular application using the bellow ng command.

Step 2: Create Environment File: Now you can see on your angular app there is a “environments” folder with default set following files. here we will add new environment file for “dev” as like bellow:

Step 3: Configure Environment Files: After creating environment file we need to configure in angular.json file. we will add dev environment, so let’s do it as following

Step 4: Use Environment Variable: now, we will just use our environment variable in our component and run app with local, dev and production configuration.

Step 5: Run App with Environment: Now, we will run our app using three environment with default, dev and production. you can run as bellow and see preview of output.