cd /news/ai-tools/how-to-use-codex-cli-with-openrouter · home › topics › ai-tools › article
[ARTICLE · art-176472] src=dev.to ↗ pub= topic=ai-tools verified=true sentiment=· neutral

How to use Codex CLI with OpenRouter

A developer documented how to point OpenAI's Codex CLI at OpenRouter by defining a custom model provider in ~/.codex/config.toml, setting base_url to OpenRouter's API endpoint with wire_api = "responses", and supplying an OpenRouter key through command-backed authentication. The guide notes that OpenRouter's Responses API is stateless and that a ChatGPT subscription or OpenAI API key does not cover OpenRouter usage, which is billed against OpenRouter credits.

recommendation

When routing Codex CLI through OpenRouter, run a small representative task first and check its token cost in the Activity dashboard before committing to a long job.

more in playbook: Controlling LLM cost
by read9 min views16 publishedNov 26, 2026

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

Yes, Codex CLI works with OpenRouter through a custom model provider. Set OpenRouter's API base URL in your user-level config.toml, export your key, and choose an OpenRouter model. Here is the setup, how to verify it, and what changes when you switch providers.

Yes. Define a custom provider in ~/.codex/config.toml with base_url = "https://openrouter.ai/api/v1" and wire_api = "responses". Supply your OpenRouter key and select an OpenRouter model ID.

OpenRouter publishes a Codex CLI guide and documents an OpenAI-compatible Responses API at https://openrouter.ai/api/v1/responses. In Codex, enter the base URL without the final /responses.

OpenRouter describes this API as stateless, with reasoning, tool calling, and web search integration. That documents an API interface; it does not promise identical behavior from every model. The configuration below follows the official documentation checked on November 23, 2026.

OpenRouter lets you use one API key across models from different suppliers. Codex remains your terminal coding agent; the custom provider changes where its model requests go.

A ChatGPT subscription does not fund this OpenRouter setup. Likewise, an OpenAI API key belongs to OpenAI's billing system. Choose the connection whose billing and model access you want.

Before a long task, run a small representative one and check its cost in OpenRouter. The billing FAQ explains how token usage is charged.

Connection Billing Model choice Setup
ChatGPT sign-in ChatGPT plan access and applicable limits OpenAI models available to your account or workspace Use the built-in OpenAI provider and run codex login
OpenAI API key Usage billed to your OpenAI Platform account OpenAI models your API account can access Use the built-in OpenAI provider and API-key login
OpenRouter Usage charged against OpenRouter credits OpenRouter catalog; verify tool support and compatibility Define a custom provider and supply an OpenRouter key

The terminal examples use Bash or Zsh. If Codex is not installed, OpenAI's official repository documents npm install -g @openai/codex, alongside standalone installers and Homebrew.

Open the API Keys page linked from OpenRouter's Codex guide and create a key. Add credits for paid model requests. Use an OpenRouter key for this provider.

Set the variable in the same terminal that will launch Codex. Replace the placeholder below with your key. For later terminals, add the export to your Bash or Zsh startup file.

Create ~/.codex if needed, then merge the provider configuration below into ~/.codex/config.toml. Preserve your other settings. Keep top-level model and model_provider assignments before table headers.

Start a new session from your project directory after saving the file. The selected provider sends model requests to OpenRouter.

Enter /status to see session details such as context usage and rate limits. Ask Codex to inspect a small file, then check the OpenRouter Activity dashboard for the request, model, token usage, and cost to confirm which model served it.

Terminal: set your key

export OPENROUTER_API_KEY="<your-openrouter-key>"
mkdir -p ~/.codex

This configuration uses the command-backed authentication recommended by OpenRouter's current Codex guide:

~/.codex/config.toml

model_provider = "openrouter"
model = "~openai/gpt-sol-latest"

[model_providers.openrouter]
name = "OpenRouter"
base_url = "https://openrouter.ai/api/v1"
wire_api = "responses"

