Skip to main content

Function Signature

async function secretUuid(
  key: string,
  fallback?: UUID
): Promise<UUID>

Parameters

key
string
required
The environment variable name that points to the secret file path
fallback
UUID
Optional default UUID to return if the secret is not found

Returns

Promise<UUID> - A UUID string from the secret file

How It Works

This function reads secrets from the filesystem, following Docker secrets conventions:
  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. Throws an error if the secret is missing or invalid (unless a fallback is provided)
The UUID must be in standard format (e.g., 123e4567-e89b-12d3-a456-426614174000).

Example

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

// Reads from file path in $API_TOKEN or /run/secrets/API_TOKEN
export const API_TOKEN = await secretUuid("API_TOKEN")

// With fallback
export const SESSION_ID = await secretUuid(
  "SESSION_ID",
  "123e4567-e89b-12d3-a456-426614174000" as UUID
)

Secret File Format

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

Error Handling

Throws an error if:
  • The secret file doesn’t exist (when no fallback provided)
  • The file is empty (when no fallback provided)
  • The value is not a valid UUID format
When a fallback is provided, returns the fallback value instead of throwing if the file doesn’t exist.

Build docs developers (and LLMs) love