Overview
Load Env provides a robust system for loading environment variables from.env files with proper precedence handling and NODE_ENV support. The library follows common conventions while adding type safety and error handling.
The loadEnv Function
TheloadEnv() function is the entry point for loading environment variables from .env files:
With Custom Path
You can specify a custom directory for your.env files:
File Loading Order
Environment variables are loaded with a specific precedence order. Files loaded first take priority over files loaded later:.env.${NODE_ENV}.local
Environment-specific local overrides (e.g.,
.env.production.local)These files should be gitignored and used for local development overrides..env.${NODE_ENV}
Environment-specific variables (e.g.,
.env.production, .env.development)These files contain environment-specific configuration that can be committed to version control..env.local
Local overrides for all environmentsThis file should be gitignored and used for local development secrets.
Variables that already exist in
process.env will not be overwritten by values from .env files. This allows you to override values via command line or system environment variables.NODE_ENV Behavior
TheNODE_ENV environment variable controls which environment-specific files are loaded:
Default NODE_ENV
IfNODE_ENV is not set, it defaults to development:
How It Works
Here’s what happens when you callloadEnv():
View implementation details
View implementation details
The function:
- Reads
NODE_ENVfromprocess.env(defaults to"development") - Constructs file paths based on the loading order
- Reads all files in parallel using
Promise.all - Parses each file with Node.js’s built-in
parseEnvutility - Merges results with earlier files taking precedence
- Merges with existing
process.env(existing values win) - Sets
NODE_ENVexplicitly in the final result - Updates
process.envwith the merged values
Error Handling
The library is designed to be resilient:Missing Files
Missing.env files are not treated as errors. The library will continue loading other files:
No Files Found
If no environment variables can be loaded from any file, an error is thrown:The error includes a
cause property containing an array of all errors encountered while reading files, which is helpful for debugging.Common Patterns
Load Early in Application
CallloadEnv() as early as possible in your application:
Multiple Environments
Create different.env files for each environment:
Testing Configuration
Next Steps
Now that your environment variables are loaded, learn how to access them with type safety:Environment Variables
Learn about type-safe functions for accessing environment variables
