Environment Variables in Angular

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.

๐ŸŠ Alligator.io recommends

Our recommended Angular courses

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';

@Component({ ... })
export class AppComponent {
  animal: string = environment.animal;
}

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: '๐Ÿป'
};
  Tweet It

๐Ÿ•ต Search Results

๐Ÿ”Ž Searching...

Sponsored by #native_company# โ€” Learn More
#native_title# #native_desc#
#native_cta#