OpenAI Codex CLI With Clash: Setup Guide For Stable Access

Codex CLI brings AI-assisted coding to the terminal, but unreliable network access can interrupt authentication and commands. Learn how Clash routing can make everyday Codex sessions more dependable.

Why Codex CLI Benefits from a Proper Clash Route

Codex CLI brings AI-assisted coding into the terminal, which makes it useful in a very different way from a browser-based chat interface. A single coding session may send several types of requests: authentication traffic, model API requests, usage or project metadata, file-related operations, and tool responses triggered by commands. If one of these connections is interrupted, the visible symptom may be misleading. The login page can open successfully while a model request times out, or a short prompt can work while a longer coding task fails halfway through.

Clash can make this workflow more predictable by providing one controlled outbound path for Codex CLI. The important point is not simply turning on a proxy. You need to decide whether the CLI will use environment variables, the operating system proxy, or a TUN interface, then make sure DNS resolution, proxy variables, and Clash rules agree with that choice.

This guide focuses on the practical setup used on Windows, macOS, and Linux with a maintained mihomo-based client such as Clash Verge Rev, Clash Verge, or another compatible Clash GUI. The same principles also apply when the mihomo core is running as a background service. The examples use a local Clash mixed port of 7890; check your own client before copying the value because the port may be different.

A proxy cannot fix every Codex error

Clash only controls traffic that reaches its listener. An expired API key, an account permission problem, a rate limit, an invalid model name, a broken subscription, or a server-side outage will still fail with a correctly configured proxy. Use the logs and command-line error text together instead of treating every timeout as a routing problem.

Before You Start: Client, Kernel, and Credentials

Start with a client that can run the configuration you intend to use. For desktop CLI work, a mihomo-based build is usually the most flexible choice because it supports system proxy mode, TUN mode, modern DNS handling, rule providers, and more complete outbound compatibility than the discontinued original Clash kernel. The graphical interface is only the control layer; the core is what actually accepts connections and applies routing rules.

  • Install an active Clash client. Download the build for your operating system from the download center. On Windows, confirm that the client starts without being blocked by Windows Defender or the firewall. On macOS, allow the required network extension or helper when the client requests it. On Linux, verify that the service or GUI remains running after you close the terminal.
  • Import a working subscription. A subscription should provide at least one reachable proxy node and a proxy group that can be selected in the Clash dashboard. Test a node with an ordinary browser request before debugging Codex CLI.
  • Confirm the local listener. In the Clash settings or dashboard, find the mixed, HTTP, and SOCKS ports. A mixed port accepts both HTTP CONNECT and SOCKS5-style traffic, which is convenient for command-line tools. Do not assume that 7890 is universal.
  • Prepare authentication separately. Codex CLI credentials may come from an interactive login flow, an API key, or an environment variable supported by the installed release. Keep credentials out of shell history, public repositories, screenshots, and shared configuration files.
  • Check the CLI installation. Run codex --version and record the result. Configuration names and authentication behavior can change between releases, so troubleshooting is much easier when the client and CLI versions are known.

Do not confuse the Clash subscription URL with the Codex credential. The subscription controls which network nodes are available to Clash, while the API key or login session controls access to the coding service. They are different secrets with different reset procedures. If either one is exposed, rotate it from the relevant provider account rather than merely deleting it from a local file.

Layer What it controls What to verify
Clash client Local listeners, rules, DNS, and tunnel mode The core is running and the selected node is available
Shell environment How Codex CLI discovers an HTTP or SOCKS proxy HTTPS_PROXY, HTTP_PROXY, and NO_PROXY are intentional
Codex authentication Account or API authorization Login or API-key status is valid
Routing rules Which destinations use DIRECT or the proxy group Requests appear in Clash logs under the expected policy

Choose the Right Clash Mode for a Terminal Workflow

There are three practical ways to connect Codex CLI to Clash. They are not interchangeable, and using more than one at the same time can make diagnosis unnecessarily difficult.

Option One: Explicit Proxy Environment Variables

This is the clearest option when only Codex CLI and a few developer tools should use the proxy. The command inherits proxy variables from the shell, while unrelated desktop applications continue using their normal network path. It also makes the selected route visible in a project runbook or a diagnostic command.

