Merge multiple Claude API gateways into one local endpoint. Automatic failover · sticky prompt-cache routing · model aliasing · zero dependencies.
English · Tiếng Việt
You have accounts on several third-party Claude gateways. Each one has its own base URL, its own API key, and a slightly different model catalog. When one runs out of credit or goes down, you edit your config and restart. When you switch gateways mid-conversation, you silently lose your prompt cache and every request gets slower and more expensive.
One local endpoint that speaks the Anthropic API. Point Claude Code at it once and forget the gateways exist.
┌──────────────────────────────────┐
│ Free Claude Gateway │
│ │
Claude Code ──────────▶│ auth ─ model alias ─ router │
(or any Anthropic │ │ │
compatible client) │ ▼ │
│ circuit breaker + failover │
└────┬────────┬────────┬───────┬───┘
│ │ │ │
gorouter justwoker agent tabitoken
router
- Automatic failover. A gateway returns 502, times out, or runs out of credit? The next one takes over in the same request. The client never sees it.
- Sticky routing keeps your cache warm. Each gateway has its own prompt cache. One conversation stays pinned to one gateway, so
cache_read_input_tokenskeeps hitting. - Model aliasing. Claude Code asks for
claude-haiku-4-5-20251001; no gateway has it. The proxy maps it to a model that actually exists instead of returning 404. - Circuit breaker. A dead gateway is skipped entirely — no network call, no waiting — and re-probed automatically once its cooldown expires.
- Honest streaming semantics. Once the first byte reaches the client, failover is impossible. The proxy peeks the first chunk before committing so most failures are still recoverable, and when one isn't, it closes the stream with a valid SSE error instead of a truncated response.
- Zero dependencies.
node:httpand the built-infetch. Nothing to audit, nothing to update.
These four gateways are pre-configured. All are New API instances (a one-api fork) and expose both the Anthropic and OpenAI wire formats.
The links below are my referral links — signing up through them gives you extra starting credit (and gives me some too). Plain links are in providers.md if you'd rather not use them.
| Gateway | Sign up | Models | Pricing (measured) | Notes |
|---|---|---|---|---|
| gorouter.app | Register → | 4 Claude models | per-request 0.2–0.3 — cheapest |
Cloudflare blocks curl/* user agents |
| api.justwoker.icu | Register → | 4 Claude models | /api/pricing empty, unknown |
No user-agent gate |
| agentrouter.org | Register → | claude-opus-5, claude-opus-4-8, gpt-5.6-sol |
per-token, ratio 1.0–1.5, completion ×5 |
No -thinking variants. Requires a claude-cli/... user agent |
| tabitoken.com | Register → | 4 Claude models | per-request 0.5–0.8 |
Most expensive of the four |
"4 Claude models" means claude-opus-5, claude-opus-5-thinking, claude-opus-4-8, claude-opus-4-8-thinking.
You do not need all four. Any single gateway works — the rest simply give you failover. A gateway with no key in .env is marked disabled at boot and skipped; it never blocks the others.
Adding your own gateway. Any New API / one-api instance works. Add an entry to
PROVIDER_DEFSinsrc/config.jswith itsbaseUrl, key env var, and model list.
Requires Node 22 or newer (for built-in fetch and process.loadEnvFile).
git clone https://github.com/Hungvip69/Free-Claude-Gateway.git
cd Free-Claude-Gateway
cp .env.example .env # Windows: copy .env.example .env
npm run keygen # prints a PROXY_KEY — paste it into .env
# Paste at least one gateway key into .env, then:
npm startFree Claude Gateway http://127.0.0.1:8787
providers up: gorouter, justwoker, agentrouter
providers down: tabitoken (no key)
Verify without spending a single token:
curl http://127.0.0.1:8787/health
curl -H "x-api-key: $PROXY_KEY" http://127.0.0.1:8787/v1/modelsGET /v1/models is free on all four gateways — the proxy uses it to discover each one's real catalog at boot.
Add to ~/.claude/settings.json:
{
"env": {
"ANTHROPIC_BASE_URL": "http://127.0.0.1:8787",
"ANTHROPIC_AUTH_TOKEN": "sk-proxy-your-key-from-npm-run-keygen"
}
}Restart Claude Code. That's it — no ANTHROPIC_DEFAULT_*_MODEL needed, the alias layer handles model names.
export ANTHROPIC_BASE_URL=http://127.0.0.1:8787
export ANTHROPIC_API_KEY=sk-proxy-your-keyfrom anthropic import Anthropic
client = Anthropic(
base_url="http://127.0.0.1:8787",
api_key="sk-proxy-your-key",
)| Route | Auth | Behaviour |
|---|---|---|
POST /v1/messages |
✅ | Anthropic native. Streaming and non-streaming |
POST /v1/chat/completions |
✅ | OpenAI compatible. Bearer auth upstream, data: [DONE] passed through |
POST /v1/messages/count_tokens |
✅ | Handled locally — no gateway implements this endpoint |
GET /v1/models |
✅ | Union of every enabled gateway's catalog, cached 5 minutes |
GET /health |
❌ | Liveness. Returns 503 when no gateway is usable |
GET /stats |
✅ | Breaker states, negative cache, sticky map, p50/p95 latency, token totals |
Auth accepts your PROXY_KEY via either x-api-key or Authorization: Bearer. /health is the only unauthenticated route, and it exposes no key material.
Claude Code requests real Anthropic model IDs. The gateways only carry five. Without mapping, every small-model call — conversation titles, summaries, background chores — returns 404.
| Client requests | Sent upstream |
|---|---|
claude-opus-5, claude-opus-4-8, either -thinking, gpt-5.6-sol |
unchanged |
anything matching haiku |
claude-opus-4-8, thinking stripped |
anything matching sonnet |
claude-opus-5, thinking stripped |
anything matching opus |
claude-opus-5, upgraded to -thinking if the request sets thinking.type = "enabled" |
gpt-*, o1/o3/o4-*, chatgpt-*, codex-* |
gpt-5.6-sol (agentrouter only) |
| anything else | claude-opus-5 |
A trailing [1m] suffix is stripped before matching. When a request is downgraded to a non-thinking model, only the top-level thinking field is removed — thinking content blocks in the conversation history are left untouched, since deleting those would corrupt prior assistant turns.
Requesting a -thinking model automatically excludes agentrouter from routing, because it doesn't carry those variants.
Cost implication, stated plainly. No gateway sells a haiku-class model, so every cheap call becomes an opus call. Your real spend is higher than it would be on first-party Anthropic for small work. Every log line records
client_modelandresolved_modelso you can see exactly what you're paying for. SettingCLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1in Claude Code suppresses much of this traffic.
The routing key is sha256(system prompt + first user message + resolved model). Both components are immutable for the life of a conversation — Claude Code only appends to the tail — so a conversation stays on one gateway across every turn.
This matters because each gateway maintains its own prompt cache. Bouncing between them mid-conversation drops cache_read_input_tokens to zero, which is both slower and more expensive than any load imbalance.
New conversations are distributed across gateways by rotating the candidate list by the key's hash — deterministic per conversation, but spread across your accounts rather than hammering the first one.
After a failover, the conversation re-pins to the new gateway. Its cache just warmed up; flapping back would throw that away.
New API does not use HTTP status codes conventionally, so each case is classified explicitly:
| Upstream response | Classification | Action |
|---|---|---|
500 + body matching field X is required / invalid_request |
client error | Relay verbatim. No failover — retrying a malformed request across four gateways just burns money |
503 + 无可用渠道 |
model unsupported | Negative-cache (gateway, model) for 5 min. Breaker stays closed |
403 with empty body |
model unsupported | Same — gorouter/justwoker enforce a model allowlist at the Cloudflare edge |
401 |
dead key | Open breaker immediately for 10 min |
429 |
rate limited | Open breaker for Retry-After (capped at 15 min) |
400, 404, 413, 422 |
client error | Relay verbatim |
502, 504, 52x, opaque 500, network error, timeout |
gateway fault | Count toward breaker, try next gateway |
200 with an error envelope in the body |
gateway fault | Try next gateway |
Two of these deserve emphasis. The 500-as-validation rule is what stops a single malformed request from being retried against every gateway you own. The model-unsupported rules are kept separate from the circuit breaker because "this gateway lacks this model" is per-model information — a gateway missing claude-opus-5-thinking is still perfectly healthy for claude-opus-5.
3 consecutive failures
┌────────┐ ────────────────────▶ ┌────────┐
│ CLOSED │ │ OPEN │ ── no network call at all
└────────┘ ◀──────────┐ └────────┘
▲ │ │ cooldown elapsed
│ │ ▼
│ probe passes │ ┌───────────┐
└────────────────┴────────│ HALF-OPEN │ ── exactly one probe admitted
probe fails └───────────┘
(cooldown × 2)
Cooldown starts at 60 s and doubles on each failed probe, capped at 15 minutes. A 401 jumps straight to a 10-minute cooldown — retrying a bad key sooner is pointless — but still auto-probes when it expires, so topping up an account or fixing a key recovers without a restart.
Writing the first byte to the client is irreversible. HTTP gives you no way to un-send it, so after that moment there is no failover. The design makes this boundary explicit rather than pretending otherwise.
Before committing, the proxy reads the first chunk of the upstream stream while holding the client response untouched. If that chunk is an SSE error event, or the gateway returned 200 and immediately closed, or the read times out — the attempt is discarded and the next gateway is tried. The client sees nothing unusual. This is the common gateway failure mode, and it's fully recoverable.
After committing, if the upstream dies mid-stream, the proxy keeps the bytes already delivered, appends one valid SSE error frame, and closes cleanly:
event: error
data: {"type":"error","error":{"type":"api_error","message":"upstream stream aborted (provider=gorouter, request_id=...)"}}
The Anthropic SDK surfaces that as a normal APIError, so Claude Code shows a failed turn you can retry — instead of a truncated stream that fails JSON parsing. No message_stop is fabricated. The log records error: "stream_aborted", so these are countable rather than mysterious.
A separate consequence worth knowing: failover is not free even when it succeeds. A gateway that emits an error frame may have already generated and billed tokens, and per-request-billed gateways may charge for a failed attempt outright. This is why MAX_ATTEMPTS defaults to 3 rather than trying everything.
Everything lives in .env. Only PROXY_KEY and at least one gateway key are required.
| Variable | Default | Purpose |
|---|---|---|
PROXY_KEY |
— | Required. The key clients must present. npm run keygen generates one |
HOST |
127.0.0.1 |
Bind address. Anything else prints a security warning |
PORT |
8787 |
Bind port |
UPSTREAM_UA |
claude-cli/2.0.1 (external, cli) |
User agent sent upstream — see below |
AGENTROUTER_KEY |
— | Gateway keys. Empty or absent ⇒ that gateway is disabled |
TABITOKEN_KEY |
— | |
GOROUTER_KEY |
— | |
JUSTWOKER_KEY |
— | |
MAX_ATTEMPTS |
3 |
Max gateways tried per request |
HEADER_TIMEOUT_MS |
60000 |
Wait for response headers and the first stream chunk |
STREAM_IDLE_TIMEOUT_MS |
120000 |
Max silence between two stream chunks |
MAX_BODY_BYTES |
33554432 |
Request body limit (32 MB) |
LOG_ENABLED |
1 |
Set 0 to disable jsonl logging (/stats still works) |
LOG_DIR |
logs |
Log directory |
<GATEWAY>_BASE_URL |
— | Override a base URL, e.g. GOROUTER_BASE_URL |
agentrouter rejects any client whose user agent doesn't match claude-cli/<semver> (external, <client>) — it returns 401 unauthorized_client_error. The same user agent also satisfies the Cloudflare rules on gorouter and tabitoken, which block curl/*.
The proxy sits between Claude Code and these gateways, so it declares what the traffic actually is. It's a compatibility shim, and it's a config variable rather than a hardcoded string precisely because gateways can tighten their checks at any time.
logs/requests-YYYY-MM-DD.jsonl — one line per request:
{
"ts": "2026-08-23T14:47:31.261Z",
"id": "677d651b-72d2-4803-8dcb-9bf220a304e5",
"route": "/v1/messages",
"client_model": "claude-haiku-4-5-20251001",
"resolved_model": "claude-opus-4-8",
"thinking": false,
"provider": "gorouter",
"sticky_hit": true,
"stream": true,
"status": 200,
"attempts": [
{ "provider": "agentrouter", "status": 503, "class": "model-unsupported", "ms": 412 }
],
"ttfb_ms": 890,
"ms": 14300,
"bytes": 48211,
"usage": {
"input_tokens": 12043,
"output_tokens": 301,
"cache_read_input_tokens": 11800,
"stop_reason": "end_turn"
},
"error": null
}Redaction is structural, not best-effort. The logger accepts only an explicit field allowlist, so a gateway object — and therefore a key — can never be serialized. Every upstream-sourced string passes a scrubber that replaces sk-… tokens with [redacted], because New API sometimes echoes the offending token back in Invalid token responses. Request and response bodies are never written, and there is no body-logging mode to accidentally enable. A test asserts no configured key appears anywhere in the output.
GET /stats gives you the live picture: per-gateway breaker state and cooldown, the (gateway, model) unsupported map, sticky map size and hit rate, p50/p95 latency, and cumulative token counts.
Watch cache_read_input_tokens there. It tells you whether sticky routing is actually buying you anything — New API load-balances internally across its own upstream channels, so pinning to one gateway doesn't strictly guarantee the same underlying account. If that number stays at zero, sticky routing isn't helping and the TTL is worth revisiting.
- Binds to
127.0.0.1by default. SettingHOSTto anything else prints a loud warning at boot. This endpoint spends real money, guarded by a single static key with no rate limiting — don't expose it without a real auth story in front. - Client credentials never reach upstream. Outbound headers are built from an allowlist, not filtered by a denylist.
cookie,host,authorization,x-api-key,x-forwarded-*,cf-*, SDK telemetry headers, and all hop-by-hop headers are dropped and rebuilt from scratch. - One auth header, never both.
x-api-keyon Anthropic routes,Authorization: Beareron OpenAI routes. Sending both is what makes the real Anthropic API return 401. set-cookieis stripped in both directions.- Gateway keys sit in plaintext in
.env..gitignorecovers it, but any process on the machine that can read the file can read the keys.
npm test # 135 tests, zero real upstream calls
npm run test:watch
npm run dev # node --watchThe suite never touches a real gateway. test/helpers/fake-upstream.js is a scriptable New API emulator built on node:http — per-response status, body, headers, delay, SSE chunk sequences, mid-stream socket destruction, and a hang mode for idle-timeout tests. It records every request it receives, so the most valuable assertions are the negative ones: gateway #2 was never called.
The circuit breaker takes an injectable clock, so cooldown and half-open tests advance virtual time instead of sleeping.
| Module | Responsibility |
|---|---|
src/config.js |
Gateway topology, .env parsing, boot validation |
src/models.js |
Alias table, catalog probing, merged model list |
src/auth.js |
Local key check via hashed timingSafeEqual |
src/classify.js |
Outbound header allowlist, upstream error classification |
src/breaker.js |
Circuit breaker state machine, negative-capability cache |
src/router.js |
Sticky key derivation, candidate ordering |
src/proxy.js |
Failover loop, streaming commit latch |
src/usage.js |
Token usage extraction from JSON and SSE |
src/tokens.js |
Local count_tokens estimation |
src/log.js |
jsonl writer, redaction, in-memory stats |
src/server.js |
Routing table, graceful shutdown |
No module has import-time side effects — every one is a pure function or a factory — so tests instantiate the whole app in-process on port 0.
- Post-commit stream failures are unrecoverable. Inherent to HTTP streaming, not a bug. Mitigated by the first-chunk peek and a clean in-band error frame.
count_tokensis an estimate. No gateway implements the endpoint and Anthropic doesn't publish its tokenizer, so it's achars / 3.5approximation. Fine for context measurement, not for billing predictions.- Single process, in-memory state. Breaker, sticky map, and stats reset on restart and aren't shared across instances. Correct for a local single-user proxy; out of scope to fix.
- Gateway balances aren't observable. All four report placeholder
soft_limit_usd/hard_limit_usdvalues, so health is failure-driven — a gateway can be silently out of credit until it starts erroring. - Model IDs are gateway-specific.
claude-opus-5is not a real Anthropic model ID; it exists only in these catalogs and can change without notice. The boot probe surfaces drift quickly. - The empty-body
403rule is inferred. Measured: valid model + bad body ⇒ 500; unknown model + bad body ⇒ 403 with zero content length. If it turns out to be a rate limit instead, a gateway gets wrongly skipped for 5 minutes — acceptable, since the TTL is short and the breaker stays closed.
Issues and pull requests welcome. Please keep the two hard constraints intact:
- Zero runtime dependencies.
- No test may call a real gateway. Use the fake upstream.
Run npm test before opening a PR.
Built for Claude Code. The gateways are New API instances, a fork of one-api.