Use .env variables in Node.js
11 May 2022 (Updated 11 May 2022)
Install dotenv package
npm i dotenv
Create env files
Create a .env.example file in the root of your project and commit this to Git. This will serve as a template for the .env file.
FOO=
BAR=
Create a .env in the root of your project and make sure you don’t include it in Git (add .env to your .gitignore file):
FOO=foo
BAR=bar
Load env file
You have two options for loading your .env file.
1. Preload
$ node -r dotenv/config your_main_script.js
2. Load in application code
As early as possible in your application, import and configure dotenv:
require('dotenv').config();
console.log(process.env.FOO)'
Sources
Tagged:
Node.js tooling
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment