Angular doesn’t natively support loading environment variables from .env
files like some server-side environments or JavaScript build tools do (e.g., Node.js with dotenv
).
Here’s how you can set up environment variables in Angular:
- Create Environment Files:
Angular allows you to create different environment files for different environments (e.g.,environment.ts
for development andenvironment.prod.ts
for production). In your Angular project, navigate to thesrc/environments/
folder. You’ll find two default environment files:environment.ts
andenvironment.prod.ts
. You can add your environment-specific variables to these files. - Define Environment Variables:
Open theenvironment.ts
andenvironment.prod.ts
files and define your environment-specific variables as properties of theenvironment
object. For example:
// 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://your-production-api.com/api',
};
- Access Environment Variables:
In your Angular components or services, you can import theenvironment
object from the appropriate environment file and access the variables like this:
import { environment } from 'src/environments/environment';
// Access environment variables
console.log(environment.production); // For checking if it's production
console.log(environment.apiUrl); // Your API URL
- Build for Specific Environment:
When you build your Angular application, you can specify which environment configuration to use. For instance, to build for production, you can use the--prod
flag:
ng build --prod
This command will use the environment.prod.ts
file for configuration.
- Dynamic Configuration (Optional):
If you need to dynamically load configuration at runtime (e.g., from an.env
file), you would need to make an HTTP request or use other techniques to fetch the configuration and then assign it to your Angular variables programmatically. You can do this in your app’s initialization code, such as in theAppModule
.
Environment variables defined in an Angular application are exposed on the client-side.
Including sensitive information like API keys or secrets is a risk.
API keys or secrets should be managed on the server-side to ensure security.