ยท best practices

You Don't Need dotenv Anymore

Node.js now has built-in support for loading environment variables from .env files. Learn how to use the native loadEnvFile function and ditch the dotenv dependency for good.

For years, dotenv has been the standard for loading environment variables from .env files. But Node.js v20.6.0 introduced native support, eliminating the need for this dependency.

You can now use the loadEnvFile function from node:process or the --env-file CLI flag. Here's how to make the switch.

Contents

The dotenv Approach

The "dotenv" package required installing a dependency, importing it, and calling its config method:

.env
DATABASE_URL=postgresql://localhost/mydb
main.ts
import dotenv from 'dotenv';
 
dotenv.config();
 
console.log(process.env.DATABASE_URL);

This worked fine but added an external dependency that needed maintenance and updates.

The Node.js Solution

Node.js provides two ways to load .env files without external dependencies.

Using the CLI Flag

Use the --env-file flag when running your application:

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

You can specify multiple files, with later files overriding earlier ones:

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

Using loadEnvFile

Import and call loadEnvFile for more control:

main.ts
import { loadEnvFile } from 'node:process';
 
loadEnvFile();
 
console.log(process.env.DATABASE_URL);

Specify a custom path if needed:

main.ts
import { loadEnvFile } from 'node:process';
 
loadEnvFile('.env.production');
 
console.log(process.env.DATABASE_URL);

Enhancing with dotenv-defaults

While Node.js's native loadEnvFile works great, you can enhance it with dotenv-defaults for a better developer experience. This package lets you create a .env.defaults file containing sensible default values that work out of the box.

Developers only need to override specific values in their local .env file rather than configuring every single variable. The defaults file can be committed to version control, providing a solid foundation that everyone relies on.

Using dotenv-defaults

Install it alongside the native solution:

npm install dotenv-defaults
.env.defaults
# Committed to git - safe defaults for development
DATABASE_URL=postgresql://localhost:5432/myapp_dev
API_URL=http://localhost:3000
PORT=3000
LOG_LEVEL=info
CACHE_TTL=3600
.env
# In .gitignore - only override what you need
DATABASE_URL=postgresql://localhost:5432/my_custom_db
API_KEY=my-secret-key
main.ts
import 'dotenv-defaults/config';
 
console.log(process.env.DATABASE_URL);

With this setup, developers can start working immediately with sensible defaults. They only configure the few variables they need to change, like database connection strings or API keys specific to their environment.

Back to Blog