How to Set Environment Variables in Angular Projects
In Angular, set environment variables by adding them to
src/environments/environment.ts and environment.prod.ts files. Access these variables in your code by importing environment from src/environments/environment.Syntax
Angular uses separate environment files for different build targets. Each file exports an environment object with key-value pairs for variables.
Example files:
environment.tsfor developmentenvironment.prod.tsfor production
Import the environment object in your TypeScript files to use the variables.
typescript
export const environment = { production: false, apiUrl: 'http://localhost:3000/api' };
Example
This example shows how to define an API URL in environment files and use it in a service.
typescript
// src/environments/environment.ts export const environment = { production: false, apiUrl: 'http://localhost:3000/api' }; // src/environments/environment.prod.ts export const environment = { production: true, apiUrl: 'https://api.example.com' }; // src/app/api.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment } from '../environments/environment'; @Injectable({ providedIn: 'root' }) export class ApiService { private baseUrl = environment.apiUrl; constructor(private http: HttpClient) {} getData() { return this.http.get(`${this.baseUrl}/data`); } }
Output
When running in development, API calls go to http://localhost:3000/api/data; in production, calls go to https://api.example.com/data
Common Pitfalls
- Forgetting to import the
environmentobject from the correct path (src/environments/environment). - Not rebuilding the project after changing environment files, so changes don’t apply.
- Trying to access environment variables directly from
process.envlike in Node.js; Angular does not support this. - Not configuring
angular.jsonfile'sfileReplacementsto swap environment files for production builds.
typescript
// Wrong: Trying to use process.env in Angular console.log(process.env.API_URL); // undefined // Right: Import environment object import { environment } from '../environments/environment'; console.log(environment.apiUrl);
Quick Reference
Summary tips for environment variables in Angular:
- Define variables in
src/environments/environment.tsandenvironment.prod.ts. - Use
angular.jsonto replace files on build. - Import
environmentobject to access variables. - Rebuild app after changes to environment files.
Key Takeaways
Define environment variables in separate files under src/environments for different builds.
Import the environment object to access variables in your Angular code.
Configure angular.json to replace environment files during production builds.
Do not use Node.js style process.env in Angular; it won't work.
Always rebuild your Angular app after changing environment files.