TIL: You don't need dotenv in latest version of Node
Starting from Node v20.6.0, you don't need dotenv package to load the environment variables within process.env scope as Node now natively support loading the environment variables from default .env file or custom .env files such as .env.development or others.
There are two ways, you can use this feature.
1. Pass .env to the script as CLI flag: Consider the example where you've following two scripts in your package.json file.
"dev": "nodemon app.js", "start": "node app.js"
Then you can pass the .env file to the app.js script as value of --env-file CLI flag.
"dev": "nodemon --env-file=.env app.js", "start": "node --env-file=.env app.js"
Or you can pass different .env file based on the environment.
"dev": "nodemon --env-file=.env.development app.js", "start": "node --env-file=.env app.js"
2. Load within code using loadEnvFile(): Function loadEnvFile() is available within process module that we can import and optionally pass the .env file name to the function.
const process = require("process") // Loads the default .env file in current directoy. process.loadEnvFile() // OR pass a custom path process.loadEnvFile("./config/.env")
Now, you can use environment variables within process.env scope from the given environment file.