npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@de44/dotenv

v0.1.0

Published

A TypeScript-first environment variable loader with Zod schema validation and multi-line string support

Readme

@de44/dotenv

A TypeScript-first environment variable loader with Zod schema validation, multi-line string support, and automatic value coercion.

🚀 Why This Library?

Unlike the standard dotenv package, this library provides:

  • 🔒 Type Safety: Validate your environment variables with Zod schemas
  • 📝 Multi-line Strings: Support for complex JSON configs and markdown content
  • 🎯 TypeScript First: Built with TypeScript and full type inference
  • ⚡ Minimal Dependencies: Only depends on Zod for validation and lodash for utilities
  • 🛡️ Runtime Safety: Catch configuration errors before your app starts
  • 🔄 Value Coercion: Automatic conversion of strings to appropriate types (JSON, boolean, number, null)
  • 📁 Profile Support: Load environment-specific configurations using the PROFILES environment variable

📦 Installation

npm install @de44/dotenv zod lodash

🎯 Quick Start

Basic Usage

import { Dotenv } from "@de44/dotenv";
import { z } from "zod";

// Define your environment schema
const schema = z.object({
  DATABASE_URL: z.string().url(),
  PORT: z.string().transform(Number),
  NODE_ENV: z.enum(["development", "production"]),
  API_KEY: z.string().min(1),
});

// Load and validate environment variables
const config = await Dotenv.load({
  filepaths: [".env", ".env.local"],
  schema,
});

console.log(config);
// {
//   DATABASE_URL: 'postgresql://user:pass@localhost:5432/db',
//   PORT: 3000,
//   NODE_ENV: 'development',
//   API_KEY: 'your-api-key'
// }

Multi-line String Support

This library supports complex multi-line strings for JSON configs, markdown content, and more using triple double quotes ("""):

# .env
DATABASE_URL=postgresql://user:pass@localhost:5432/db
PORT=3000
NODE_ENV=development

# Multi-line JSON configuration
API_CONFIG="""
{
  "baseUrl": "https://api.example.com",
  "timeout": 5000,
  "retries": 3
}
"""

# Multi-line markdown content
WELCOME_MESSAGE="""
# Welcome to Our App
This is a **markdown** message with:
- Bullet points
- "Quoted text"
- And more content
"""

Environment Profiles

Load different configurations using the PROFILES environment variable:

// Set PROFILES=dev,test,prod to load .env.dev, .env.test, .env.prod
process.env.PROFILES = "dev,test,prod";

const config = await Dotenv.load({
  filepaths: [".env"], // Base file
  schema,
});
// This will automatically load .env.dev, .env.test, .env.prod in order
// Later profiles override earlier ones

Advanced Configuration

import { Dotenv } from "@de44/dotenv";
import { z } from "zod";

const schema = z.object({
  DATABASE_URL: z.string().url(),
  PORT: z.string().transform(Number),
  NODE_ENV: z.enum(["development", "production"]),
  API_CONFIG: z.string().transform((val) => JSON.parse(val)),
  LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]),
});

// Custom logger
const logger = {
  info: (message: string, ctx?: Record<string, unknown>) => console.log(`[INFO] ${message}`, ctx),
  error: (message: string, ctx?: Record<string, unknown>) => console.error(`[ERROR] ${message}`, ctx),
};

const config = await Dotenv.load({
  filepaths: [".env", ".env.local"],
  schema,
  logger,
  coerceValues: true, // Enable automatic value coercion
});

🔧 API Reference

Dotenv.load<T>(options: LoadOptions<T>): Promise<T>

Load and validate environment variables.

Options:

  • filepaths?: string[] - Array of .env file paths to load
  • schema: z.ZodSchema<T> - Zod schema for validation
  • logger?: DotenvLogger - Optional custom logger
  • coerceValues?: boolean - Enable automatic value coercion (default: false)

Returns: Validated configuration object

Dotenv.configure(options: ConfigOptions): Promise<Dotenv>

Configure and initialize the Dotenv instance.

Options:

  • filepaths?: string[] - Array of .env file paths to load
  • schema?: z.ZodSchema - Optional Zod schema for validation
  • logger?: DotenvLogger - Optional custom logger
  • coerceValues?: boolean - Enable automatic value coercion (default: false)

Returns: Dotenv instance

dotenv.get<T>(schema: z.ZodSchema<T>): T

Get validated environment variables from an existing Dotenv instance.

🔄 Value Coercion

When coerceValues: true is enabled, the library automatically converts string values to appropriate types:

# .env
DATABASE_URL=postgresql://user:pass@localhost:5432/db
PORT=3000
DEBUG=true
API_TIMEOUT=5000
RETRY_COUNT=3
CACHE_TTL=null
API_CONFIG={"baseUrl": "https://api.example.com", "timeout": 5000}
const config = await Dotenv.load({
  filepaths: [".env"],
  schema,
  coerceValues: true,
});

// Values are automatically coerced:
// - Numbers: "3000" → 3000
// - Booleans: "true" → true, "false" → false
// - Null: "null" → null
// - JSON: "{\"key\": \"value\"}" → {key: "value"}
// - Strings: remain as strings

📝 Multi-line String Format

Multi-line strings must be enclosed in triple double quotes ("""):

# ✅ Valid multi-line strings
JSON_CONFIG="""
{
  "key": "value",
  "nested": {
    "data": "content"
  }
}
"""

MESSAGE="""
This is a
multi-line message
with "quotes" inside
"""

# ✅ Valid single-line quoted strings
SINGLE_LINE="This is a single line with quotes"

# ❌ Invalid (no quotes)
INVALID=This won't work
for multi-line content

# ❌ Invalid (single quotes not supported)
INVALID='This also
won\'t work'

Escape Rules:

  • No need to escape quotes inside triple-quoted strings
  • Use \\ for literal backslashes
  • Line breaks are preserved as-is
  • Single quotes (") are still supported for single-line strings

🆚 Comparison with Standard dotenv

| Feature | Standard dotenv | @de44/dotenv | | -------------------- | --------------- | ------------------- | | TypeScript Support | ❌ | ✅ | | Schema Validation | ❌ | ✅ | | Multi-line Strings | ❌ | ✅ | | Type Safety | ❌ | ✅ | | Runtime Validation | ❌ | ✅ | | Error Messages | Basic | Detailed Zod errors | | Value Coercion | ❌ | ✅ | | Profile Support | ❌ | ✅ | | Minimal Dependencies | ❌ | ✅ (Zod + lodash) |

📚 Examples

Check out the examples/ directory for more usage examples:

  • examples/basic-usage.ts - Basic setup and validation
  • examples/multiline-strings.ts - Multi-line string features
  • examples/env.example - Sample environment file

🤝 Contributing

See MAINTAINER.md for development setup and contribution guidelines.

📄 License

MIT License - see LICENSE for details.