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 andindex.html - ✅
process.envandimport.meta.envsupport - ✅ Monorepo cascading for Nx and Turborepo
- ✅ Filters sensitive variables with a prefix / regular expression
Quick start
1. Add @ngx-env to your Angular project
ng add @ngx-env/builderThis 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
NG_APP_VERSION=$npm_package_versionNG_APP_API_URL=https://api.example.comNG_APP_ENABLE_SENTRY=false3. 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
npm startNG_APP_ENABLE_SENTRY=true npm run buildDefining variables
You can set NG_APP_* variables from the command line or from .env files.
NG_APP_BRANCH_NAME=$GITHUB_HEAD_REF ng build$env:NG_APP_BRANCH_NAME="main"; ng buildset "NG_APP_BRANCH_NAME=main" && ng build.env files are loaded with priorities, so you can layer environment-specific
values on top of shared defaults:
.env # committed defaults.env.local # local overrides (git-ignored).env.production # loaded for production builds.env.production.localSee 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:
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.
workspace├── .env # API_BASE shared by every app├── apps│ └── my-ng-app│ └── .env # NG_APP_* specific to this app└── nx.jsonRead 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.