Skip to content

@j0nathan-ll0yd/env ​

Type-safe environment variable access with validation.

Functions ​

getRequiredEnv(name) ​

Get a required environment variable. Throws MissingEnvVarError if not set.

typescript
const dbUrl = getRequiredEnv("DATABASE_URL");

getOptionalEnv(name, defaultValue?) ​

Get an optional environment variable with an optional default.

typescript
const logLevel = getOptionalEnv("LOG_LEVEL", "info");

getRequiredEnvNumber(name) ​

Get a required environment variable and parse it as a number.

typescript
const port = getRequiredEnvNumber("PORT");

getOptionalEnvNumber(name, defaultValue?) ​

Get an optional environment variable as a number.

createLazyConfig(factory) ​

Create a lazily-initialized configuration object. The factory is only called once on first access.

typescript
const config = createLazyConfig(() => ({
  dbUrl: getRequiredEnv("DATABASE_URL"),
  apiKey: getRequiredEnv("API_KEY"),
  maxRetries: getOptionalEnvNumber("MAX_RETRIES", 3),
}));

// Config is not evaluated until first access
config.dbUrl; // Now the factory runs

loadEnvFile(path?) ​

Load a .env file into process.env. Defaults to .env in the current working directory and silently does nothing when the file is absent, so it is safe to call unconditionally.

typescript
loadEnvFile(); // .env
loadEnvFile(".env.staging");

The mantle CLI calls this at startup. Lambda code should not: Lambda environment variables come from the generated infrastructure, not from a file in the bundle.

Error Classes ​

MissingEnvVarError ​

Thrown when a required environment variable is not set.

typescript
class MissingEnvVarError extends Error {
  readonly variableName: string;
}