> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch31-configuration-system/31.5-environment-variables.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 31.5 Environment Variables

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~215k tokens, Output \~5k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

Configuration files inevitably contain sensitive information—API keys, database passwords, tokens from third-party services. Writing these values directly in JSON5 files is neither secure (might be accidentally committed to version control) nor flexible (different environments need different values). OpenClaw solves this problem through an environment variable substitution mechanism: use `${VAR_NAME}` placeholders in configuration files, which are automatically replaced with corresponding environment variable values at load time. This section analyzes the implementation details of this mechanism.

***

## 31.5.1 Environment Variable Substitution (`src/config/env-substitution.ts`)

### Basic Syntax

In any configuration string value, you can reference environment variables using `${VAR_NAME}`:

```json5
{
  models: {
    providers: {
      "vercel-gateway": {
        apiKey: "${VERCEL_GATEWAY_API_KEY}"
      }
    }
  },
  gateway: {
    auth: {
      token: "${OPENCLAW_AUTH_TOKEN}"
    }
  }
}
```

At load time, `${VERCEL_GATEWAY_API_KEY}` is replaced with the value of `process.env.VERCEL_GATEWAY_API_KEY`.

### Variable Name Rules

Environment variable names must match a strict regex pattern—only uppercase letters, digits, and underscores are allowed, and must start with a letter or underscore:

```typescript
// src/config/env-substitution.ts

const ENV_VAR_NAME_PATTERN = /^[A-Z_][A-Z0-9_]*$/;
```

This means:

* `${MY_API_KEY}` — valid
* `${OPENCLAW_TOKEN_123}` — valid
* `${_INTERNAL}` — valid
* `${myApiKey}` — **invalid** (lowercase letters)
* `${123_KEY}` — **invalid** (starts with digit)

The uppercase restriction is an intentional design choice—it prevents configuration authors from mistakenly treating JSON key names as environment variables (e.g., `${apiKey}`), while conforming to Unix environment variable naming conventions.

### Escape Syntax

If you need to include a literal `${...}` in a configuration value (rather than variable substitution), use double dollar signs to escape:

```json5
{
  prompt: "Use the $${VARIABLE} syntax for templating"
  // After parsing: Use the ${VARIABLE} syntax for templating
}
```

### Core Substitution Logic

The `substituteString` function scans the string character by character, handling three cases:

```typescript
// src/config/env-substitution.ts (simplified)

function substituteString(value: string, env: NodeJS.ProcessEnv, configPath: string): string {
  // Fast path: no $ symbol → return directly
  if (!value.includes("$")) return value;

  const chunks: string[] = [];

  for (let i = 0; i < value.length; i++) {
    const char = value[i];
    if (char !== "$") {
      chunks.push(char);
      continue;
    }

    const next = value[i + 1];
    const afterNext = value[i + 2];

    // Case 1: $${VAR} → output literal ${VAR}
    if (next === "$" && afterNext === "{") {
      const end = value.indexOf("}", i + 3);
      if (end !== -1) {
        const name = value.slice(i + 3, end);
        if (ENV_VAR_NAME_PATTERN.test(name)) {
          chunks.push(`\${${name}}`);
          i = end;
          continue;
        }
      }
    }

    // Case 2: ${VAR} → replace with environment variable value
    if (next === "{") {
      const end = value.indexOf("}", i + 2);
      if (end !== -1) {
        const name = value.slice(i + 2, end);
        if (ENV_VAR_NAME_PATTERN.test(name)) {
          const envValue = env[name];
          if (envValue === undefined || envValue === "") {
            throw new MissingEnvVarError(name, configPath);
          }
          chunks.push(envValue);
          i = end;
          continue;
        }
      }
    }

    // Case 3: ordinary $ symbol → keep as is
    chunks.push(char);
  }

  return chunks.join("");
}
```

### Error Handling: MissingEnvVarError

When a referenced environment variable is not set or is an empty string, the system throws `MissingEnvVarError`, with the variable name and configuration path for easy problem location:

```typescript
// src/config/env-substitution.ts

export class MissingEnvVarError extends Error {
  constructor(
    public readonly varName: string,
    public readonly configPath: string,
  ) {
    super(`Missing env var "${varName}" referenced at config path: ${configPath}`);
    this.name = "MissingEnvVarError";
  }
}
```

For example: if `models.providers.vercel-gateway.apiKey` references `${VERCEL_GATEWAY_API_KEY}` but that environment variable is not set, the error message will be:

```
Missing env var "VERCEL_GATEWAY_API_KEY" referenced at config path: models.providers.vercel-gateway.apiKey
```

### Recursive Substitution

`resolveConfigEnvVars` serves as the entry function, recursively traversing the entire configuration object through `substituteAny`, executing substitution on all string values:

```typescript
// src/config/env-substitution.ts

function substituteAny(value: unknown, env: NodeJS.ProcessEnv, path: string): unknown {
  if (typeof value === "string") {
    return substituteString(value, env, path);
  }
  if (Array.isArray(value)) {
    return value.map((item, index) => substituteAny(item, env, `${path}[${index}]`));
  }
  if (isPlainObject(value)) {
    const result: Record<string, unknown> = {};
    for (const [key, val] of Object.entries(value)) {
      result[key] = substituteAny(val, env, path ? `${path}.${key}` : key);
    }
    return result;
  }
  // Primitive types (number, boolean, null) pass through directly
  return value;
}

export function resolveConfigEnvVars(
  obj: unknown,
  env: NodeJS.ProcessEnv = process.env,
): unknown {
  return substituteAny(obj, env, "");
}
```

Note several design details:

1. **Path Tracking**: The `path` parameter builds the complete configuration path during recursion (e.g., `models.providers.vercel-gateway.apiKey`), enabling precise error location.
2. **String-Only Processing**: Numbers, booleans, and `null` pass through directly without substitution attempts.
3. **Non-Destructive**: The function returns a new object without modifying the input (pure function semantics).

***

## 31.5.2 Environment Variable Collection (`src/config/env-vars.ts`)

### config.env Configuration Section

OpenClaw allows users to preset environment variables through the `env` section in the configuration file, which are injected into `process.env` early in configuration loading:

```json5
{
  env: {
    // Structured variable declaration
    vars: {
      "MY_CUSTOM_API_KEY": "sk-xxx",
      "DATABASE_URL": "postgres://localhost/openclaw"
    },
    // Top-level shortcuts (backward compatible)
    "NODE_ENV": "production",
    "DEBUG": "openclaw:*"
  }
}
```

### collectConfigEnvVars

The `collectConfigEnvVars` function collects all environment variables to be injected from the configuration, merging two sources:

```typescript
// src/config/env-vars.ts

export function collectConfigEnvVars(cfg?: OpenClawConfig): Record<string, string> {
  const envConfig = cfg?.env;
  if (!envConfig) return {};

  const entries: Record<string, string> = {};

  // Source 1: explicit declarations in env.vars
  if (envConfig.vars) {
    for (const [key, value] of Object.entries(envConfig.vars)) {
      if (!value) continue;
      entries[key] = value;
    }
  }

  // Source 2: top-level shortcuts under env (excluding reserved keys)
  for (const [key, value] of Object.entries(envConfig)) {
    if (key === "shellEnv" || key === "vars") continue;  // Skip reserved keys
    if (typeof value !== "string" || !value.trim()) continue;
    entries[key] = value;
  }

  return entries;
}
```

Note the handling of two reserved keys:

* **`vars`**: This is the container for structured variable declarations, already processed in the first step, should not be treated as an environment variable name.
* **`shellEnv`**: This is a boolean configuration item controlling whether shell environment variables are passed to child processes, should not be treated as an environment variable.

### Position in the Loading Pipeline

Recalling the 12-step configuration loading pipeline introduced in section 23.1, environment variable-related processing appears in steps 3 and 4:

```
Step 3: config.env injection → collectConfigEnvVars → write to process.env
Step 4: ${VAR} substitution → resolveConfigEnvVars → replace variable references in config
```

This order is critical—first inject variables declared in `config.env` into `process.env`, then execute `${VAR}` substitution. This means users can define a variable in `env.vars` and then reference it elsewhere in the configuration:

```json5
{
  env: {
    vars: {
      "MY_API_BASE": "https://api.example.com"
    }
  },
  models: {
    providers: {
      "custom": {
        baseUrl: "${MY_API_BASE}/v1"  // Reference the variable declared above
      }
    }
  }
}
```

> **Sidebar**: This "declare first, reference later" design is common in configuration systems. Kubernetes ConfigMap, Docker Compose's `.env` file, GitHub Actions' `env` section all adopt similar patterns. The core advantage is "single source of truth"—sensitive values are defined in only one place, other locations use references, avoiding inconsistencies from copy-paste.

***

## Summary of This Section

1. **`${VAR_NAME}` Syntax** allows referencing environment variables in configuration strings, variable names must be all uppercase and match the `[A-Z_][A-Z0-9_]*` pattern.
2. **`$${VAR}` Escape** outputs literal `${VAR}`, used for scenarios where configuration needs to include template syntax.
3. **MissingEnvVarError** is thrown when a variable is not set or is empty, with variable name and precise configuration path for easy debugging.
4. **Recursive Substitution** traverses the entire configuration object tree, executing substitution only on string values, numbers and booleans pass through directly.
5. **`config.env` Section** supports two environment variable declaration methods: `env.vars` (structured) and top-level shortcuts (backward compatible).
6. **Load Order Guarantee**: First inject `config.env` into `process.env`, then execute `${VAR}` substitution—allowing configuration self-reference.

***

> ### 🔬 Going Deeper: 31.6 Source Deep Dive
>
> That's the end of the chapter's main text. If you're going to **modify this code**, or reproduce it in your own project, read on: [**31.6 Source Deep Dive: The Five-Stage Read Pipeline and Write-Back Restoration**](https://www.openclawbook.xyz/en/ch31-configuration-system/31.6-source-deep-dive-read-pipeline-and-write-back.md) traces the real implementation line by line along with the issues behind it, at a noticeably higher information density.
>
> **The main text is for understanding structure; the deep dive is for understanding trade-offs.**
