Skip to main content

Function Signature

async function maybeSecretUuid(
  key: string
): Promise<UUID | undefined>

Parameters

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

Returns

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

How It Works

This is the optional variant of secretUuid. 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 validates it as a UUID
  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 UUID

Difference from secretUuid

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

Example

import { maybeSecretUuid } from "@nore/load-env"
import type { UUID } from "node:crypto"

// Returns undefined if the secret doesn't exist
const API_TOKEN = await maybeSecretUuid("API_TOKEN")

if (API_TOKEN) {
  console.log(`Using API token: ${API_TOKEN}`)
  // Make authenticated requests
} else {
  console.log("No API token found, using anonymous access")
  // Make unauthenticated requests
}

Secret File Format

The secret file should contain a valid UUID:
123e4567-e89b-12d3-a456-426614174000

Error Handling

Returns undefined if:
  • The secret file doesn’t exist
  • The file is empty
Throws an error if:
  • The file exists but the value is not a valid UUID format

Build docs developers (and LLMs) love