Use an HTTP proxy URL for HTTP_PROXY and HTTPS_PROXY when the Clash listener supports HTTP CONNECT. A mixed port is commonly suitable. If your client exposes only a SOCKS5 listener, use a SOCKS URL and confirm that the CLI release and its underlying HTTP library support it. Some tools recognize ALL_PROXY but ignore HTTPS_PROXY; others do the opposite, so the actual behavior must be tested rather than guessed.

Option Two: System Proxy Mode

System proxy mode is convenient for applications that read Windows or macOS proxy settings, but terminal programs are inconsistent. Some inherit the operating system setting, some require environment variables, and some use their own network stack. Therefore, enabling system proxy mode alone is not proof that Codex CLI is proxied. Explicit variables are still preferable when you need a reproducible command-line setup.

Option Three: TUN Mode

TUN mode captures traffic at the virtual network interface level and is useful when the CLI ignores proxy variables or when several tools need the same route. It normally requires administrator permission on Windows, a network extension or elevated helper on macOS, and suitable privileges on Linux. TUN mode can also capture DNS and connections from tools that do not understand HTTP or SOCKS proxies, but it adds another layer of route and DNS interaction.

For a first setup, begin with environment variables. Move to TUN mode only when the CLI or a related tool does not honor the explicit proxy, or when you intentionally want system-wide capture. Do not run a full VPN, another transparent proxy, and Clash TUN simultaneously while diagnosing failures; overlapping route tables can produce loops, unreachable local services, or traffic that never appears in the expected Clash policy.

Keep local development traffic direct

Use NO_PROXY for loopback and local development addresses such as 127.0.0.1, localhost, and ::1. If a local model server, package registry mirror, or callback service runs on your machine, sending it through a remote node can cause connection failures and unnecessary latency.

Hands-On Setup: Route Codex CLI Through Clash

The following procedure uses a local mixed listener on port 7890 and a proxy group named PROXY as examples. Your actual policy group may be called Proxy, GLOBAL, or something else. Policy names are case-sensitive in many configurations, so select the existing group name from the Clash interface instead of pasting this name blindly.

  1. Test Clash first. Start Clash, select a known-good node, and open the client log. Confirm that an ordinary browser request is recorded. If the browser cannot connect, fix the subscription, node, or DNS configuration before involving Codex CLI.
  2. Set a predictable policy. For the first test, temporarily select a stable proxy group rather than a complex automatic group. A url-test group may switch nodes during a session, which can look like intermittent authentication or streaming failures. Restore automatic selection after the basic path works.
  3. Open a new shell. Environment changes in a terminal affect processes started after the change. Using a new shell prevents an old proxy value from being mixed with the new one.
  4. Export the proxy variables. Use the syntax for your operating system. Do not include quotation marks in the value unless your shell requires them.
  5. Check the effective environment. Print the variable names and local port, but avoid printing API keys or complete credential-bearing URLs. Confirm that the value points to the Clash listener and not to an old VPN service.
  6. Run a harmless CLI check. Start with codex --version, then use the CLI's supported login or status command. Watch the Clash log at the same time and verify that the request is assigned to the intended policy.
  7. Run a small coding task. Use a non-sensitive test directory with a short prompt such as asking for a file listing or a simple explanation. This separates network validation from a large repository operation.

On PowerShell, a temporary session can use:

$env:HTTP_PROXY = "http://127.0.0.1:7890"
$env:HTTPS_PROXY = "http://127.0.0.1:7890"
$env:ALL_PROXY = "http://127.0.0.1:7890"
$env:NO_PROXY = "127.0.0.1,localhost,::1"
codex --version

On macOS or Linux with a POSIX-compatible shell, use:

export HTTP_PROXY="http://127.0.0.1:7890"
export HTTPS_PROXY="http://127.0.0.1:7890"
export ALL_PROXY="http://127.0.0.1:7890"
export NO_PROXY="127.0.0.1,localhost,::1"
codex --version

These commands configure the shell session only. They do not change Clash rules, create a new node, or authenticate Codex. Close the terminal or run Remove-Item Env:HTTP_PROXY, Env:HTTPS_PROXY, Env:ALL_PROXY in PowerShell, or unset HTTP_PROXY HTTPS_PROXY ALL_PROXY NO_PROXY in a POSIX shell, when you want to return to a direct test.

If your CLI release documents a dedicated proxy option, prefer the documented option for a one-off test and use environment variables for repeatable sessions. Avoid placing an API key and proxy URL in the same command line because command history and process inspection tools may expose both. A safer pattern is to store non-secret proxy settings in a shell profile and provide credentials through the CLI's supported login store or a protected environment mechanism.

What a successful first test looks like

The CLI starts normally, authentication reaches the service without a timeout, the request appears in Clash logs, and the selected policy remains stable for several short commands. A successful version command by itself is not enough because it may not perform any network request.

Clash Rules and DNS Settings for Codex Sessions

Codex traffic is normally HTTPS, so a domain-based rule is usually the most reliable starting point. Put service-specific rules before broad regional or catch-all rules. If a domain is matched by a direct rule first, later proxy rules cannot override it. Conversely, placing a broad MATCH,DIRECT rule too early will bypass every rule below it.

The following fragment is intentionally a template. Replace the placeholder service domains with the domains documented by the Codex release and account provider you actually use. Do not add guessed domains merely because they contain a familiar product name.

proxy-groups:
  - name: PROXY
    type: select
    proxies:
      - "Stable Node"
      - DIRECT

rules:
  - DOMAIN-SUFFIX,service.example.invalid,PROXY
  - DOMAIN-SUFFIX,auth.example.invalid,PROXY
  - DOMAIN-SUFFIX,telemetry.example.invalid,PROXY
  - DOMAIN-SUFFIX,local.test,DIRECT
  - IP-CIDR,127.0.0.0/8,DIRECT,no-resolve
  - IP-CIDR,192.168.0.0/16,DIRECT,no-resolve
  - MATCH,DIRECT

In a real configuration, the final fallback may be a proxy group instead of DIRECT, depending on whether the goal is domestic-direct and overseas-proxy routing or an explicitly selective Codex-only route. If the rest of your configuration already uses rule providers, add the service domains to the appropriate provider rather than creating duplicate rules in several places.

DNS matters because a domain rule cannot work reliably if the name is resolved incorrectly or outside the intended path. With mihomo, review dns.enable, enhanced-mode, and fake-ip-filter according to the existing configuration. A common desktop arrangement is fake-IP mode with TUN DNS hijacking, but it is not automatically correct for every network. Some corporate networks, local portals, and development services require real addresses or direct resolution.

  • Use a small, known-good set of upstream resolvers instead of adding many entries with unknown behavior.
  • Ensure default-nameserver can bootstrap encrypted DNS hostnames when your configuration uses DoH or DoT.
  • Keep local domains and router management addresses in the appropriate fake-IP filter or direct-resolution list.
  • After changing DNS mode, restart the Clash core or flush the operating system DNS cache before judging the result.
  • Inspect the Clash DNS log and connection log together; a correct proxy rule does not help if the name cannot be resolved.

Do not route every DNS query through a remote node just because Codex needs stable HTTPS access. A focused configuration is easier to audit. The objective is to ensure that the CLI's service domains resolve and connect consistently while local package managers, LAN services, and development containers continue to use the path they require.

Verification and Troubleshooting by Symptom

Run tests in layers. First verify the local listener, then the route, then authentication, and finally the coding workflow. This order prevents an account error from being mistaken for a Clash error.

Symptom Likely cause Action
The CLI ignores the proxy Unsupported variable or stale shell session Open a new shell, set both uppercase and lowercase proxy variables if required by the tool, and inspect the CLI documentation
Clash shows no connection The request is direct, captured by another VPN, or handled by a different process Clear old proxy variables, disable competing tunnel software, and test with explicit variables again
Authentication opens but callback fails Local callback or loopback traffic is being proxied Add loopback addresses to NO_PROXY and keep local callback routes direct
Connection timeout after a node switch Unstable node, overloaded group, or incorrect rule match Select one stable node, inspect the matched policy, and repeat the short test
DNS errors appear before connection errors Upstream DNS, fake-IP, or DNS hijacking mismatch Review the DNS log, bootstrap resolver, and TUN DNS settings
Requests reach the service but are rejected Credential, account, model, quota, or permission issue Test the same account without changing routing and read the CLI's HTTP status or error message

Read Logs Before Changing Five Settings

In Clash, search the connection log for the destination domain and check the policy column. The useful evidence is the matched rule, selected outbound, connection duration, and whether the failure occurs during DNS, TCP, TLS, or application response. If the request is visible under DIRECT when you expected PROXY, fix rule order or the domain list. If it is visible under the correct proxy group but repeatedly fails during TLS, test another node and check the system clock.

On Windows, also check whether a security product is intercepting command-line TLS connections. On macOS, inspect network extension permissions and whether the shell is running inside a different environment from the GUI. On Linux, compare the environment inside the interactive shell with the environment used by a systemd service, IDE terminal, container, or task runner. A proxy variable exported in your terminal does not automatically reach a background service.

Containers, IDEs, and Remote Shells

When Codex CLI runs inside a container, 127.0.0.1 refers to the container itself, not the host running Clash. Use the host gateway address supported by your container runtime, expose the Clash listener to the required interface, and restrict that listener with a firewall. Never bind an unauthenticated proxy listener to a public interface. For an IDE-integrated terminal, verify the IDE's environment separately; it may launch shells without reading the same profile file as your normal terminal.

Remote SSH sessions have the opposite issue: the command runs on the remote machine, so it cannot use the Clash listener on your laptop unless you deliberately build a secure forwarding arrangement. In that case, configure the proxy where the CLI actually runs, not only on the local desktop. Keep the setup limited to trusted interfaces and remove temporary forwarding after the test.

Stable Daily Use Without Over-Proxifying Development

Once the basic connection works, optimize for consistency rather than maximum capture. A fixed, healthy node is often better for authentication and long coding sessions than a latency test that changes nodes every few minutes. Automatic groups are useful, but frequent switching can invalidate long-lived connections or make the same command produce different results.

  • Separate coding traffic from general browsing. Use a dedicated policy group for the service domains and leave ordinary domestic sites on the existing direct rules.
  • Keep package registries intentional. Some package managers read proxy variables differently from Codex CLI. Decide whether registry traffic should be direct or proxied and configure that tool explicitly.
  • Preserve local access. Add loopback, private LAN ranges, local domain suffixes, and internal development hosts to the correct direct or bypass handling.
  • Use TUN only when needed. TUN is valuable for tools that ignore proxy variables, but it can alter routing for browsers, containers, games, and system services that you did not intend to capture.
  • Keep configuration backups free of secrets. A Clash YAML file may contain provider URLs, node credentials, or private addresses. Store it with appropriate file permissions and redact secrets before sharing diagnostic output.
  • Record the working baseline. Note the Clash client, mihomo core, listener port, selected group, DNS mode, and Codex CLI version. Change one item at a time when troubleshooting.

For a team workflow, document proxy variables as optional environment settings rather than hard-coding a personal LAN address into project scripts. A repository script should not silently redirect every developer's traffic to one machine. If a project needs a proxy, use a clearly named local variable and provide a direct mode for environments where no proxy is available.

Never publish credentials in diagnostic output

Before sharing a terminal transcript, remove API keys, authorization headers, subscription URLs, cookie files, callback tokens, and full proxy URLs containing usernames or passwords. Connection logs can also reveal private hostnames and repository paths. Share the error category, timing, matched policy, and sanitized version information instead.

FAQ: OpenAI Codex CLI and Clash

Does enabling Clash system proxy automatically proxy Codex CLI?

Not necessarily. The CLI may read environment variables or use a network library that does not consult the operating system proxy settings. Set the documented proxy variables for the shell that launches Codex, then confirm the request appears in the Clash connection log.

Should I use HTTP, SOCKS5, or TUN mode?

Start with an HTTP mixed listener through HTTPS_PROXY because it is simple to inspect. Use SOCKS5 only when the CLI supports it and the SOCKS listener is stable. Choose TUN when the application ignores proxy variables or when you intentionally need system-level capture.

Why does login work but a coding request still time out?

Login and API requests may use different destinations, so one can match a proxy rule while the other matches DIRECT. Compare both entries in the Clash log, check DNS results, and make sure the selected node remains available. If both use the expected policy, investigate credentials, account limits, model permissions, or service-side errors.

Can I run Codex CLI inside a container through Clash on the host?

Yes, but container loopback is separate from host loopback. Use the container runtime's host gateway address, expose the Clash listener only to the required trusted interface, and set the proxy variables inside the container. Keep local services in NO_PROXY where appropriate.

Continue With a Clean Clash Baseline

A stable Codex CLI session depends on a working client, an explicit proxy path, correct DNS behavior, and rules that match the actual service destinations. If Clash is not installed yet, start with the platform build, then follow the basic import and proxy workflow before adding service-specific rules.

Download the Clash Client

Rule-based routing needs a client to take over traffic first. Head to the download hub, pick a client for your platform, then come back to this guide to finish setting up system proxy or TUN takeover.

Download Clash