Quick Start

Get up and running with safe-env in under 2 minutes.

Step 1: Import

import { env } from "@liahus/safe-env";

Step 2: Define Your Schema

Create a schema using the simple DSL syntax:

const ENV = env({
  DATABASE_URL: "string:url",
  PORT: "number:default=3000",
  NODE_ENV: "enum:development,production,test",
  JWT_SECRET: "string:min=32:secret",
});

Step 3: Use It!

Your environment variables are now fully typed and validated:

// ENV is fully typed! 🎉
console.log(ENV.PORT); // 3000 (number, not string!)
console.log(ENV.NODE_ENV); // "development" | "production" | "test"
console.log(ENV.DATABASE_URL); // string (validated as URL)
console.log(ENV.JWT_SECRET); // string (validated, min 32 chars)

Complete Example

import { env } from "@liahus/safe-env";

// Define your environment schema
const ENV = env({
  // String with URL validation
  DATABASE_URL: "string:url",
  
  // Number with default value
  PORT: "number:default=3000",
  
  // Enum with specific values
  NODE_ENV: "enum:development,production,test",
  
  // String with minimum length and secret masking
  JWT_SECRET: "string:min=32:secret",
  
  // Number with minimum value
  TIMEOUT: "number:min=1000:default=5000",
});

// Use your typed environment variables
console.log(`Server running on port ${ENV.PORT}`);
console.log(`Environment: ${ENV.NODE_ENV}`);
console.log(`Database: ${ENV.DATABASE_URL}`);

// TypeScript knows the types!
// ENV.PORT is number
// ENV.NODE_ENV is "development" | "production" | "test"
// ENV.DATABASE_URL is string

Error Handling

safe-env validates at startup and throws clear errors if validation fails:

import { env, EnvValidationError } from "@liahus/safe-env";

try {
  const ENV = env({
    DATABASE_URL: "string:url",
    PORT: "number",
  });
} catch (error) {
  if (error instanceof EnvValidationError) {
    console.error(error.message);
    // Environment variable validation failed:
    //   DATABASE_URL: Invalid url (received: undefined)
    //   PORT: Required (received: undefined)
  }
}

With .env Files

If you use dotenv or similar, load it before calling env():

import "dotenv/config"; // Load .env file
import { env } from "@liahus/safe-env";

// Now process.env is populated
const ENV = env({
  DATABASE_URL: "string:url",
  PORT: "number:default=3000",
});

🎉 That's it!

You're ready to use safe-env. Check out the DSL Syntax guide to learn about all available options.

Learn DSL Syntax →