跳到正文
DEV Community· AlwaysAgent·· 2 小時前AI 評分62

OpenRouter API 金鑰如何用於 Claude Code

How to use an OpenRouter API key in Claude Code

AI 導讀

要在 Claude Code 使用 OpenRouter API 金鑰,需將 ANTHROPIC_BASE_URL 設為 https://openrouter.ai/api,將金鑰放入 ANTHROPIC_AUTH_TOKEN,並把 ANTHROPIC_API_KEY 留空,再登出 Anthropic 帳戶。

正文

Originally published at alwaysagent.app. The original is kept up to date.

OpenRouter has an official Claude Code integration. Four environment variables and a logout are all it takes. This guide covers the full config, verification, model switching, costs, troubleshooting, server setups, and the open-source Claude Code Router.

The short answer: four variables

To use an OpenRouter API key in Claude Code, point ANTHROPIC_BASE_URL at https://openrouter.ai/api, put your key in ANTHROPIC_AUTH_TOKEN, set ANTHROPIC_API_KEY to an empty string, and log out of any Anthropic account. This is the setup described in OpenRouter's official Claude Code integration guide.

Terminal

export OPENROUTER_API_KEY="<your-openrouter-key>"
export ANTHROPIC_BASE_URL="https://openrouter.ai/api"
export ANTHROPIC_AUTH_TOKEN="$OPENROUTER_API_KEY"
export ANTHROPIC_API_KEY=""
  • The base URL is https://openrouter.ai/api, with no /v1.
  • The key goes in ANTHROPIC_AUTH_TOKEN, which Claude Code sends as Authorization: Bearer. ANTHROPIC_API_KEY is sent as x-api-key and treated as a direct Anthropic credential, so it must stay blank.
  • Define OPENROUTER_API_KEY before the line that references it, or the token expands to nothing and you get an auth error.

Shell variables or settings.json?

Both work. Shell variables are the fastest way to try it; settings.json is better when you want the config to apply however claude is launched.

Option 1: shell profile

Add the exports above to ~/.zshrc, ~/.bashrc, or your fish config, then reload it with source ~/.zshrc or open a new terminal. OpenRouter also suggests an optional CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1, which turns on a gateway model picker (more on that below).

Option 2: settings.json

Claude Code reads an env block from its settings files. Use ~/.claude/settings.json for all projects, or .claude/settings.local.json for one project.

~/.claude/settings.json

{
  "env": {
    "ANTHROPIC_BASE_URL": "https://openrouter.ai/api",
    "ANTHROPIC_AUTH_TOKEN": "<your-openrouter-key>",
    "ANTHROPIC_API_KEY": "",
    "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "1"
  }
}
  • Never put the key in a project's .claude/settings.json. Anthropic's docs warn that this file is committed and shared with everyone who clones the repo.
  • Don't rely on a project .env file. OpenRouter notes the native installer does not read it.
  • If the same variable is set both in your shell and in a settings env block, Anthropic's docs say the settings value applies. To avoid confusion, configure it in one place only.

Step-by-step setup and verification

