Menu

1 / 2

Read environment variables from .env file in Angular

DEV Community: angular·Mirza Leka·5 months ago
#fTlOfY1u
#dev#environment#file#angular#article
Reading 0:00
15s threshold

This article will teach you how to read environment variables from .env files into multiple Angular environments.

What is the .env file?

The .env file is a plain-text file used to store sensitive data and environment-specific configuration for a software application. Sample file:

GREETING = HELLO WORLD SECRET = 12345

Enter fullscreen mode

Exit fullscreen mode

By default, Angular uses the Environment files built into the framework (under src/environments ), which are good for runtime but are publicly visible (and thus expose environment secrets). To get around this, we'll create a .env file for each environment (dev, staging, production) and load those variables into the Angular env file.

How are we going to implement this?

Create an .env file for each environment

Create a Node.js script that loads those .env files into memory

Use the script to override Angular environment project files with values from the .env files

Run the Angular build

This solution adds environment variables to the project…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.