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.
Can you use Codex with OpenRouter?
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.
Why use OpenRouter with Codex?
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.
- One account for model usage. OpenRouter aggregates billing and lets you inspect requests in its Activity dashboard.
- More model choices. Its Codex guide documents switching between OpenRouter model slugs, including OpenAI and Claude families.
- Pay-as-you-go access. With prepaid credits, request costs are deducted from your OpenRouter balance. Check current model charges and credit-purchase fees before funding it.
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.
ChatGPT sign-in vs OpenAI API key vs OpenRouter
| 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 |
Step-by-step Codex CLI OpenRouter setup
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.
Create an OpenRouter API key
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.
Export OPENROUTER_API_KEY
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.
Edit your user-level config.toml
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.
Run codex in your project
Start a new session from your project directory after saving the file. The selected provider sends model requests to OpenRouter.
Verify the model and a real request
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.
Can I use env_key instead?
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.
Which configuration file takes effect?
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.
Choosing a model, including Claude
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.
Switching between OpenRouter and OpenAI login
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.
Limitations to understand
- ChatGPT services have separate requirements. OpenAI states that Codex cloud requires ChatGPT sign-in. A custom OpenRouter key does not provide that login or ChatGPT workspace access.
-
Responses compatibility has boundaries. OpenRouter's endpoint is stateless. It rejects
store: trueand a non-nullprevious_response_idwith a 400 error. Do not assume OpenAI's server-side conversation storage is available. - Model behavior varies. Protocol support and successful authentication do not establish coding quality. Test the specific model and workflow before using them for larger changes.
- Credits and rate limits still apply. Long tasks can stop when funds, spending limits, or available provider capacity run out. OpenRouter's error reference documents 429 rate limiting.
Troubleshooting Codex OpenRouter errors
401: invalid or missing credentials
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.
Model not found
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.
wire_api error or a Chat Completions URL
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.
Project-local config ignored warning
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.
402: insufficient credits
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.
429 or a stopped 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.
Keep Codex running on AlwaysAgent
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 paused. Join the waitlist for availability.
FAQ
Can I use Codex with OpenRouter?
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.
Where do I put OPENROUTER_API_KEY for Codex?
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.
Can Codex CLI use a Claude model through OpenRouter?
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.
Does my ChatGPT subscription pay for OpenRouter requests?
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.
Can I put the provider in my project's .codex/config.toml?
No. Codex ignores project-local model_provider and model_providers settings and warns at startup. Put the provider definition in ~/.codex/config.toml.
How do I switch back to ChatGPT sign-in?
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.
Top comments (0)