Built-in .env Support in Node.js v20.6.0

It's always nice to peel dependencies out of projects.

dotenv has been a staple for managing our .env files in our Node applications.

But soon, it'll no longer be needed since with Node.js v20.6.0, we get support for .env files out of the box.

That's all thanks to adding the new --env-file flag.

Usage with Built-in .env Support

  1. In the root of your project, create a .env file. Note: You can name this whatever you like, but .env is a typical convention.

  2. Run your Node.js application and pass the env file to the --env-file flag in the CLI command:

node --env-file .env index.js

Example

Create our .env file with the environment variables:

TOP_SECRET_PASSWORD=POOP1234

Then our Node script in index.js:

console.log(process.env.TOP_SECRET_PASSWORD);

And then run the following:

node -v

And make sure your Node version is higher than 20.6.0, then run:

node --env-file .env index.js

Which will result in a log of POOP1234 in our terminal.

Bonus 🚀

There is another bonus to using this flag.

You can also define your Node CLI options directly in the .env file rather than in your command:

# .env
NODE_OPTIONS="--inspect --max-old-space-size=4096"

It will automatically apply those options when you run using this .env.

Happy coding! ⚡️

NodejsJS
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.