Skip to content

Environment Variables

Antony Budianto edited this page Aug 6, 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 app's config won't breaks other environments. The usual way is to have environment variables which varies between environments.

It's one of The Twelve-Factor App and I tried to adapt it as much as possible since some aren't applicable for client-side app.

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.

⭐ Advantages

  • Independently managed by each environment, resulting Scalable environment config (No file that groups every environments)
  • Using JSON file as it's language-independent data format
  • Strong-typed environment variables

ℹ️ Getting started

  1. Define your app's config at AppEnv interface
  2. Create env.json file at project root and add your env key-value pairs there.
    • The key must matches the AppEnv 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.

AppEnv interface is optional, you can have weak/dynamic types instead. But it's recommended to have the interface so that we know what env vars used by app, and what're to be supplied to env.json

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

Clone this wiki locally