TIL: Node --env-file Loads .env Without the dotenv Package
Run node --env-file=.env app.js and Node reads the file into process.env before your code runs. Added in Node 20.6.0. A variable already set in the shell wins over the file, and a later --env-file flag wins over an earlier one.
Node can read a .env file on its own now. The flag is --env-file, and it has been in Node since 20.6.0.
node --env-file=.env app.js
Node reads the file before your code runs and puts each line into process.env. Comments, quotes and values that span more than one line work the same way they do in the dotenv package. If a variable is already set in your shell, the shell value wins. Pass the flag twice and the second file wins over the first, so --env-file=.env --env-file=.env.local gives you a shared file and a local override.
I wrote about the dotenv package back in 2020. For most projects you can uninstall it and delete the require line.
What if the file is missing?
--env-file stops with an error when the file is not there. --env-file-if-exists, added in 22.9.0, carries on without it. Use that one in a Dockerfile where the .env only exists on your laptop.
Can I load it from code instead?
Yes. process.loadEnvFile(".env") does the same thing from inside a script, and the argument is optional when the file is called .env. It landed in 20.12.0.