Skip to main content

Function Signature

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

Parameters

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

Returns

Promise<string> - The string value read 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 as a UTF-8 string (trimmed)
  4. Throws an error if the secret is missing or empty (unless a fallback is provided)

Example

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

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

// With fallback
export const SERVICE_NAME = await secretString("SERVICE_NAME", "default-service")

Docker Secrets Usage

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

secrets:
  api_key:
    file: ./secrets/api_key.txt
The secret will be mounted at /run/secrets/API_KEY in the container.

Error Handling

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

Build docs developers (and LLMs) love