Load Secrets From Environment Not From Files

A config loader that keeps secret values out of committed files by resolving them from the environment and refusing to read them from disk.

JavascriptConfig Management

Code

export class SecretConfigError extends Error {
  constructor(message, details = {}) {
    super(message);
    this.name = "SecretConfigError";
    this.missing = details.missing ?? [];
    this.leaked = details.leaked ?? [];
  }
}

export function loadConfig(filePayload, secretSpecs, env = process.env) {
  if (!filePayload || typeof filePayload !== "object" || Array.isArray(filePayload)) {
    throw new SecretConfigError("file payload must be an object");
  }

  const leaked = secretSpecs
    .filter((spec) => Object.prototype.hasOwnProperty.call(filePayload, spec.key))
    .map((spec) => spec.key);
  if (leaked.length > 0) {
    throw new SecretConfigError(
      "secret keys must never appear in a committed file: " + leaked.join(", "),
      { leaked },
    );
  }

  const config = { ...filePayload };
  const missing = [];
  for (const spec of secretSpecs) {
    const value = env[spec.envVar];
    if (value === undefined || value === "") {
      missing.push(spec.envVar);
      continue;
    }
    config[spec.key] = value;
  }
  if (missing.length > 0) {
    throw new SecretConfigError("missing required secrets: " + missing.join(", "), { missing });
  }
  return config;
}

A config file that carries a token gets committed once and leaks forever, even after the file is later removed from the repository.

Use case: engineers who keep credentials out of version control

Inputs / outputs

  • Input: a spec listing which keys are secrets and their environment variable names
  • Output: a config object where secret keys come only from the environment

Error conditions

  • secret key missing from the environment
  • secret key present in the file payload (refused)
  • file payload is not an object

Approach

load the non-secret file payload; copy secret keys exclusively from the environment; refuse the whole load if a secret appears in the file payload.

Implementation

export class SecretConfigError extends Error {
  constructor(message, details = {}) {
    super(message);
    this.name = "SecretConfigError";
    this.missing = details.missing ?? [];
    this.leaked = details.leaked ?? [];
  }
}

export function loadConfig(filePayload, secretSpecs, env = process.env) {
  if (!filePayload || typeof filePayload !== "object" || Array.isArray(filePayload)) {
    throw new SecretConfigError("file payload must be an object");
  }

  const leaked = secretSpecs
    .filter((spec) => Object.prototype.hasOwnProperty.call(filePayload, spec.key))
    .map((spec) => spec.key);
  if (leaked.length > 0) {
    throw new SecretConfigError(
      "secret keys must never appear in a committed file: " + leaked.join(", "),
      { leaked },
    );
  }

  const config = { ...filePayload };
  const missing = [];
  for (const spec of secretSpecs) {
    const value = env[spec.envVar];
    if (value === undefined || value === "") {
      missing.push(spec.envVar);
      continue;
    }
    config[spec.key] = value;
  }
  if (missing.length > 0) {
    throw new SecretConfigError("missing required secrets: " + missing.join(", "), { missing });
  }
  return config;
}

Verification tests

import { test } from "node:test";
import assert from "node:assert/strict";
import { SecretConfigError, loadConfig } from "./example.mjs";

const specs = [
  { key: "apiToken", envVar: "API_TOKEN" },
  { key: "dbPassword", envVar: "DB_PASSWORD" },
];

test("resolves secrets from the environment", () => {
  const config = loadConfig(
    { region: "eu" },
    specs,
    { API_TOKEN: "t-1", DB_PASSWORD: "p-1" },
  );
  assert.equal(config.region, "eu");
  assert.equal(config.apiToken, "t-1");
  assert.equal(config.dbPassword, "p-1");
});

test("refuses a file that carries a secret key", () => {
  assert.throws(
    () => loadConfig({ apiToken: "leaked" }, specs, {}),
    (err) => {
      assert.ok(err instanceof SecretConfigError);
      assert.deepEqual(err.leaked, ["apiToken"]);
      return true;
    },
  );
});

test("reports every missing secret at once", () => {
  assert.throws(
    () => loadConfig({}, specs, {}),
    (err) => {
      assert.deepEqual(err.missing.sort(), ["API_TOKEN", "DB_PASSWORD"]);
      return true;
    },
  );
});

test("rejects a non-object payload", () => {
  assert.throws(() => loadConfig("nope", specs, {}), SecretConfigError);
});

Dependencies and running

No external dependencies (standard library only).

Runtime: node >= 18 Entry point: node example.mjs

Limitations and error handling

no vault or KMS integration; no secret rotation; environment only.

Verification boundary

execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox

Interactive Tools for This Topic