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.
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
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
Node's -r flag applies to ts-node as well!
ts-node -r dotenv/config your_script.ts
- 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