CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-next--env

Next.js dotenv file loading utility with proper environment priority and variable expansion

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

@next/env

@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.

Package Information

  • Package Name: @next/env
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @next/env

Core Imports

import { 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");

Basic Usage

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);

Architecture

@next/env is built around several key concepts:

  • File Priority System: Loads multiple .env files with proper precedence (.env.development.local > .env.local > .env.development > .env)
  • Environment Mode Detection: Automatically determines loading behavior based on NODE_ENV and development flags
  • Variable Expansion: Uses dotenv-expand for variable substitution within environment files
  • Process Environment Management: Safely manages process.env with backup and restore capabilities
  • Caching Layer: Optimizes performance by caching loaded files and avoiding redundant reads

Capabilities

Environment Configuration Loading

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
  }
);

Environment Processing

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?];

Environment Reset

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)

Initial Environment Update

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"
});

Initial Environment Access

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;

Types

/**
 * 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;
}

Environment File Priority

@next/env loads environment files in the following priority order (highest to lowest):

  1. .env.{mode}.local - Environment-specific local overrides
  2. .env.local - Local overrides (not loaded in test mode)
  3. .env.{mode} - Environment-specific defaults
  4. .env - Default environment variables

Where {mode} is determined as:

  • test when NODE_ENV === 'test'
  • development when dev parameter is true
  • production otherwise

Advanced Features

Variable Expansion

@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}

Process Environment Management

The library safely manages process.env by:

  • Preserving the initial state for reset functionality
  • Protecting Next.js internal variables (starting with __NEXT_PRIVATE)
  • Providing clean restoration of the original environment

Caching and Performance

  • Caches loaded environment files to avoid redundant file system operations
  • Tracks file changes for reload detection
  • Only processes environment variables when necessary

Error Handling

  • Gracefully handles missing environment files (ENOENT errors are ignored)
  • Logs errors for file read failures while continuing processing
  • Provides detailed error context including file paths

docs

index.md

tile.json