Skip to content

Environment Variables

Antony Budianto edited this page Jul 31, 2016 · 47 revisions

As a developer who works with many environments, like local machine, your teammate's machine, staging, QA, or production, you need to make sure that changing settings won't breaks other environments. The usual way is to have environment variables which varies between environments.

The usual use cases:

  • Staging server uses stag-api.domain.com where Production server uses api.domain.com
  • My local machine uses localhost where my teammate's machine uses api.domain.dev
  • PORT differences

The starter supports file-based and strong-typed environment variables

❔ How it works

It works by reading your env.json located at project root and transforming it into a TypeScript file that exports a const so you can import it into your application.

ℹ️ Getting started

  1. Define your app env interface in src/app/shared/constant/env.model.ts
  2. Create env.json file at project root and add your env key-value pairs there.
    • The key must matches the env interface defined in step 1, unless it's an optional key
  3. Now, every transpilation will generate a new src/app/shared/constant/env.ts and you can import it to your application
    • You also can generate it manually by running npm run env
  4. Access the env in CONSTANT.ENV from src/app/shared module

💡 Tips

  • You can directly update generated src/app/shared/constant/env.ts file for fast update and response in development. Of course you need to update env.json for permanent update
  • Bundling
    • It's up-to-you to commit production/staging/etc json files like env.production.json into source control OR to keep it somewhere in the server/machine. First choice is favorable when you have limited/no server access
    • Before bundling using npm run build, copy env.json from server/repo
  • When you update AppEnv interface, you can update env.example.json along so others can use as quick template for their environment

⚠️ Warning

  • Since this is client-side environment variables, DON'T STORE SENSITIVE INFORMATION like your api tokens, secret keys, or other variables that should be kept secret on server-side
  • This is why you can commit env.<environment>.json to source control since it should only contains non-sensitive environment values.

Environment variable feature is optional, you can do so by emptying the AppEnv interface so you don't need to have env.json at all

☀️ Support this starter by sharing it to your friends, giving stars, or pull requests! 😄

Clone this wiki locally