Node.js - Loading variables from dotenv .env file

by
Jeremy Canfield |
Updated: July 22 2024
| Node.js articles
Let's say you have the following files that make up your Node.js app.
├── .env
├── package.json
├── app.js
And let's say the .env file contains variables, perhaps something like this.
FOO="hello"
BAR="world"
The dotenv package is used to read variables from a .env file. Your package.json file will need to include the dotenv dependency.
{
"dependencies": {
"dotenv": "^16.0.3"
},
"type": "commonjs"
}
And then in your app.js file, here is how you could use dotenv in console.log. Notice in this example that package.json has "type": "commonjs". WIth CommonJS, you will use require.
require("dotenv").config()
console.log('The FOO variable contains a value of:', process.env.FOO);
console.log('The BAR variable contains a value of:', process.env.BAR);
Or better yet, create FOO and BAR constants.
require("dotenv").config()
const { FOO, BAR } = process.env;
console.log('The FOO variable contains a value of:', FOO);
console.log('The BAR variable contains a value of:', BAR);
If package.json had "type": "module" then app.js would have to use import (not require).
import "dotenv/config";
const { FOO, BAR } = process.env;
console.log('The FOO variable contains a value of:', FOO);
console.log('The BAR variable contains a value of:', BAR);
The console should contain something like this.
]$ node app.js
> NodeJS@1.0.0 start
The FOO variable contains a value of: hello
The BAR variable contains a value of: world
Did you find this article helpful?
If so, consider buying me a coffee over at