Next.js dotenv file loading utility with proper environment priority and variable expansion
npx @tessl/cli install tessl/npm-next--env@15.5.0@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.
npm install @next/envimport { loadEnvConfig, processEnv, resetEnv, updateInitialEnv, initialEnv } from "@next/env";
import type { Env, LoadedEnvFiles } from "@next/env";For CommonJS:
const { loadEnvConfig, processEnv, resetEnv, updateInitialEnv, initialEnv } = require("@next/env");import { loadEnvConfig } from "@next/env";
// Load environment configuration for a project directory
const { combinedEnv, loadedEnvFiles } = loadEnvConfig(
process.cwd(), // Project directory
true, // Development mode
console, // Logger (optional)
false, // Force reload (optional)
(filePath) => console.log(`Reloaded: ${filePath}`) // Reload callback (optional)
);
// Environment variables are now available in process.env
console.log(process.env.DATABASE_URL);@next/env is built around several key concepts:
.env.development.local > .env.local > .env.development > .env)Main function for loading and processing environment files with proper priority and variable expansion.
/**
* Load environment configuration from dotenv files with proper priority
* @param dir - Directory to search for .env files
* @param dev - Optional boolean to indicate development mode
* @param log - Optional logger with info and error methods
* @param forceReload - Optional boolean to force reload cached files
* @param onReload - Optional callback called when an env file is reloaded
* @returns Object containing combined environment, parsed environment, and loaded files
*/
function loadEnvConfig(
dir: string,
dev?: boolean,
log?: Log,
forceReload?: boolean,
onReload?: (envFilePath: string) => void
): {
combinedEnv: Env;
parsedEnv: Env | undefined;
loadedEnvFiles: LoadedEnvFiles;
};Usage Example:
import { loadEnvConfig } from "@next/env";
// Basic usage - load for current directory in production mode
const config = loadEnvConfig(process.cwd());
// Development mode with custom logger
const devConfig = loadEnvConfig(
"./my-project",
true, // development mode
{
info: (msg) => console.log(`[INFO] ${msg}`),
error: (msg) => console.error(`[ERROR] ${msg}`)
}
);
// With reload detection
const configWithReload = loadEnvConfig(
process.cwd(),
true,
console,
false,
(filePath) => {
console.log(`Environment file ${filePath} was reloaded`);
// Perform any necessary reload logic here
}
);Low-level function for processing loaded environment files and applying them to process.env.
/**
* Process loaded environment files and apply them to process.env
* @param loadedEnvFiles - Array of loaded environment file objects
* @param dir - Optional directory path for error reporting
* @param log - Optional logger with info and error methods
* @param forceReload - Optional boolean to force reload
* @param onReload - Optional callback called when an env file is reloaded
* @returns Tuple of [combined environment, parsed environment (if processing occurred)]
*/
function processEnv(
loadedEnvFiles: LoadedEnvFiles,
dir?: string,
log?: Log,
forceReload?: boolean,
onReload?: (envFilePath: string) => void
): [Env, Env?];Resets process.env to its initial state before any modifications.
/**
* Reset process.env to its initial state
*/
function resetEnv(): void;Usage Example:
import { loadEnvConfig, resetEnv } from "@next/env";
// Load environment variables
loadEnvConfig(process.cwd(), true);
console.log(process.env.MY_CUSTOM_VAR); // Available
// Reset to initial state
resetEnv();
console.log(process.env.MY_CUSTOM_VAR); // undefined (if not in initial env)Updates the stored initial environment with new values.
/**
* Update the initial environment with new values
* @param newEnv - Environment object to merge with initial environment
*/
function updateInitialEnv(newEnv: Env): void;Usage Example:
import { updateInitialEnv } from "@next/env";
// Add variables to the initial environment
updateInitialEnv({
CUSTOM_INITIAL_VAR: "value",
ANOTHER_VAR: "another value"
});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.
/**
* Initial environment state (exported variable)
* Contains a snapshot of process.env before any modifications
*/
let initialEnv: Env | undefined;Usage Example:
import { initialEnv } from "@next/env";
// Access the original process.env state
const originalNodeEnv = initialEnv?.NODE_ENV;
// Use as fallback environment for child processes
const defaultEnv = initialEnv || process.env;/**
* Environment variables as key-value pairs
*/
type Env = { [key: string]: string | undefined };
/**
* Array of loaded environment files with metadata
*/
type LoadedEnvFiles = Array<{
path: string; // Relative path to the env file
contents: string; // Raw file contents
env: Env; // Parsed environment variables from this file
}>;
/**
* Logger interface for info and error messages
*/
interface Log {
info: (...args: any[]) => void;
error: (...args: any[]) => void;
}@next/env loads environment files in the following priority order (highest to lowest):
.env.{mode}.local - Environment-specific local overrides.env.local - Local overrides (not loaded in test mode).env.{mode} - Environment-specific defaults.env - Default environment variablesWhere {mode} is determined as:
test when NODE_ENV === 'test'development when dev parameter is trueproduction otherwise@next/env supports variable expansion using dotenv-expand syntax:
# .env file
API_URL=https://api.example.com
API_VERSION=v1
FULL_API_URL=${API_URL}/${API_VERSION}The library safely manages process.env by:
__NEXT_PRIVATE)