Separating production and development HTTP URLs using environment.ts file in Angular
Configure and build Angular application for different environments
By default Angular application can be built to development environment or to production environment. Based on target…
During development of Angular application, we use some mock REST APIs or development specific APIs. Once we are done with development, we would like to point our Angular application to production server APIs.
I have seen many developers switching between development URLs and production URLs by commenting out one on other.
Ideally, Angular application shouldn’t require any code change to point to either development or production server HTTP URL. It should use relative HTTP URLs for consuming REST APIs and base URL which should be kept at only one place so that just by changing base URL, application should point to either development or production server.
environment.ts files comes into picture. In a Angular-Cli project, we get
environment folder with two files
This file exports a constant JSON object
environment. If you refer
environment object properties in your Angular project, during development mode i.e.
ng serve or
ng build all values shall be read from this file.
This file exports same JSON object and should have same properties as of
environment.ts file. When you build your application for production mode using
ng build --prod in that case, all values of
environment.ts file shall get overridden by
With above understanding, we can separate development and production HTTP URL using
- Put development HTTP Url inside
- Put production HTTP URL inside
- In rest of Angular application, refer
- In development mode, run
In our example,
baseUrl shall read value as if development URL:
- For production mode, run
ng build --prodcommand.
In our example,
baseUrl shall read value as if production URL:
This eases build process. Based on type of build, specific base URL shall be picked up by Angular-CLI and output
dist folder shall be generated.
Here is the complete source code of example referred in this article.