Simplify Node.js Configuration with .env Files

There's more to the new .env support than I noticed originally.

Since the release of Node.js 20.6.0, there has been native support for .env files. I didn't notice that we can now add our runtime options to this file. Here's how:

The Old Way

Traditionally, when we wanted to run a Node.js application with specific runtime options, we'd do something like this:

node --max-old-space-size=4096 --trace-warnings --experimental-fetch app.js

Or, we might create a script in our package.json:

{
  "scripts": {
    "start": "node --max-old-space-size=4096 --trace-warnings --experimental-fetch app.js"
  }
}

This approach works, but it can lead to long, unwieldy commands and cluttered script definitions.

The New Way

I recently discovered that runtime options support directly from your .env file.

Create a .env file in our project root and add NODE_OPTIONS alongside your existing options:

NODE_OPTIONS="--max-old-space-size=4096 --trace-warnings"
API_KEY="your-secret-api-key"

And run our application like this:

node --env-file=.env app.js

That's it!

Node.js will automatically apply the options specified in NODE_OPTIONS and make any other variables (like API_KEY) available in process.env.

Allowing developers to specify command-line options in a .env really cleans things up! 🧽

Nodejs
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.