Skip to content

Angular environment variables with @ngx-env/builder

@ngx-env/builder is the most popular way to use environment variables in Angular. It reads .env files and injects the variables into your app at build time — no process polyfill, no custom Webpack config.

  • ✅ The official recommendation in the dotenv docs
  • ✅ Works with the modern application / esbuild builder and Webpack
  • NG_APP_* variables in TypeScript, templates and index.html
  • process.env and import.meta.env support
  • ✅ Monorepo cascading for Nx and Turborepo
  • ✅ Filters sensitive variables with a prefix / regular expression

Quick start

1. Add @ngx-env to your Angular project

Terminal window
ng add @ngx-env/builder

This updates your angular.json to use the @ngx-env/builder builders. If you still build with Webpack, use the application@ngx-env/builder:application mapping that ng add sets up for you.

2. Define environment variables in a .env file

.env
NG_APP_VERSION=$npm_package_version
NG_APP_API_URL=https://api.example.com
NG_APP_ENABLE_SENTRY=false

3. Use the variables in TypeScript

@Component({
selector: 'app-footer',
template: `{{ version }} — {{ commit }}`,
})
export class FooterComponent {
version = import.meta.env.NG_APP_VERSION; // recommended
commit = process.env.NG_APP_COMMIT; // also supported
}

4. …and in index.html

<head>
<title>My App %NG_APP_VERSION%</title>
</head>

5. Run your usual Angular commands

Terminal window
npm start
NG_APP_ENABLE_SENTRY=true npm run build

Defining variables

You can set NG_APP_* variables from the command line or from .env files.

Terminal window
NG_APP_BRANCH_NAME=$GITHUB_HEAD_REF ng build

.env files are loaded with priorities, so you can layer environment-specific values on top of shared defaults:

Terminal window
.env # committed defaults
.env.local # local overrides (git-ignored)
.env.production # loaded for production builds
.env.production.local

See loading priorities for the full order.

TypeScript autocompletion

ng add generates a src/env.d.ts file. Declare your variables there to get autocompletion and type-checking on import.meta.env:

src/env.d.ts
declare interface ImportMetaEnv {
readonly NG_APP_VERSION: string;
readonly NG_APP_API_URL: string;
}

Monorepo support ✨

In an Nx or Turborepo workspace, .env files cascade from the workspace root down to each application, so shared configuration lives in one place and each app can override it.

Terminal window
workspace
├── .env # API_BASE shared by every app
├── apps
└── my-ng-app
└── .env # NG_APP_* specific to this app
└── nx.json

Read the Monorepo Setup guide for details.

Try it online

Learn more

The full README — runtime variables, Docker, custom builders and known issues — lives in the package repository.