The whole process takes a few minutes, and /status tells you whether it worked.

  1. Install Claude Code — Use the native installer from Anthropic (curl -fsSL https://claude.ai/install.sh | bash on macOS, Linux, and WSL) or npm install -g @anthropic-ai/claude-code.
  2. Create an OpenRouter key — Add credits and create an API key in your OpenRouter dashboard.
  3. Set the variables — Use either option above, not both.
  4. Log out of Anthropic — If you ever signed in with a claude.ai account, run /logout, quit, and start claude again. The gateway credential takes precedence over a saved login, but logging out avoids auth-conflict warnings.
  5. Check /status — Run claude, then /status. You should see Auth token: ANTHROPIC_AUTH_TOKEN and Anthropic base URL: https://openrouter.ai/api. If the auth line names ANTHROPIC_API_KEY or a Claude account, reload your shell and restart claude.
  6. Send a prompt and check the dashboard — Send any message. A normal reply confirms it works, and the request should appear in your OpenRouter Activity dashboard with the model name.

How to choose and switch models

Claude Code picks models by alias (opus, sonnet, haiku), and you can map each alias to an OpenRouter model ID with environment variables. Anthropic notes that ANTHROPIC_BASE_URL changes where requests go, not which model answers them, so the mapping is what decides the model.

  • Inside a session: /model opens the picker; /model sonnet switches immediately.
  • At startup: claude --model opus applies to that session only.
  • Persistently: set "model" in your settings file, or ANTHROPIC_MODEL in the environment.

To pin which OpenRouter model each alias resolves to, set these in your shell or env block:

Terminal

export ANTHROPIC_DEFAULT_OPUS_MODEL="<openrouter-model-id>"
export ANTHROPIC_DEFAULT_SONNET_MODEL="<openrouter-model-id>"
export ANTHROPIC_DEFAULT_HAIKU_MODEL="<openrouter-model-id>"
export CLAUDE_CODE_SUBAGENT_MODEL="<openrouter-model-id>"

Use the exact IDs from the OpenRouter model list, because names and versions change often. OpenRouter's guide also documents "latest" style aliases for the Claude families; check its page for the current spelling. After setting them, open /model and confirm the expected entries appear, then check the model column in the OpenRouter dashboard.

ANTHROPIC_DEFAULT_HAIKU_MODEL also covers background tasks, so pin it too if you want predictable costs. ANTHROPIC_SMALL_FAST_MODEL is deprecated.

Gateway model picker

With CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1, Claude Code asks the gateway for its model list at startup and adds those names to /model. OpenRouter says this shows a curated set of top-ranked models rather than the full catalog, and that pinning a model through the variables above bypasses it. Restart Claude Code to refresh the list.

Context window

OpenRouter's guide says Claude Code assumes a 200k context unless the model name ends in [1m], and that OpenRouter strips the marker before routing. If your context seems stuck at 200k, add the suffix to model IDs that support 1M.

Costs and credits

With OpenRouter, you pay OpenRouter per token from your credit balance; there is no Claude subscription quota involved. Anthropic's docs confirm that once a gateway credential is set, requests no longer count against a claude.ai plan.

  • Per-request view: OpenRouter's Activity dashboard shows usage, cost, and the model for each request.
  • Budgets: OpenRouter says teams can set spending limits and allocate credits. Keep your balance topped up, since an empty balance shows up as request errors.
  • In-terminal cost: OpenRouter publishes an optional status line script (in its openrouter-examples repo, under claude-code) that shows session cost in Claude Code. It is configured through the statusLine entry in ~/.claude/settings.json, and replaces any status line you already have.
  • Prompt logging: OpenRouter says prompts are not logged unless you opt in.

Troubleshooting common errors

Most failures come from a leftover credential, a blank-token expansion, or a model that does not behave like Claude. Work through these in order.

Symptom Likely cause Fix
Auth error or invalid key ANTHROPIC_API_KEY is not empty, or the token expanded to blank Set ANTHROPIC_API_KEY="", define the key variable first, reload the shell, check /status
Auth-conflict warning at startup A saved claude.ai login plus a gateway credential Run /logout, or unset the variable to go back to the login
Still logged into Anthropic after /logout A real ANTHROPIC_API_KEY is exported in your shell profile /logout only clears the cached login, not shell variables; blank the variable and reload
"Model not found" for a model ID Auth conflict, or a wrong model ID OpenRouter lists this as usually an auth conflict; fix auth first, then verify the ID in OpenRouter's model list
401 errors Credential in the wrong variable Use ANTHROPIC_AUTH_TOKEN for bearer-style gateways such as OpenRouter
Asked to log in even though the key works The env block is in a project settings file, which applies only after first-run setup and the trust prompt Put it in ~/.claude/settings.json or a shell export
Context stuck at 200k Model ID lacks [1m] Append [1m] on models that support it
400 errors about unrecognized fields An upstream provider rejects fields Claude Code sends Anthropic documents CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1 for this on gateways

OpenRouter states Claude Code "is only guaranteed to work with the Anthropic first-party provider." Claude Code is built for Anthropic models, so routing to other providers or non-Anthropic models may not work correctly, including tool calling. Anthropic's own docs say it does not support routing Claude Code to non-Claude models through any gateway. Test any non-Claude model on a small task before relying on it.

  • Fast mode is only available when requests are routed to Anthropic first-party, and /fast through OpenRouter needs CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK=1 according to OpenRouter's guide.
  • OpenRouter can fail over between providers. If you need consistency, pin the provider with provider.order or provider.only; OpenRouter recommends making Anthropic first-party the top priority.
  • Using a gateway disables Anthropic's Remote Control and cloud sessions, which require a claude.ai login.

Using it on a server or in the cloud

On a remote machine the setup is the same, but the main risk is where your key ends up. Treat the OpenRouter key like a password, because anyone who holds it can spend your credits.

  • Keep it out of git. Use ~/.claude/settings.json in your home directory or a shell profile, never a committed project file. If you use .claude/settings.local.json, add it to your gitignore first.
  • Restrict file permissions. Run chmod 600 ~/.claude/settings.json so other users on the machine cannot read it.
  • Load from a secret store where you can. OpenRouter suggests pulling the key from the OS keychain rather than hardcoding it. For CI, use your platform's secrets.
  • Use settings.json for background processes. Anthropic notes that shell-only exports do not reliably reach background agents, while a settings file does.
  • CI example. For the Claude Code GitHub Action, OpenRouter's guide stores the key as a secret, passes it as anthropic_api_key (only to satisfy the action's launch check), and sets ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN in the step's env.
  • Anthropic's hosted cloud sessions will not use it. They require a claude.ai login, and gateway variables set in their environment are not applied, so use your own server instead.
  • Rotate on exposure. If a key ever lands in a log, a screenshot, or a repo, delete it in OpenRouter and create a new one.

