Next.js dotenv file loading utility with proper environment priority and variable expansion
npx @tessl/cli install tessl/npm-next--env@15.5.00
# @next/env
1
2
@next/env is a specialized dotenv file loading utility designed specifically for Next.js applications. It provides sophisticated environment variable management with proper file priority ordering, variable expansion, and development/production environment handling.
3
4
## Package Information
5
6
- **Package Name**: @next/env
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @next/env`
10
11
## Core Imports
12
13
```typescript
14
import { loadEnvConfig, processEnv, resetEnv, updateInitialEnv, initialEnv } from "@next/env";
15
import type { Env, LoadedEnvFiles } from "@next/env";
16
```
17
18
For CommonJS:
19
20
```javascript
21
const { loadEnvConfig, processEnv, resetEnv, updateInitialEnv, initialEnv } = require("@next/env");
22
```
23
24
## Basic Usage
25
26
```typescript
27
import { loadEnvConfig } from "@next/env";
28
29
// Load environment configuration for a project directory
30
const { combinedEnv, loadedEnvFiles } = loadEnvConfig(
31
process.cwd(), // Project directory
32
true, // Development mode
33
console, // Logger (optional)
34
false, // Force reload (optional)
35
(filePath) => console.log(`Reloaded: ${filePath}`) // Reload callback (optional)
36
);
37
38
// Environment variables are now available in process.env
39
console.log(process.env.DATABASE_URL);
40
```
41
42
## Architecture
43
44
@next/env is built around several key concepts:
45
46
- **File Priority System**: Loads multiple .env files with proper precedence (`.env.development.local` > `.env.local` > `.env.development` > `.env`)
47
- **Environment Mode Detection**: Automatically determines loading behavior based on NODE_ENV and development flags
48
- **Variable Expansion**: Uses dotenv-expand for variable substitution within environment files
49
- **Process Environment Management**: Safely manages process.env with backup and restore capabilities
50
- **Caching Layer**: Optimizes performance by caching loaded files and avoiding redundant reads
51
52
## Capabilities
53
54
### Environment Configuration Loading
55
56
Main function for loading and processing environment files with proper priority and variable expansion.
57
58
```typescript { .api }
59
/**
60
* Load environment configuration from dotenv files with proper priority
61
* @param dir - Directory to search for .env files
62
* @param dev - Optional boolean to indicate development mode
63
* @param log - Optional logger with info and error methods
64
* @param forceReload - Optional boolean to force reload cached files
65
* @param onReload - Optional callback called when an env file is reloaded
66
* @returns Object containing combined environment, parsed environment, and loaded files
67
*/
68
function loadEnvConfig(
69
dir: string,
70
dev?: boolean,
71
log?: Log,
72
forceReload?: boolean,
73
onReload?: (envFilePath: string) => void
74
): {
75
combinedEnv: Env;
76
parsedEnv: Env | undefined;
77
loadedEnvFiles: LoadedEnvFiles;
78
};
79
```
80
81
**Usage Example:**
82
83
```typescript
84
import { loadEnvConfig } from "@next/env";
85
86
// Basic usage - load for current directory in production mode
87
const config = loadEnvConfig(process.cwd());
88
89
// Development mode with custom logger
90
const devConfig = loadEnvConfig(
91
"./my-project",
92
true, // development mode
93
{
94
info: (msg) => console.log(`[INFO] ${msg}`),
95
error: (msg) => console.error(`[ERROR] ${msg}`)
96
}
97
);
98
99
// With reload detection
100
const configWithReload = loadEnvConfig(
101
process.cwd(),
102
true,
103
console,
104
false,
105
(filePath) => {
106
console.log(`Environment file ${filePath} was reloaded`);
107
// Perform any necessary reload logic here
108
}
109
);
110
```
111
112
### Environment Processing
113
114
Low-level function for processing loaded environment files and applying them to process.env.
115
116
```typescript { .api }
117
/**
118
* Process loaded environment files and apply them to process.env
119
* @param loadedEnvFiles - Array of loaded environment file objects
120
* @param dir - Optional directory path for error reporting
121
* @param log - Optional logger with info and error methods
122
* @param forceReload - Optional boolean to force reload
123
* @param onReload - Optional callback called when an env file is reloaded
124
* @returns Tuple of [combined environment, parsed environment (if processing occurred)]
125
*/
126
function processEnv(
127
loadedEnvFiles: LoadedEnvFiles,
128
dir?: string,
129
log?: Log,
130
forceReload?: boolean,
131
onReload?: (envFilePath: string) => void
132
): [Env, Env?];
133
```
134
135
### Environment Reset
136
137
Resets process.env to its initial state before any modifications.
138
139
```typescript { .api }
140
/**
141
* Reset process.env to its initial state
142
*/
143
function resetEnv(): void;
144
```
145
146
**Usage Example:**
147
148
```typescript
149
import { loadEnvConfig, resetEnv } from "@next/env";
150
151
// Load environment variables
152
loadEnvConfig(process.cwd(), true);
153
console.log(process.env.MY_CUSTOM_VAR); // Available
154
155
// Reset to initial state
156
resetEnv();
157
console.log(process.env.MY_CUSTOM_VAR); // undefined (if not in initial env)
158
```
159
160
### Initial Environment Update
161
162
Updates the stored initial environment with new values.
163
164
```typescript { .api }
165
/**
166
* Update the initial environment with new values
167
* @param newEnv - Environment object to merge with initial environment
168
*/
169
function updateInitialEnv(newEnv: Env): void;
170
```
171
172
**Usage Example:**
173
174
```typescript
175
import { updateInitialEnv } from "@next/env";
176
177
// Add variables to the initial environment
178
updateInitialEnv({
179
CUSTOM_INITIAL_VAR: "value",
180
ANOTHER_VAR: "another value"
181
});
182
```
183
184
### Initial Environment Access
185
186
Direct access to the initial environment state before any modifications. This is primarily used internally by Next.js but can be useful for advanced environment management scenarios.
187
188
```typescript { .api }
189
/**
190
* Initial environment state (exported variable)
191
* Contains a snapshot of process.env before any modifications
192
*/
193
let initialEnv: Env | undefined;
194
```
195
196
**Usage Example:**
197
198
```typescript
199
import { initialEnv } from "@next/env";
200
201
// Access the original process.env state
202
const originalNodeEnv = initialEnv?.NODE_ENV;
203
204
// Use as fallback environment for child processes
205
const defaultEnv = initialEnv || process.env;
206
```
207
208
## Types
209
210
```typescript { .api }
211
/**
212
* Environment variables as key-value pairs
213
*/
214
type Env = { [key: string]: string | undefined };
215
216
/**
217
* Array of loaded environment files with metadata
218
*/
219
type LoadedEnvFiles = Array<{
220
path: string; // Relative path to the env file
221
contents: string; // Raw file contents
222
env: Env; // Parsed environment variables from this file
223
}>;
224
225
/**
226
* Logger interface for info and error messages
227
*/
228
interface Log {
229
info: (...args: any[]) => void;
230
error: (...args: any[]) => void;
231
}
232
```
233
234
## Environment File Priority
235
236
@next/env loads environment files in the following priority order (highest to lowest):
237
238
1. `.env.{mode}.local` - Environment-specific local overrides
239
2. `.env.local` - Local overrides (not loaded in test mode)
240
3. `.env.{mode}` - Environment-specific defaults
241
4. `.env` - Default environment variables
242
243
Where `{mode}` is determined as:
244
- `test` when `NODE_ENV === 'test'`
245
- `development` when `dev` parameter is `true`
246
- `production` otherwise
247
248
## Advanced Features
249
250
### Variable Expansion
251
252
@next/env supports variable expansion using dotenv-expand syntax:
253
254
```bash
255
# .env file
256
API_URL=https://api.example.com
257
API_VERSION=v1
258
FULL_API_URL=${API_URL}/${API_VERSION}
259
```
260
261
### Process Environment Management
262
263
The library safely manages process.env by:
264
- Preserving the initial state for reset functionality
265
- Protecting Next.js internal variables (starting with `__NEXT_PRIVATE`)
266
- Providing clean restoration of the original environment
267
268
### Caching and Performance
269
270
- Caches loaded environment files to avoid redundant file system operations
271
- Tracks file changes for reload detection
272
- Only processes environment variables when necessary
273
274
### Error Handling
275
276
- Gracefully handles missing environment files (ENOENT errors are ignored)
277
- Logs errors for file read failures while continuing processing
278
- Provides detailed error context including file paths