Published at
Updated at
Reading time
1min
This post is part of my Today I learned series in which I share all my web development learnings.

Node.js continues to follow the lead of competing runtimes and implements more and more userland features. Loading .env files was one of these features that's been solved in userland (dotenv has 46m weekly downloads) since I started writing Node.js code almost 15 years ago.

Today I learned that Node.js not only added support for loading environment files from the command line with the --env-file and --env-file-if-exists flags, but also added a new loadEnvFile() method to load .env files right in your scripts, similar to how dotenv does it. The new method is marked stable since Node.js v24.

import { loadEnvFile } from 'node:process';

// load .env file with default path ('./.env')
loadEnvFile();
// load .env file with a custom path
loadEnvFile('../../.env');

One thing to watch out for, though, is that loadEnvFile() throws if the .env file doesn't exist, which is usually the case in production environments. But that's no problem, and I wrapped it into a small utility when I was removing dotenv from one of my projects.

import { loadEnvFile } from 'node:process';

export function safeLoadEnvFile(): void {
  try {
    loadEnvFile();
  } catch (error) {
    // In prod environments there's usually no `.env` file.
    // Ignore the error thrown if the file doesn't exist.
  }
}

I love seeing Node.js moving forward!

If you enjoyed this article...

Join 6.3k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles