Skip to main content

Function Signature

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

Parameters

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

Returns

Promise<URL | undefined> - A URL object from the secret file, or undefined if not found

How It Works

This is the optional variant of secretUrl. 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 parses it as a URL
  4. Returns undefined if the secret file doesn’t exist (instead of throwing)
  5. Still throws an error if the file exists but contains an invalid URL

Difference from secretUrl

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

Example

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

// Returns undefined if the secret doesn't exist
const API_URL = await maybeSecretUrl("API_URL")

if (API_URL) {
  const response = await fetch(API_URL)
  console.log(`Connected to ${API_URL.hostname}`)
} else {
  console.log("No API URL configured, using local mode")
}

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

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 a valid URL

Build docs developers (and LLMs) love