> 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/ch37-deployment/37.4-nix-declarative-deployment.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 37.4 Nix Declarative Deployment

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

***

OpenClaw officially maintains a Nix ecosystem integration project [**nix-openclaw**](https://github.com/openclaw/nix-openclaw), providing a declarative deployment solution based on Home Manager. Unlike npm global installation or Docker containers, Nix deployment offers three major advantages: **reproducibility**, **instant rollback**, and **declarative configuration management**.

> **Sidebar**: Nix is a functional package manager and build system. Its core idea is to treat software package building as a pure function — identical inputs (source code + dependencies) necessarily produce identical outputs (build artifacts), guaranteeing reproducibility. NixOS extends this philosophy to the entire operating system, while Home Manager focuses on user-level program and configuration management. **Flake** is Nix's modern project format, precisely locking all dependency versions through `flake.nix` and `flake.lock`.

## 37.4.1 nix-openclaw Overview

nix-openclaw is a Nix Flake project providing:

* **Home Manager module**: Declaratively configure Gateway, macOS application, toolchain
* **Launchd/systemd services**: Automatically generate daemon process configuration
* **Plugin system**: Declaratively manage OpenClaw extensions
* **Templates**: Quick-start flake templates

### Deployment Architecture

```
flake.nix (user configuration)
    │
    ├── inputs.nix-openclaw (Flake input)
    │
    └── home-manager.modules = [{
            programs.openclaw = {
                enable = true;
                gateway.enable = true;
                gateway.port = 18789;
                gateway.auth.mode = "token";
                # ...
            };
        }]
            │
            ├── Generate openclaw.json (configuration file)
            ├── Generate launchd plist / systemd unit
            ├── Install OpenClaw npm package (pinned version)
            └── Set OPENCLAW_NIX_MODE=1
```

## 37.4.2 Quick Start

nix-openclaw provides an AI-agent-oriented installation mode — users can directly send installation instructions to an AI assistant (like Claude, Cursor), letting the AI agent complete all configuration work:

```
I want to set up nix-openclaw on my Mac.
Repository: github:openclaw/nix-openclaw

What I need you to do:
1. Check if Determinate Nix is installed (if not, install it)
2. Create a local flake at ~/code/openclaw-local using templates/agent-first/flake.nix
3. Set up secrets (API keys) - plain files at ~/.secrets/ is fine
4. Fill in the template placeholders and run home-manager switch
5. Verify: launchd running, gateway responds
```

Manual installation steps:

```bash
# 1. Install Determinate Nix (if not already installed)
curl --proto '=https' --tlsv1.2 -sSf -L \
  https://install.determinate.systems/nix | sh -s -- install

# 2. Create project from template
nix flake init -t github:openclaw/nix-openclaw#agent-first
# Or clone to specific directory
mkdir -p ~/code/openclaw-local && cd ~/code/openclaw-local
nix flake init -t github:openclaw/nix-openclaw#agent-first

# 3. Edit flake.nix, fill in configuration
# 4. Apply configuration
home-manager switch --flake .
```

## 37.4.3 Nix Mode Runtime Behavior

When OpenClaw runs in a Nix environment, `nix-openclaw` automatically sets the environment variable `OPENCLAW_NIX_MODE=1`. OpenClaw core detects this mode through `resolveIsNixMode()`:

```typescript
// src/config/paths.ts
export function resolveIsNixMode(env = process.env): boolean {
  return env.OPENCLAW_NIX_MODE === "1";
}
```

Behavior changes in Nix mode:

| Feature                  | Normal Mode                 | Nix Mode                                        |
| ------------------------ | --------------------------- | ----------------------------------------------- |
| Auto-install flow        | Enabled                     | **Disabled**                                    |
| Missing dependency hints | Generic install guide       | **Nix-specific fix suggestions**                |
| Console UI               | Normal                      | Display read-only Nix mode banner               |
| Configuration path       | `~/.openclaw/openclaw.json` | Managed by Nix (read-only)                      |
| State directory          | `~/.openclaw/`              | `OPENCLAW_STATE_DIR` points to Nix-managed path |

### Path Management

In Nix mode, configuration files and state directories are precisely controlled through environment variables:

```bash
# Automatically set by nix-openclaw
OPENCLAW_NIX_MODE=1
OPENCLAW_CONFIG_PATH=/path/to/nix-managed/openclaw.json   # Read-only config
OPENCLAW_STATE_DIR=~/.openclaw                             # Mutable state
```

`resolveStateDir()` and `resolveConfigPath()` prioritize reading environment variable overrides:

```typescript
export function resolveStateDir(env = process.env): string {
  const override = env.OPENCLAW_STATE_DIR?.trim();
  if (override) return resolveUserPath(override);
  // ... fallback logic
}
```

This design ensures that configuration files in Nix's immutable store (Nix store) aren't modified at runtime, while mutable state (sessions, logs, cache) can still be written normally.

### macOS Application Integration

macOS applications don't automatically inherit shell environment variables, so Nix mode can also be set via macOS defaults command:

```bash
defaults write bot.molt.mac openclaw.nixMode -bool true
```

## 37.4.4 Declarative Configuration Example

A complete `flake.nix` configuration example:

```nix
{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
    home-manager.url = "github:nix-community/home-manager";
    nix-openclaw.url = "github:openclaw/nix-openclaw";
  };

  outputs = { nixpkgs, home-manager, nix-openclaw, ... }: {
    homeConfigurations."myuser" = home-manager.lib.homeManagerConfiguration {
      pkgs = nixpkgs.legacyPackages.aarch64-darwin;
      modules = [
        nix-openclaw.homeManagerModules.default
        {
          programs.openclaw = {
            enable = true;
            
            gateway = {
              enable = true;
              port = 18789;
              bind = "loopback";
              
              auth = {
                mode = "token";
                # token read from secrets file
              };
              
              tailscale = {
                mode = "serve";
                resetOnExit = true;
              };
              
              discovery.mdns.mode = "minimal";
            };
            
            # API keys managed through secrets
            secrets.anthropicKey = "/Users/myuser/.secrets/anthropic-key";
          };
        }
      ];
    };
  };
}
```

## 37.4.5 Comparison with Other Deployment Methods

| Dimension         | npm Global               | Docker                         | Nix                                   |
| ----------------- | ------------------------ | ------------------------------ | ------------------------------------- |
| Installation      | `npm i -g`               | `docker compose up`            | `home-manager switch`                 |
| Reproducibility   | ✗ (depends on host Node) | △ (depends on image version)   | ✓ (precisely locked)                  |
| Rollback          | Manual                   | `docker pull` old version      | `home-manager switch --rollback`      |
| Configuration     | Manual JSON editing      | Environment variables + mounts | Declarative Nix expressions           |
| Isolation         | None                     | Container isolation            | Nix store isolation                   |
| macOS integration | ✓ (native)               | △ (requires port mapping)      | ✓ (launchd + native app)              |
| Use cases         | Quick start              | Server deployment              | Advanced users / team standardization |

The core advantage of Nix deployment is **declarative reproducibility** — the entire system state (including OpenClaw version, configuration, dependencies) is precisely described in a single `flake.nix` file. Anyone at any time using the same flake gets exactly identical results.

***

## Section Summary

1. **nix-openclaw** is OpenClaw's official Nix integration, providing declarative deployment as a Home Manager module.
2. **Nix mode** (`OPENCLAW_NIX_MODE=1`) changes runtime behavior: disables auto-install flow, shows Nix-specific error hints, configuration paths precisely controlled by environment variables.
3. **Path separation design** ensures Nix's immutable configuration (read-only) and runtime mutable state (sessions, cache) don't interfere with each other.
4. Compared to npm and Docker, Nix provides precise reproducibility and instant rollback capability, especially suitable for advanced users and team standardized deployment.
5. The Nix deployment solution reflects OpenClaw's support for multiple deployment philosophies — from simplest npm global installation to strictest declarative management, users can choose based on needs.
