DEV Community 👩‍💻👨‍💻

Cover image for Announcing @ngx-env/builder
Chihab Otmani
Chihab Otmani

Posted on • Updated on

Announcing @ngx-env/builder

Have you ever wanted to consume variables declared in your environment inside your Angular application?

# GitHub Action command
NG_APP_GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }} ng build
Enter fullscreen mode Exit fullscreen mode

Environment variables can be useful for:

  • displaying information conditionally based on where the project is deployed
  • consuming data (potentially sensitive) that lives outside of version control


With @ngx-env/builder the environment variables will be defined for you on process.env, just like in Node.js applications.

For example, having an environment variable named NG_APP_API_BASE_URL will be exposed in your TS/JS as process.env.NG_APP_API_BASE_URL.

The environment variables are embedded during the build time.

Add @ngx-env to your CLI project

ng add @ngx-env/builder
Enter fullscreen mode Exit fullscreen mode

Define Environment Variables in .env

Enter fullscreen mode Exit fullscreen mode

Use in TS and HTML

  selector: "app-footer",
export class FooterComponent {
  version = process.env.NG_APP_VERSION;
  branch = process.env.NG_APP_BRANCH_NAME;
  token = process.env.NG_APP_GITHUB_TOKEN;
Enter fullscreen mode Exit fullscreen mode
<!-- Same output -->
<span> {{ 'process.env.NG_APP_BRANCH_NAME' | env }} </span>
<span> {{ 'NG_APP_BRANCH_NAME' | env }} </span>
<span> {{ branch }} </span>
Enter fullscreen mode Exit fullscreen mode
<!-- index.html -->
  <title>NgApp on %NG_APP_BRANCH_NAME%</title>
Enter fullscreen mode Exit fullscreen mode

Run your CLI commands

npm start
# Command Line environment variable
NG_APP_BRANCH_NAME=`git branch --show-current` NG_APP_GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }} npm run build
Enter fullscreen mode Exit fullscreen mode

Variables defined in .env file or in the command line are injected into your Angular Application.


Top comments (2)

mmannefeld profile image
Michael Mannefeld

interesting approach, thank you very much.
I only had to use a different notation for Angular 13 because the compiler was complaining:
version = process.env['NG_APP_VERSION'];
instead of
version = process.env.NG_APP_VERSION;
Then it worked fine.

And i think, it would be worth mentioning that the variables need to start with 'NG_APP', as you did in your article (

spock123 profile image
Lars Rye Jeppesen

Great stuff, thanks

We are hiring! Do you want to be our Senior Platform Engineer? Are you capable of chipping in across sysadmin, ops, and site reliability work, while supporting the open source stack that runs DEV and other communities?

This role might just be for you!

Apply now