Skip to main content

Function Signature

async function maybeSecretEnum<const T extends string[]>(
  key: string,
  values: T
): Promise<T[number] | undefined>

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

Returns

Promise<T[number] | undefined> - One of the allowed enum values, or undefined if not found

How It Works

This is the optional variant of secretEnum. 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 against allowed values
  4. Returns undefined if the secret file doesn’t exist (instead of throwing)
  5. Still throws an error if the file exists but contains a value not in the allowed list

Difference from secretEnum

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

Example

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

// Returns undefined if the secret doesn't exist
export const LOG_LEVEL = await maybeSecretEnum(
  "LOG_LEVEL",
  ["debug", "info", "warn", "error"] as const
)

const level = LOG_LEVEL ?? "info" // Default to "info" if not set
console.log(`Using log level: ${level}`)

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 one of the allowed enum values

Build docs developers (and LLMs) love