Skip to main content

Function Signature

async function maybeSecretDate(
  key: string
): Promise<Date | undefined>

Parameters

key
string
required
The environment variable name that points to the secret file path

Returns

Promise<Date | undefined> - A Date object from the secret file, or undefined if not found

How It Works

This is the optional variant of secretDate. It reads secrets from the filesystem without throwing errors when the file is missing:
  1. Checks if the environment variable key contains a file path
  2. If no path is set, defaults to /run/secrets/{key}
  3. Reads the file contents and parses it as a Date
  4. Returns undefined if the secret file doesn’t exist (instead of throwing)
  5. Still throws an error if the file exists but contains an invalid date

Difference from secretDate

  • maybeSecretDate: Returns undefined when the secret file is missing
  • secretDate: Throws an error when the secret file is missing (unless a fallback is provided)
Use maybeSecretDate for truly optional date secrets where absence is a valid state.

Example

import { maybeSecretDate } from "@nore/load-env"

// Returns undefined if the secret doesn't exist
export const EXPIRES_AT = await maybeSecretDate("EXPIRES_AT")

if (EXPIRES_AT) {
  console.log(`Expires on ${EXPIRES_AT.toISOString()}`)
} else {
  console.log("No expiration date set")
}

Error Handling

Returns undefined if:
  • The secret file doesn’t exist
  • The file is empty
Throws an error if:
  • The file exists but cannot be parsed as a valid Date

Build docs developers (and LLMs) love