Skip to main content

Function Signature

async function secretEnum<const T extends string[]>(
  key: string,
  values: T,
  fallback?: T[number]
): Promise<T[number]>

Parameters

key
string
required
The environment variable name that points to the secret file path
values
T extends string[]
required
Array of allowed string values for the enum
fallback
T[number]
Optional default value to return if the secret is not found (must be one of the allowed values)

Returns

Promise<T[number]> - One of the allowed enum values 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 against the allowed values
  4. Throws an error if the secret is missing or not in the allowed values (unless a fallback is provided)

Example

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

// Reads from file path in $LOG_LEVEL or /run/secrets/LOG_LEVEL
export const LOG_LEVEL = await secretEnum(
  "LOG_LEVEL",
  ["debug", "info", "warn", "error"] as const
)

// With fallback
export const ENVIRONMENT = await secretEnum(
  "ENVIRONMENT",
  ["development", "staging", "production"] as const,
  "development"
)

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 one of the allowed enum values
When a fallback is provided, returns the fallback value instead of throwing if the file doesn’t exist.

Build docs developers (and LLMs) love