Automatically load .env files in Node.js scripts
- Published at
- Updated at
- Reading time
- 1min
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!
Join 6.3k readers and learn something new every week with Web Weekly.