Claude Code Router: what it is and when to use it

Claude Code Router (CCR) is a separate open-source project that runs a local gateway between Claude Code and many model providers. It is not made by Anthropic or OpenRouter. The project's GitHub README (musistudio/claude-code-router, MIT license) describes it as a local control plane for coding agents that gives supported agents one stable local endpoint.

  • What it does: you manage providers, models, accounts, and routing rules in one place. The README lists routing conditions, retries with ordered fallback models, and credential pools with key rotation.
  • Providers: it supports OpenAI-style, Anthropic Messages, and Gemini protocols, plus services such as OpenRouter, DeepSeek, Moonshot, and Z.AI, and custom compatible providers.
  • Install: the README gives npm install -g @musistudio/claude-code-router and then ccr ui, which opens a management UI locally. It requires Node.js 22 or newer, and a desktop app is also offered. Check the README for current steps.

CCR vs. connecting directly to OpenRouter

Direct OpenRouter is simpler: no extra process, four variables, and one provider's billing. CCR adds a layer you run and maintain, in exchange for flexibility.

Direct to OpenRouter Claude Code Router
Setup Environment variables only Install and run a local service
Providers Whatever OpenRouter offers OpenRouter and many other providers, mixed
Routing rules, fallbacks OpenRouter-side provider routing Your own rules, configured locally
Moving parts None A local gateway that must be running

Use direct OpenRouter if you want Claude models with minimal setup. Consider CCR if you want to send different tasks to different providers or keep several accounts behind one local endpoint. Remember that Anthropic does not support non-Claude models behind any gateway, so quality and tool-calling behavior are on you to test.

Run it on AlwaysAgent

AlwaysAgent gives you a dedicated Linux server with Claude Code and Codex preinstalled, so the "on a server" steps above are already done. Paste your OpenRouter key in settings and the workspace configures the variables for you. Your key stays on your server; we never proxy your requests or add a markup, and your tasks keep running after you close the browser.

FAQ

How do I use an OpenRouter API key in Claude Code?

Set ANTHROPIC_BASE_URL to https://openrouter.ai/api, put your OpenRouter key in ANTHROPIC_AUTH_TOKEN, set ANTHROPIC_API_KEY to an empty string, run /logout if you were signed in to Anthropic, then restart claude and check /status.

Why does Claude Code say my OpenRouter key is invalid?

Usually ANTHROPIC_API_KEY isn't blank, the key variable was referenced before being defined so the token is empty, or an old Anthropic login is still active. Blank the API key, run /logout, restart, and check /status.

Should I use ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY for OpenRouter?

Use ANTHROPIC_AUTH_TOKEN, which is sent as a Bearer token. OpenRouter's guide says ANTHROPIC_API_KEY must be explicitly empty, because it is sent as x-api-key and treated as a direct Anthropic credential.

How do I switch models when using OpenRouter in Claude Code?

Use /model in a session or claude --model at startup. To control which OpenRouter model each alias (opus, sonnet, haiku) uses, set the ANTHROPIC_DEFAULT_*_MODEL variables to IDs from the OpenRouter model list.

Can I use non-Claude models through OpenRouter in Claude Code?

You can point the model aliases at other models, but OpenRouter only guarantees Claude Code with the Anthropic first-party provider, and Anthropic doesn't support non-Claude models behind a gateway. Tool calling may break, so test before relying on it.

How do I see how much Claude Code is costing on OpenRouter?

Open the Activity dashboard on OpenRouter to see usage, cost, and model per request. OpenRouter also publishes an optional status line script that shows session cost inside Claude Code.

What is Claude Code Router, and do I need it?

Claude Code Router is a separate open-source local gateway that routes Claude Code to many providers with its own rules. You don't need it to use OpenRouter; connecting directly with environment variables is simpler.

Can I use Codex with OpenRouter too?

Codex uses its own config: define a custom provider in ~/.codex/config.toml with a base_url and env_key. AlwaysAgent sets up Claude Code and Codex separately.

來源:DEV Community · dev.to