Skip to main content

Function Signature

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

Parameters

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

Returns

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

How It Works

This is the optional variant of secretString. 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 as a UTF-8 string (trimmed)
  4. Returns undefined if the secret file doesn’t exist or is empty (instead of throwing)

Difference from secretString

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

Example

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

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

if (API_KEY) {
  console.log("API key is configured")
  // Use the API with authentication
} else {
  console.log("No API key found, running in limited mode")
  // Run without authentication
}

Docker Secrets Usage

# docker-compose.yml
services:
  app:
    secrets:
      - api_key

secrets:
  api_key:
    file: ./secrets/api_key.txt
If the secret file doesn’t exist, the function returns undefined instead of crashing your application.

Error Handling

Returns undefined if:
  • The secret file doesn’t exist
  • The file is empty
This function does not throw errors for missing secrets, making it ideal for optional configuration.

Build docs developers (and LLMs) love