Skip to main content

Signature

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

Parameters

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

Returns

Date
Date
The parsed Date object from the environment variable or fallback

Behavior

  • Reads the environment variable and trims whitespace
  • Falls back to the ISO string representation of the fallback Date if the variable is not set
  • Throws an error if both the variable and fallback are missing
  • Parses the string value using the Date constructor
  • Validates that the parsed date is valid (not NaN)
  • Throws a TypeError if the value is not a valid date string

Error Handling

  • Throws Error with message "$KEY is missing" when the environment variable is not set and no fallback is provided
  • Throws TypeError with message "$KEY is not a valid Date: VALUE" when the value cannot be parsed as a valid date

Example

import { envDate } from "@natoboram/load_env"

// With fallback
export const START_DATE = envDate(
  "START_DATE",
  new Date("2025-01-01T00:00:00.000Z")
)

// Without fallback (will throw if not set)
export const EXPIRY_DATE = envDate("EXPIRY_DATE")

// Usage examples:
// START_DATE=2025-05-28T00:50:58.816Z → Date object
// START_DATE="May 28, 2025" → Date object
// START_DATE not set → Date("2025-01-01T00:00:00.000Z") (uses fallback)

Build docs developers (and LLMs) love