How to configure Angular environment variables
Managing environment-specific configuration is essential for Angular applications deployed across development, staging, and production environments. As the creator of CoreUI with over 11 years of Angular development experience since 2014, I’ve configured countless enterprise applications for multiple environments. The most effective solution is to use Angular’s environment files to store configuration variables that change between environments. This approach keeps sensitive data out of your codebase and makes deployment straightforward.
Use environment files to configure environment-specific variables in Angular.
// src/environments/environment.ts (development)
export const environment = {
production: false,
apiUrl: 'http://localhost:3000/api',
apiKey: 'dev-key-12345'
}
// src/environments/environment.prod.ts (production)
export const environment = {
production: true,
apiUrl: 'https://api.example.com',
apiKey: 'prod-key-67890'
}
// src/app/services/api.service.ts
import { environment } from '../environments/environment'
export class ApiService {
private apiUrl = environment.apiUrl
getData() {
return this.http.get(`${this.apiUrl}/data`)
}
}
Environment files export a configuration object with environment-specific values. Angular automatically uses the correct file based on the build configuration. The angular.json file maps configurations to environment files. When you build for production with ng build --configuration production, Angular replaces imports from environment.ts with environment.prod.ts. This file replacement happens at build time, ensuring only the relevant configuration is included in the bundle.
Best Practice Note
This is the same environment configuration we use in CoreUI Angular projects for managing API endpoints and feature flags. Never commit sensitive credentials to environment files in version control. For truly sensitive data, use environment variables or secret management services and inject them during the build process.



