Skip to main content

Function Signature

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

Parameters

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

Returns

Promise<URL> - A URL object parsed 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 parses it as a URL using the URL constructor
  4. Throws an error if the secret is missing or invalid (unless a fallback is provided)

Example

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

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

// With fallback
export const DATABASE_URL = await secretUrl(
  "DATABASE_URL",
  new URL("postgres://localhost:5432/dev")
)

// Use the URL
const response = await fetch(API_URL)

Secret File Format

The secret file should contain a valid URL string:
https://api.example.com
Or with authentication:
postgres://user:password@host:5432/database

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

Build docs developers (and LLMs) love