Skip to main content

Signature

function envString(key: string, fallback?: string): string
Obtains an environment variable as a string.

Parameters

key
string
required
The name of the environment variable to read
fallback
string
Optional fallback value if the environment variable is not set. If not provided and the variable is missing, an error will be thrown.

Returns

string
string
The string value from the environment variable or fallback

Behavior

  • Reads the environment variable and trims whitespace
  • Falls back to the string representation of the fallback value if the variable is not set
  • Throws an error if both the variable and fallback are missing
  • Validates that the resulting string is not empty
  • Throws an error even if an empty string is provided as fallback

Error Handling

  • Throws Error with message "$KEY is missing" when:
    • The environment variable is not set and no fallback is provided
    • The environment variable is set but empty (after trimming)
    • An empty string is provided as fallback

Example

import { envString } from "@natoboram/load_env"

// With fallback
export const NODE_ENV = envString("NODE_ENV", "development")

// Without fallback (will throw if not set)
export const API_KEY = envString("API_KEY")

// Usage examples:
// NODE_ENV=production → "production"
// NODE_ENV="  example  " → "example" (trimmed)
// NODE_ENV="" → throws Error (empty after trim)
// NODE_ENV not set → "development" (uses fallback)

Build docs developers (and LLMs) love