Skip to main content

Function Signature

function maybeEnvUuid(key: string): UUID | undefined

Parameters

key
string
required
The name of the environment variable to read

Returns

UUID | undefined - A UUID string (branded type from node:crypto), or undefined if the variable is not set or empty.

Behavior

Returns undefined when:
  • The environment variable is not set
  • The environment variable is an empty string
  • The environment variable contains only whitespace
Throws TypeError when:
  • The value is not a valid UUID format

Example

import { maybeEnvUuid } from "@load-env/core"
import type { UUID } from "node:crypto"

// Optional tenant ID
export const TENANT_ID = maybeEnvUuid("TENANT_ID")

if (TENANT_ID) {
  console.log(`Running in multi-tenant mode for tenant: ${TENANT_ID}`)
  await loadTenantConfig(TENANT_ID)
} else {
  console.log("Running in single-tenant mode")
}

// Optional trace ID for distributed tracing
export const TRACE_ID = maybeEnvUuid("TRACE_ID")

function logWithTrace(message: string) {
  if (TRACE_ID) {
    console.log(`[${TRACE_ID}] ${message}`)
  } else {
    console.log(message)
  }
}

// Optional service instance ID
export const INSTANCE_ID = maybeEnvUuid("INSTANCE_ID")

const instanceId: UUID = INSTANCE_ID ?? crypto.randomUUID()

UUID Format

Accepts standard UUID formats:
  • 550e8400-e29b-41d4-a716-446655440000 (with hyphens)
  • Any valid UUID v1, v3, v4, or v5

When to Use

Use maybeEnvUuid instead of envUuid when:
  • The environment variable is optional
  • You want to handle missing values gracefully with undefined
  • You can generate a UUID or use alternative logic when not provided
Use envUuid when:
  • The environment variable is required for your application
  • You want the application to fail fast if the variable is missing

Build docs developers (and LLMs) love