[model_providers.openrouter.auth]
command = "sh"
args = ["-c", "echo $OPENROUTER_API_KEY"]

openrouter is the custom provider ID; it must match the table name. Built-in IDs such as openai, ollama, and lmstudio are reserved. The command prints the environment variable's value so Codex can obtain the bearer token.

The model alias above comes directly from OpenRouter's integration guide, which omits wire_api; Codex's reference says responses is the only supported value and the default, so keeping the line is harmless. It follows a model family rather than pinning one release. You can replace it with an exact model ID available on OpenRouter.

Terminal: launch Codex

cd /path/to/your/project
codex

For a first check, ask: “Read one source file and summarize what it does without editing anything.” Then try a small change and its tests. This checks the workflow beyond receiving a chat reply.

Yes. OpenAI documents env_key as the name of the environment variable containing a provider key. Remove the entire [model_providers.openrouter.auth] block and place this line inside [model_providers.openrouter]:

Alternative authentication setting

env_key = "OPENROUTER_API_KEY"

OpenRouter says env_key works for authentication, but Codex will not fetch its model catalog in that mode. Non-OpenAI models show an “Unknown model” fallback-metadata warning. Its guide recommends command-backed authentication to obtain the correct metadata. Do not combine auth with env_key.

On Windows, OpenRouter documents command = "powershell" with args = ["-NoProfile", "-Command", "Write-Output $env:OPENROUTER_API_KEY"] for the auth block. Its guide uses setx OPENROUTER_API_KEY "<your-openrouter-key>"; restart Codex afterward so it sees the variable.

Codex reads its user configuration from ~/.codex/config.toml. If you set CODEX_HOME, edit $CODEX_HOME/config.toml instead. Keep the provider definition in this user configuration, outside your repository.

OpenAI documents command-line flags as higher priority than profile files and user defaults. Trusted project configuration can change some settings, but never the provider definitions. If the model looks wrong, inspect launch flags, the selected profile, and project overrides before repeatedly changing the provider block.

For using OpenAI Codex with other models, copy the API model ID from OpenRouter rather than guessing from a display name. IDs commonly use an author/model format. OpenRouter's integration guide explicitly lists ~openai/gpt-sol-latest and ~anthropic/claude-sonnet-latest.

The ~ prefix identifies a rolling alias for the latest approved stable version of a family. Use an available pinned version when repeatable comparisons matter. The Models API reference distinguishes the routable id from the permanent canonical_slug; use the request ID.

Tool-calling support matters. A coding agent needs to request actions and use their results. Check the model's supported parameters before testing it. OpenRouter documents this catalog query for models supporting tools:

Terminal: find tool-capable models

curl "https://openrouter.ai/api/v1/models?supported_parameters=tools"

To try a Codex CLI Claude model through the configured provider for one session:

Terminal: select a documented Claude alias

codex --model "~anthropic/claude-sonnet-latest"

Tool support is a starting requirement. Compare whether the model reads relevant files, makes correct edits, runs tests, and responds sensibly to failures. Also check context limits and supported reasoning settings instead of copying them from another model.

Rolling aliases are convenient for discovery, but their targets can change. Once you find a useful model, copy its exact routable ID from the catalog if you want to compare later runs against the same version.

Codex supports named profile files and temporary command-line overrides. Current OpenAI configuration docs define profiles as separate files beside the base configuration.

With the OpenRouter configuration above as your default, create ~/.codex/openai-login.config.toml containing:

~/.codex/openai-login.config.toml

model_provider = "openai"
model = "gpt-6.1-sol"

That OpenAI model appears in its configuration documentation; substitute one your account can access. Set both keys so the OpenRouter model alias is not inherited. Sign in with codex login, then select the profile:

Terminal: choose the connection

codex --profile openai-login
codex

The first command selects the OpenAI profile; the second starts your default OpenRouter setup. Profile files overlay ~/.codex/config.toml and use top-level keys. Current docs do not use legacy [profiles.name] tables or a top-level profile = "name" selector.

