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.

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

// ...
if(environment.production) {
// ...

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 apiurl depending if we’re in development or production mode:

export const environment = {
production: false,
apiurl: 'https://api.yourdomain.com/'

export const environment = { 
  production: true, 
  apiurl: 'https://api.yourdomain1.com/' 

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

import { Component } from '@angular/core'; import { environment } from '../environments/environment'; @Component({ ... }) export class AppComponent { apiurl: string = environment.apiurl; }

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

Now in development mode the apiurl variable resolves to https://api.yourdomain.com/ and in production, if you run ng build --prod for example, apiurl resolves https://api.yourdomain1.com/.

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 Local 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:


"environments": { 
  "dev": "environments/environment.ts", 
  "prod": "environments/environment.prod.ts", 
  "local": "environments/environment.local.ts"

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


export const environment = {
 production: true, 
 apiurl: 'https://api.yourdomain.com' 

Leave a comment

Your email address will not be published. Required fields are marked *