Function Signature
.env files in the specified directory. NODE_ENV must be set in the environment and will not be picked up from the filesystem.
If NODE_ENV is not set, it defaults to development.
Parameters
Configuration options for loading environment variables.
Return Value
An object extending
NodeJS.ProcessEnv with all loaded environment variables, including a guaranteed NODE_ENV property.Loading Order
Environment variables are loaded in the following priority order (first to last):.env.${NODE_ENV}.local- Environment-specific local overrides.env.${NODE_ENV}- Environment-specific variables.env.local- Local overrides for all environments.env- Default environment variables
process.env variables take precedence, and finally NODE_ENV is set.
Error Handling
The function throws an error if:- No environment variables could be loaded from any
.envfile - All file reads failed (files don’t exist or are inaccessible)
cause property containing an array of all errors encountered during file reading.
Usage
Basic Usage
Custom Directory
With Type-Safe Accessors
Setting NODE_ENV
Example .env Files
.env
.env.development
.env.production
.env.local
Best Practices
-
Call Early: Call
loadEnv()at the very beginning of your application before accessing any environment variables. -
Don’t Commit Secrets: Add
.env.localand.env.*.localfiles to.gitignoreto avoid committing sensitive data. -
Set NODE_ENV: Always set
NODE_ENVin your environment before running your application, not in.envfiles. -
Use Type-Safe Accessors: Use the provided type-safe accessor functions (
envString,envInt, etc.) instead of directly accessingprocess.env. - Provide Defaults: Use default values for non-critical configuration to make your application more resilient.