For a single run without creating a profile, -c overrides configuration values using TOML syntax:

Terminal: temporary OpenAI override

codex -c 'model_provider="openai"' -c 'model="gpt-6.1-sol"'

For OpenAI API billing, set OPENAI_API_KEY and use its documented login command: printenv OPENAI_API_KEY | codex login --with-api-key. Profiles select configuration; authenticate with the intended OpenAI method separately. OpenRouter continues to use its own configured credential.

Remember that --model only selects a model; switching connections also needs the right model_provider. OpenAI documents codex login status for checking the active OpenAI authentication method.

store: true and a non-null previous_response_id with a 400 error. Do not assume OpenAI's server-side conversation storage is available. Check that OPENROUTER_API_KEY is set in the launching process and contains an OpenRouter key. With command-backed auth, the command must run successfully and print a token. OpenRouter says a missing Authorization header can mean the variable was unset or the auth command printed nothing.

For env_key, enter the variable name rather than the secret. Do not enable requires_openai_auth = true: OpenAI documents that this uses OpenAI authentication and ignores env_key.

Copy the exact request ID from OpenRouter's model catalog. Check punctuation, the author prefix, and whether you intended a rolling alias. OpenRouter's Codex guide specifically recommends checking its model list for this error.

The current Codex configuration reference lists responses as the only supported wire_api value. Replace old wire_api = "chat" examples. Use https://openrouter.ai/api/v1 as the base URL, without /chat/completions or /responses.

Move model_provider and model_providers into your user-level ~/.codex/config.toml. OpenAI documents that project-local .codex/config.toml files cannot override these settings and trigger a startup warning. Trusting the project does not remove that restriction.

OpenRouter documents 402 for insufficient account or key credits. Check your balance and the error details. Its limits guide also documents temporary in-flight spending-budget failures: when limit_source is openrouter_in_flight_budget, wait for the supplied Retry-After interval. Repeated retries do not fix an unaffordable request.

A 429 indicates rate limiting. Follow Retry-After when present and reduce request pressure. OpenRouter's error reference also distinguishes unavailable providers and upstream failures; read the returned message before changing credentials.

AlwaysAgent provides each user a dedicated cloud Linux server with its own public IP and Codex and Claude Code preinstalled. Its computer and phone browser workspace includes AI chat, files, a terminal, remote browser preview, and version history. No app installation or SSH is required.

Supply your Base URL and API key in settings. Keys stay on your own server; AlwaysAgent does not handle AI calls, add model markups, or resell model credits. Tasks continue on the server after you close your computer or browser.

Registration is currently d. Join the waitlist for availability.

Yes. OpenRouter publishes a Codex CLI guide and an OpenAI-compatible Responses endpoint. Define a custom provider in ~/.codex/config.toml with base_url https://openrouter.ai/api/v1, wire_api "responses", an OpenRouter credential, and a model ID.

Export it in the environment that launches Codex. OpenRouter recommends command-backed authentication that reads this variable. Alternatively, set env_key = "OPENROUTER_API_KEY" in the provider block, with the model-catalog limitation described above.

OpenRouter's Codex guide lists ~anthropic/claude-sonnet-latest as an example. Select it with --model or the model configuration key. Verify tool calling and test coding tasks; model availability does not guarantee equivalent results.

No. This setup uses OpenRouter credentials and credits. ChatGPT sign-in uses ChatGPT plan access, while OpenAI API-key usage is billed separately through OpenAI Platform.

No. Codex ignores project-local model_provider and model_providers settings and warns at startup. Put the provider definition in ~/.codex/config.toml.

Select the built-in openai provider and an OpenAI model your account can access, then use codex login for ChatGPT authentication. A separate name.config.toml file selected with codex --profile name lets you keep OpenRouter as your default.

── more in #ai-tools 4 stories · sorted by recency
── more on @openai 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/how-to-use-codex-cli…] indexed:0 read:9min 2026-11-26 · —