Tutorial

Environment Variables in Angular

Angular

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

Need to use different values depending on the environment you’re in? If you’re building an app that talks to the Stripe API for example, you’ll want to use your test publishable key during development and then your live publishable key in production. It’s easy to do in Angular using the environment.ts file.

This post applies to Angular 2+ apps.

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

main.ts
// ...

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

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 be a different animal depending if we’re in development or production mode:

environment.ts
export const environment = {
  production: false,
  animal: '🐊'
};
environment.prod.ts
export const environment = {
  production: true,
  animal: 'πŸ”'
};

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

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


And it’s as simple as that! Angular takes care of swapping the environment file for the correct one.

Now in development mode the animal variable resolves to 🐊 and in production, if you run ng build --prod for example, animal resolves πŸ”.

Detecting Development Mode With isDevMode()

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

import { Component, OnInit, isDevMode } from '@angular/core';

@Component({ ... })
export class AppComponent implements OnInit {
  ngOnInit() {
    if (isDevMode()) {
      console.log('πŸ‘‹ Development!');
    } else {
      console.log('πŸ’ͺ Production!');
    }
  }
}

Adding a Staging Environment

It’s easy to add new environments in Angular CLI projects by adding new entries to the environments field in the .angular-cli.json file. Let’s add a staging environment for example:

.angular-cli.json
"environments": {
  "dev": "environments/environment.ts",
  "prod": "environments/environment.prod.ts",
  "staging": "environments/environment.staging.ts"
}

And now we can add a staging environment file and suddenly be a 🐻 if we build the project with ng build --env=staging:

environment.staging.ts
export const environment = {
  production: true,
  animal: '🐻'
};
Creative Commons License