Skip to content

Instantly share code, notes, and snippets.

@kamauwashington
Last active September 4, 2022 23:31
Show Gist options
  • Save kamauwashington/fd3a19ae3d65fc3ab20d88e13aff962c to your computer and use it in GitHub Desktop.
Save kamauwashington/fd3a19ae3d65fc3ab20d88e13aff962c to your computer and use it in GitHub Desktop.

TypeScript Bits

Preload dotenv, don't require it

TypeScript Bits are small, easily digestible pieces of information to encourage TypeScript/JavaScript best practices. From beginner, to intermediate, to ninja, these bits are for you 😄


Estimated reading time : 2 minutes

Oh my dotenv! If you work with NodeJS at some point you will use and implement dotenv. It loads environment variables from a .env file (configurable name btw), into process.env, following the 12 Factor App methodology of separating environment from code. Pure awesomeness, and makes development configuration loading a breeze mimicking your higher environments.

An important note. Do not use .env in production! Your environments be them containers, RHEL, Cloud, CentOS, Windows Server are responsible for and capable of providing environment variables without dotenv.

Given the above, one should also avoid bundling dotenv as a dependency, exclude configuration in the codebase, and consider dotenv a developer workstation tool only.

Avoid

dotenv documentation states "As early as possible in your application, require and configure dotenv.". To avoid loading in higher environments, most perform the following check :

if (process.env.node_env == 'development') require('dotenv').config() //this should not be in your code

Better

Preload dotenv in your start script, by installing dotenv as a development dependency npm install --save-dev dotenv and using Node's built in -r flag to preload the configuration module from dotenv, you no longer have to _require('dotenv').config() in your code!

$ node -r dotenv/config your_script.js

But I use ts-node!!!

Node's -r flag applies to ts-node as well!

ts-node -r dotenv/config your_script.ts

Notes

  • It is still possible to use the dotenv_config_path argument using the preload method, for custom file name and path
  • this should be placed in your npm scripts section in start or even better start-dev
    • important note, avoid using npm start in production (though Heroku and similar services do for simplicity and workflow), best practice is to use the NodeJS binary instead of the package manager like so node my-app.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment