Why Claude Code and Clash Verge belong in the same terminal setup
Searches such as Claude Code terminal proxy, Claude Code with Clash Verge, and Anthropic API connection failed usually appear after the command-line workflow works once and then becomes unreliable. The browser may open normally, while Claude Code reports a timeout, hangs during a long response, fails during authentication, or loses a connection halfway through a file-editing task. In many cases, Claude Code itself is not the first component to investigate. The real problem is that the terminal process, the Clash client, and the selected route are not using the same network path.
Clash Verge gives you a practical control plane for that path. You can import a compatible subscription, inspect live connections, select a suitable proxy group, and create rules for Anthropic-related traffic without forcing every application on your computer through the same tunnel. The terminal still needs explicit environment variables, however. A system proxy toggle can cover browsers and some desktop applications while leaving a shell session on DIRECT. That difference explains why Claude Code can fail even when Clash Verge appears to be connected.
This guide assumes no previous Clash experience. It covers the full sequence: prepare a profile, import it into Clash Verge, verify the local mixed-port listener, export proxy variables for the current shell, test connectivity, choose routing rules, and troubleshoot the common cases where authentication, DNS, TLS, or node quality is the actual cause. Use only subscriptions and network access that you are authorized to use, and avoid sharing configuration URLs or access tokens in screenshots and support tickets.
Understand the three layers before changing settings
A reliable setup becomes much easier when you separate the jobs performed by each layer. Clash Verge is the local proxy client and graphical control surface. Mihomo, or the core bundled with your particular Clash Verge build, processes the profile and applies rules. Claude Code is the terminal application that must be told where the local proxy listener is located.
| Layer | What it controls | What to verify |
|---|---|---|
| Clash Verge | Profiles, modes, proxy groups, logs, and local ports | The client is running and the intended profile is active |
| Mihomo core | DNS handling, rule matching, connections, and node selection | The core is healthy and requests are not unexpectedly DIRECT |
| Terminal shell | Environment inherited by Claude Code and its child processes | HTTPS_PROXY, HTTP_PROXY, and lowercase variants point to the local port |
| Anthropic service | Authentication, account access, API limits, and upstream responses | Credentials are valid and the service accepts the request |
These layers can disagree. For example, Clash Verge may show a selected node, but Claude Code may not use it because the shell has no proxy variables. Conversely, the shell may point correctly to port 7897, yet the active profile may route the request directly. A third possibility is that traffic reaches Anthropic successfully but the account or authentication flow rejects it. Always identify which layer is failing before replacing configuration files.
Clash Verge also has several operating modes. Rule mode is normally the best starting point because it sends matching domains through a proxy while leaving ordinary local traffic alone. Global mode sends nearly everything through the selected proxy and is useful as a short diagnostic test. Direct mode intentionally bypasses proxies and should not be used when testing a terminal proxy configuration. TUN mode is a separate system-level interception method; it can help applications that ignore environment variables, but it introduces additional DNS, permission, and routing variables.
Prepare and import a Clash Verge profile safely
Claude Code does not supply proxy servers by itself. You need a valid Clash-compatible profile from a provider you trust or from infrastructure you manage. The profile may be delivered as a remote subscription URL, a YAML file, or a converted configuration. A URL containing a token should be treated like a password: do not paste it into a public repository, shell history shared with other users, or an issue tracker.
- Open Clash Verge. Confirm that the application is the client you intend to use and that its core starts without an error. On first launch, your operating system may ask for permission to create a helper or change proxy settings. Read the prompt and approve only the component you recognize.
- Open the Profiles view. Use the provider’s subscription URL or import a local YAML file. If the URL contains spaces or has been copied from a formatted document, paste it into a plain-text editor first and remove accidental line breaks.
- Download and activate the profile. A successful download does not always mean the profile is active. Look for the active indicator and confirm that proxy groups and nodes are populated.
- Inspect the configuration. Check whether the profile defines a mixed port, HTTP port, or SOCKS port. Many installations use a mixed port such as
7897, but you must use the value shown in your own client rather than copying a number from a tutorial. - Choose a proxy group. Select a healthy automatic, fallback, or manually controlled group. If the group is empty, the subscription may have expired, the provider format may be incompatible, or the profile may have failed to parse.
Do not edit a downloaded provider profile blindly. Providers often regenerate it, and your changes may disappear during the next update. If you need permanent custom rules, use the profile’s supported override or merge mechanism. Keep a backup of any local override and record why each custom rule exists. A small, understandable override is easier to debug than a large copied ruleset whose precedence you cannot explain.
Before testing Claude Code, open the Clash Verge logs or connections panel and create a simple request from a browser or command-line tool. The purpose is not to prove that every service works; it is to establish that the core is listening and that at least one selected node can complete a normal HTTPS connection. If all requests fail, stop and fix the profile or node before investigating Claude Code.
Set proxy variables for Claude Code
The most portable way to connect a terminal application to Clash Verge is to export proxy variables in the same shell that launches Claude Code. A mixed port generally accepts both HTTP proxy requests and SOCKS-style traffic, which makes it a convenient first choice. If your client exposes separate ports, use the appropriate listener and scheme documented by that client.
On macOS or Linux, a typical temporary setup looks like this:
export HTTP_PROXY=http://127.0.0.1:7897
export HTTPS_PROXY=http://127.0.0.1:7897
export ALL_PROXY=socks5://127.0.0.1:7897
export http_proxy="$HTTP_PROXY"
export https_proxy="$HTTPS_PROXY"
export all_proxy="$ALL_PROXY"
On Windows PowerShell, the equivalent session-only variables are:
$env:HTTP_PROXY = "http://127.0.0.1:7897"
$env:HTTPS_PROXY = "http://127.0.0.1:7897"
$env:ALL_PROXY = "socks5://127.0.0.1:7897"
$env:http_proxy = $env:HTTP_PROXY
$env:https_proxy = $env:HTTPS_PROXY
$env:all_proxy = $env:ALL_PROXY
Replace 7897 with the mixed port shown by Clash Verge. The 127.0.0.1 address means the local machine, not a remote server. Keep the scheme consistent with the listener. A common mistake is using https://127.0.0.1:7897 merely because the destination uses HTTPS. Most local Clash HTTP proxy listeners are addressed with http://; the proxy then creates the encrypted connection to the destination through the HTTP CONNECT method.
Test the variables before launching Claude Code. A lightweight check can reveal whether the shell can reach the local listener:
curl -I https://api.anthropic.com
The response code is less important than the connection behavior at this stage. A 401 or another application-level response can still prove that the request reached the upstream service. A connection-refused error usually indicates that Clash Verge is closed, the port is wrong, or the core is listening only on another address. A name-resolution error suggests DNS handling rather than credentials. Check the Clash connections panel at the exact moment of the test and confirm that the hostname appears there.
Session-only exports disappear when you close the terminal. That is often preferable while diagnosing because it avoids silently changing unrelated tools. Once the setup is stable, place the variables in a shell profile such as ~/.zshrc, ~/.bashrc, or a carefully scoped PowerShell profile. If you work on multiple networks, consider a small command or script that enables and disables the variables explicitly instead of forcing every command through the proxy permanently.
Remember that environment variables are inherited at process creation time. If Claude Code is already running in another terminal, changing variables in a new window will not alter the old process. Restart the command after changing the shell environment. GUI-launched terminals, IDE integrated terminals, and remote SSH sessions may each have separate environments, so verify the variables in the exact place where you run Claude Code.
Route Anthropic traffic deliberately and select nodes by evidence
Start with Rule mode and observe the connections generated by Claude Code. Do not begin by adding every possible AI domain from an internet list. Hostnames change, authentication flows may use more than one service, and broad rules can unintentionally route local tools or package registries through a slow node. The connections panel is more reliable than an old snippet because it shows what your current version actually contacted.
When the first request runs, look for the destination hostname, the matched rule, the process name if available, and the selected proxy group. A healthy observation should answer four questions: did the request reach Clash Verge, which rule matched it, which node handled it, and did the connection close normally or remain in a retry loop?
- Direct request visible: the shell reached Clash, but the active ruleset intentionally chose DIRECT. Review rule order, domain suffix rules, and the final catch-all policy.
- No request visible: Claude Code may not be using the exported variables, may be using a separate process environment, or may be failing before network access begins.
- Repeated retries: the node, DNS path, or upstream connection may be unstable. Try another node in the same group and compare logs.
- Successful short calls but failed streaming: investigate latency, idle timeouts, connection reuse, and node congestion. Long model responses expose weaknesses that a quick header request will not.
Choose nodes by measured behavior rather than a flag, name, or advertised speed. For Claude Code, a node with moderate bandwidth and stable long-lived HTTPS sessions is often better than a fast node that resets connections after a few seconds. Compare handshake time, time to first response, failure frequency, and sustained streaming behavior. Test at the time you normally work because congestion can vary by hour.
Automatic groups can be convenient, but they may switch nodes during a task or after a health check. That can make an incident difficult to reproduce. During diagnosis, temporarily select one known-good node. Once the request is stable, return to an automatic or fallback group if you need resilience. Keep the change narrow: you are testing a hypothesis, not permanently rewriting your entire network policy.
Some users turn on TUN mode immediately because it feels more comprehensive. TUN can help binaries that ignore proxy variables, but it should be a second-line option for this terminal workflow. First prove that explicit variables work. If TUN is enabled while shell variables are also present, traffic may take a path you did not intend, and troubleshooting becomes harder. Avoid running multiple VPN clients or system-wide packet filters at the same time unless you understand their interaction.
Troubleshoot failures without guessing
Authentication and authorization errors
An HTTP 401, invalid token message, or account authorization failure is not automatically a proxy problem. If the request appears in Clash Verge and receives a prompt response from Anthropic, routing may already be working. Check the credential source used by Claude Code, the account or organization context, and whether an expired login session needs to be renewed. Never place a real token directly into a shared configuration file or a command that will be stored in shell history.
Timeouts and connection resets
Compare a short request with a longer generation. If both fail immediately, inspect the local port, profile status, and selected node. If only long responses fail, examine node stability and idle timeouts. A congested relay can pass DNS and TLS negotiation yet reset a streaming connection later. Try a different node, disable unnecessary automatic switching during the test, and check whether the same failure occurs on another network.
DNS and TLS symptoms
When the browser resolves a hostname but the terminal does not, the two applications may be using different DNS paths. Clash Verge’s DNS mode, fake-IP behavior, operating-system resolver, and shell tool can all affect the result. Avoid changing several DNS settings at once. First record the hostname and error, then test whether the request appears in the Clash log. TLS errors can also come from certificate inspection by a corporate firewall, an outdated trust store, or a tool that does not trust the same certificate authorities as your browser. Do not “fix” certificate failures by disabling verification globally.
Confirm the environment actually reaches Claude Code
Print the proxy variables in the same terminal where you launch the command. Check for an old port, a trailing quotation mark, an unexpected NO_PROXY entry, or a shell configuration that overwrites values later in startup. A broad NO_PROXY setting can bypass the proxy for domains you expected to route through Clash. Conversely, removing every bypass can disrupt local development services. Keep exclusions limited to loopback addresses, private development hosts, and destinations that genuinely must remain local.
After each meaningful change, use the same test command, the same node, and the same profile. Change one variable at a time and note the result. This turns a vague “Claude Code is random” complaint into a small comparison: direct versus proxied, node A versus node B, Rule versus Global, and short request versus streaming request. Once you have a stable baseline, restore Rule mode and confirm that the minimum required domains still match the intended policy.
A repeatable daily workflow for terminal sessions
A dependable setup should not require rebuilding the configuration every morning. Start Clash Verge before launching Claude Code, check that the expected profile is active, and confirm that the selected group has at least one usable node. If you use a remote subscription, update it on a deliberate schedule rather than during an important coding session. Profile updates can alter group names, rules, ports, and DNS behavior.
Use a small checklist when a task matters:
- Confirm Clash Verge is running and the core status is healthy.
- Confirm the shell variables point to the current local listener.
- Run one harmless connectivity check and inspect the matching connection.
- Select a stable node or verify the automatic group’s current selection.
- Launch Claude Code from that same terminal.
- Keep the logs available if a long operation begins to stall.
For teams, document the conceptual setup rather than distributing private subscription links. Write down the expected local port, the supported shell variables, the command used for a safe connectivity check, and the symptoms that indicate authentication rather than routing. Each developer should obtain credentials and subscriptions through the approved channel. This keeps the troubleshooting process reproducible without turning a shared setup document into a secret store.
Also consider project boundaries. Claude Code may invoke package managers, Git remotes, local development servers, or cloud APIs besides Anthropic. Routing all of them through one proxy may add latency or violate organizational policy. Use narrow rules and explicit exceptions where appropriate. If a project has its own network requirements, record them alongside the project documentation so a future profile update does not surprise the team.
Compared with one-click VPN clients that hide routing decisions, Clash Verge can require more initial inspection but gives you visible connections, selectable nodes, rule precedence, and shell-compatible local ports. Other desktop proxy tools may simplify the first toggle yet offer limited visibility when a CLI bypasses the system proxy or when a long stream resets. For Claude Code, that observability is the practical advantage: you can distinguish an incorrect environment variable from a DIRECT rule and a weak node instead of restarting blindly. If you want to apply this workflow with a supported client on your platform, download Clash and then reproduce the checks above with your own authorized profile.