← All articles

How to Use OpenRouter in Claude Code: Setup & Costs

Use OpenRouter in Claude Code with session-only credentials, verify /status and usage costs, and optionally switch to UniRoute with a clear way back.

UniRoute ·

To use Claude Code with OpenRouter, you need an OpenRouter key, the correct gateway address, and a compatible Claude model. Start by checking the connection, then check the resulting request in the account that pays for it. You can keep your existing configuration while trying this setup.

This guide covers the terminal client on macOS, Linux, or Windows through WSL with Bash installed. It also explains an optional switch to UniRoute. OpenRouter and UniRoute have separate keys, model catalogs, balances, and billing records. An Anthropic subscription is separate from both.

How to use OpenRouter in Claude Code

  1. Get an OpenRouter key and model ID: Create an OpenRouter API key, verify your account balance, and copy the full Claude model ID you selected in OpenRouter's catalog (OpenRouter recommends prioritizing the Anthropic 1P provider for Claude Code).
  2. Launch a session-only child shell with Anthropic Messages variables: Export ANTHROPIC_BASE_URL="https://openrouter.ai/api", put your OpenRouter key in ANTHROPIC_AUTH_TOKEN, explicitly set ANTHROPIC_API_KEY="", map the auxiliary role variables (such as ANTHROPIC_DEFAULT_HAIKU_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL, ANTHROPIC_DEFAULT_OPUS_MODEL, CLAUDE_CODE_SUBAGENT_MODEL), and run claude --model "$route_model" using the launcher in 1. Connect for one terminal session.
  3. Verify /status before sending prompts: Run /status inside Claude Code to confirm the active gateway URL (https://openrouter.ai/api), token authentication, and selected model before sending billable work; see 2. Confirm the destination before sending work.
  4. Reconcile usage or test a second gateway: Send one short non-sensitive prompt and verify the recorded tokens and charge in OpenRouter Activity (3. Compare costs using the same billing categories), or exit the child shell to return to your original setup or 4. Optionally try UniRoute.

Before connecting

Install Claude Code using Anthropic's current setup instructions, or keep your existing installation. Record the version with claude --version so troubleshooting refers to the client you actually use.

Create an OpenRouter API key, check the account balance and spending limits, and select an available Claude model from its catalog. OpenRouter states that its Claude Code compatibility guarantee applies to the Anthropic first-party provider and recommends prioritizing Anthropic 1P. A model being listed does not establish that every provider route supports the client. See the OpenRouter integration guide.

Use a project you trust. Review any existing user, project, or organization settings before changing providers. If your organization manages the gateway, confirm that an individual provider trial is allowed. Anthropic documents settings scope and precedence and gateway compatibility; a successful short reply does not verify every tool, long context, or newly released feature.

1. Connect for one terminal session

The following launcher asks for the key without echoing it or putting its value in shell history or command arguments. Run it from your trusted project directory. The gateway variables exist only in the child process; this command does not edit your shell profile, Claude settings, or saved login.

Keep shell tracing off when handling credentials. A terminal recording, a privileged process, or a diagnostic dump can still expose environment secrets. Do not paste your key into a chat or screenshot.

bash -c '
  set +x
  read -r -s -p "OpenRouter API key: " ANTHROPIC_AUTH_TOKEN
  printf "\n"
  [ -n "$ANTHROPIC_AUTH_TOKEN" ] || exit 1
  read -r -p "Full OpenRouter Claude model ID: " route_model
  [ -n "$route_model" ] || exit 1
  export ANTHROPIC_AUTH_TOKEN
  export ANTHROPIC_BASE_URL="https://openrouter.ai/api"
  export ANTHROPIC_API_KEY=""
  export ANTHROPIC_DEFAULT_HAIKU_MODEL="$route_model"
  export ANTHROPIC_DEFAULT_SONNET_MODEL="$route_model"
  export ANTHROPIC_DEFAULT_OPUS_MODEL="$route_model"
  export ANTHROPIC_DEFAULT_FABLE_MODEL="$route_model"
  export CLAUDE_CODE_SUBAGENT_MODEL="$route_model"
  claude --model "$route_model"
'

Copy the full model ID from OpenRouter when prompted. This launcher deliberately selects the same model for the main session and auxiliary model roles to avoid mixing a trial with old role mappings. For a normal workflow, you can later assign different compatible models to each role and account for their individual costs.

OpenRouter uses ANTHROPIC_AUTH_TOKEN and the base https://openrouter.ai/api; ANTHROPIC_API_KEY must be explicitly empty. Do not replace the base with the OpenAI-compatible /api/v1 endpoint. Claude Code connects with its native Messages protocol. These fields follow the OpenRouter configuration reference and Anthropic's gateway authentication documentation.

2. Confirm the destination before sending work

Inside Claude Code, run /status. Confirm the gateway address, token-based authentication, and selected model before sending a prompt. Check the model picker if the model differs from your selection.

If you see an authentication conflict, a subscription login, or a different address, stop the trial. Existing project settings, credential helpers, cloud-provider flags, or managed policy may affect the effective configuration. Review the loaded settings locally; do not print files containing keys. The launcher does not bypass those controls. Resolve the conflict using the official documentation or an administrator before continuing, rather than deleting saved credentials to force a connection.

When the destination is correct, ask for one short reply without sensitive project content. This sends a billable request. Match its time and model to OpenRouter Activity, then inspect its usage and charge. A status screen confirms configuration; a reply and matching record confirm that request's path.

Configuration comparison

ServiceBase URL for Claude CodeCredentialModel IDUsage and funds
OpenRouterhttps://openrouter.ai/apiOpenRouter key in ANTHROPIC_AUTH_TOKEN; empty ANTHROPIC_API_KEYFull Claude ID from OpenRouter, commonly with anthropic/ prefixOpenRouter Activity and its own account balance
UniRoutehttps://api.uniroute.appUniRoute key in ANTHROPIC_AUTH_TOKEN; check conflicting credentialsExact Claude ID available to your UniRoute keyUniRoute Console and its own wallet

Copy IDs from the destination's current catalog. Removing a provider prefix from one service's ID is not a reliable way to discover the other's ID. Neither key grants access to the other service, and a top-up does not transfer funds between them.

3. Compare costs using the same billing categories

A coding task can make several requests. Compare the same model version, context tier, token categories, processing options, and currency before deciding which setup fits your budget. Check the provider route as well as the displayed model name.

The table below identifies where to obtain a rate and how to interpret it; it does not quote a fixed price. Documentation links were checked on October 15, 2026. For a spending decision, record the actual rate and its retrieval time when you run the task.

Service and model scopeCategories to compareUnitCurrent source and charge check
OpenRouter: exact selected Claude model and providerOrdinary input, output, cache reads and cache writes; any applicable context or priority tierUse the rate's stated unit; normalize token rates to USD per million tokensSelected model/provider pricing in OpenRouter; reconcile with Activity. Usage accounting explains returned usage and cost.
UniRoute: exact available Claude model and routeOrdinary input, output, cache reads and cache writes; applicable tierUSD per million tokens in the public Claude rate tableCurrent UniRoute Claude rates and billing guide, including the displayed snapshot; reconcile with your Console record

For a task total, retain the request count and sum the matching recorded charges. Keep your rate snapshot with the record. If the meaning of an input field includes cached tokens, separate them before estimating ordinary input; do not charge the same tokens twice in a spreadsheet.

Claude Code's session estimate can use a different price basis from your gateway. Use the gateway's recorded charge to reconcile its account. Anthropic's cost guide explains client cost reporting. A charge from a historical UniRoute request is not evidence of today's OpenRouter cost, and this article does not claim a measured price or reliability advantage between them.

Same-task cost and verification worksheet

Because provider routes, cache state, and account rates vary by key and timestamp, this guide leaves the side-by-side comparison blank rather than quoting a pre-filled benchmark. Copy the worksheet below and fill in each cell from your own OpenRouter Activity and UniRoute Console records when running an identical task:

Field to recordOpenRouter session (https://openrouter.ai/api)UniRoute session (https://api.uniroute.app)
Date, time window, and timezone[record from your run][record from your run]
claude --version and /status check[record from your run][record from your run]
Exact model ID and routed provider/channel[record from OpenRouter Activity][record from UniRoute Console]
Snapshot rate (input / output / cache read / cache write per 1M tokens)[record rate + timestamp][record rate + timestamp]
Request rounds completed for the task[record request count][record request count]
Ordinary uncached input tokens (excluding cached tokens)[record tokens][record tokens]
Cache-write tokens and cache-read tokens[record write / read tokens][record write / read tokens]
Output tokens[record tokens][record tokens]
Recorded gateway charge (USD) across all task requests[record from OpenRouter Activity][record from UniRoute Console]
Stream completion / retries / errors observed[none / details][none / details]

Step-by-step measurement procedure:

  1. Freeze the starting repo state: Use a clean git commit or separate worktree so both sessions read the exact same files and system instructions.
  2. Run the OpenRouter trial first: Launch Claude Code with the session-only OpenRouter command above, verify /status, run your fixed prompt once, and record every request generated by that task in OpenRouter Activity.
  3. Reset to the same repo state and exit: Restore any modified files so the second trial starts from the identical codebase.
  4. Run the UniRoute trial in a fresh session: Launch Claude Code with the session-only UniRoute command below, verify /status, run the same prompt once, and record the matching requests in UniRoute Console.

Acceptance criteria for a valid comparison:

  • Both sessions used the same claude --version, starting repository state, and prompt, with /status verified before sending work.
  • Both sessions targeted the same underlying Claude model release and context tier, with cold vs. warm prompt-cache state noted explicitly.
  • Every request round triggered by the task (including subagent or tool turns) is included in the token and charge totals.
  • Final cost is taken from each service's authenticated billing record rather than client-side session estimates.

4. Optionally try UniRoute without changing the OpenRouter setup

If you want to evaluate UniRoute—or compare staying on OpenRouter, going direct, self-hosting LiteLLM, and adding a second gateway in our OpenRouter alternatives guide—first read the English Claude Code setup tutorial. It documents the native Messages address, model discovery, persistent configuration with a backup, and a dated acceptance record. That record covers a short Claude Haiku request; it does not validate every model or workload.

Create a UniRoute API key, confirm the exact Claude model is available to it, and check the current model prices. Then check wallet funds and recharge if needed. Creating a key alone does not provide funds for a paid request.

Exit the OpenRouter session before running this separate launcher. Enter a UniRoute key and a UniRoute model ID at its prompts:

bash -c '
  set +x
  read -r -s -p "UniRoute API key: " ANTHROPIC_AUTH_TOKEN
  printf "\n"
  [ -n "$ANTHROPIC_AUTH_TOKEN" ] || exit 1
  read -r -p "Full UniRoute Claude model ID: " route_model
  [ -n "$route_model" ] || exit 1
  export ANTHROPIC_AUTH_TOKEN
  export ANTHROPIC_BASE_URL="https://api.uniroute.app"
  export ANTHROPIC_API_KEY=""
  export ANTHROPIC_DEFAULT_HAIKU_MODEL="$route_model"
  export ANTHROPIC_DEFAULT_SONNET_MODEL="$route_model"
  export ANTHROPIC_DEFAULT_OPUS_MODEL="$route_model"
  export ANTHROPIC_DEFAULT_FABLE_MODEL="$route_model"
  export CLAUDE_CODE_SUBAGENT_MODEL="$route_model"
  claude --model "$route_model"
'

Check /status again, then make a short paid request only when the destination and funds are correct. In UniRoute Console, reconcile its time, model, usage, and charge. Keep your API key, raw prompt, and private request identifiers out of public reports.

Switching and restoration checklist

StageActionEvidence to keep
Preserve the original setupNote your current provider and model without copying secrets. Back up settings privately before any persistent edit. The launchers above make no settings-file edits.Client version and original provider/model
Select the destinationUse its own key, base URL, complete model ID, and balance. Exit the other trial first.Selected model and applicable rate snapshot
VerifyInspect /status; stop if credentials or address conflict. Send one small paid request only after checking the destination.Correct destination plus a matching reply and usage record
ReconcileCompare usage categories and recorded charge; separate other concurrent activity.Task total and request count, with secrets removed
ReturnExit Claude Code to end the launcher. Relaunch your usual command or rerun the OpenRouter launcher. If you made persistent edits separately, restore only the changed fields from your private backup./status confirms the intended original provider and model

Exiting restores the parent terminal's environment because the exported values belonged to the child shell. Claude Code can still write its normal session history or trust decisions; this method does not roll those back. Keep an existing working login intact while investigating conflicts.

Common connection problems

  • Authentication fails: check the destination key and its permissions, the explicitly empty old API-key field, and the effective credential source. Never send a complete key to support.
  • Model not found: confirm the exact destination ID and supported route, then restart the session. A catalog entry alone does not prove Claude Code compatibility.
  • Wrong bill or missing activity: confirm the account and request time before retrying. A client cost estimate is not an account debit.
  • Timeout, interrupted stream, or upstream error: save a sanitized error and check usage first. An interrupted response may already have incurred usage; repeated retries can add cost. Use the API error 500 troubleshooting guide to identify the failing layer and set a retry limit, or the Claude stream idle timeout guide if a response stops mid-stream with stream idle timeout - partial response received.

Start with a configuration you can identify, a small request you can reconcile, and a way to return to your existing setup. Use the Claude Code API cost guide for budgeting, the OpenRouter alternatives comparison to weigh fees, native endpoints, and routing options, and the UniRoute connection tutorial if you choose that route.