Codex 401 Unauthorized: Fix Key and config.toml
Fix Codex CLI "unexpected status 401 Unauthorized": read the url in the error, check env_key, stray quotes and base_url on any OS, then test the key with curl.
GoiAPI · · 12 min read
Ask AI and more

Codex CLI prints unexpected status 401 Unauthorized when the API server does not accept the credential Codex sent: the key is missing, wrong, has extra characters, or went to the wrong server. The fastest fix is to read the url: part at the end of the error, which tells you where the request actually went, and then check the key's environment variable in the exact terminal that runs Codex. This guide walks through each cause with fixes for Windows, macOS and Linux, and shows how to confirm the key with curl before you start Codex again.
What we checked: the config syntax against OpenAI's Codex documentation and the source code of Codex CLI 0.174.0 (the latest npm release on December 5, 2026). The 401 and 404 responses quoted below are from our own curl calls to https://api.goiapi.com on December 5, 2026. We did not rerun a full Codex session with a live key for this article, so what Codex prints is derived from its source code and not tested end to end.
How to read the Codex 401 error
Codex formats HTTP errors like this (from codex-rs/protocol/src/error.rs in 0.174.0):
unexpected status 401 Unauthorized: <API message>, url: <endpoint called>, cf-ray: <id>, request id: <id>You may also see stream error: exceeded retry limit, last status: 401 Unauthorized in older GitHub issues. That is how older Codex releases reported it. In the 0.174.0 source a 401 is not retried and always shows in the long form above.
Either way, it means the server rejected authentication. Three parts of the long form matter:
- The text after the colon is the API's own message (Codex shows the
error.messagefield from the response body). It tells you whether the key was missing or wrong. url:shows which server and path Codex called. Most people skip it, and it is the best clue you have.request id:is what support needs to look up the request.
You may also see a cf-ray: field between url: and request id:; you can ignore it.
What the message after "401 Unauthorized" means
Codex may not send an English Accept-Language header, so the text in your error can be in another language. Match on "code": "invalid_api_key" and on whether a key was sent, not on the exact wording.
| Message after the colon | Returned by | Meaning |
|---|---|---|
Missing API key. Send your key in the Authorization: Bearer <key> header or the x-api-key header. | GoiAPI | The request reached GoiAPI with no key at all |
The API key is invalid or has been revoked. | GoiAPI | A key was sent, but it is wrong, has extra characters, or was revoked |
Incorrect API key provided: ... | OpenAI's API | The key reached OpenAI's servers and OpenAI does not recognize it |
Missing bearer or basic authentication in header | OpenAI's API | The request reached OpenAI with no key |
We got the two GoiAPI messages by calling https://api.goiapi.com/v1/responses on December 5, 2026, once with no key and once with a made-up key. Both returned HTTP 401 with "code": "invalid_api_key". GoiAPI returns the English wording shown here when the Accept-Language header starts with en. The full list is on the GoiAPI error codes page. The two OpenAI messages are the ones Codex users commonly post in GitHub issues and on the OpenAI forum; we did not call OpenAI's API to check them.
The url tells you which half is broken
url: https://api.goiapi.com/v1/responses: Codex is using your custom provider. The problem is the key. Go to causes 1 and 2.url: https://api.openai.com/...orurl: https://chatgpt.com/backend-api/codex/...: Codex is not using your custom provider and fell back to the built-inopenaiprovider. The problem isconfig.toml. Go to cause 3.
Cause 1: Codex cannot see the right key in the environment
A custom provider never reads the key from config.toml. The env_key line holds only the name of an environment variable, and Codex reads that variable from its own process. In Codex 0.174.0 the logic is:
- Variable unset or empty: Codex stops locally with
Missing environment variable: `GOIAPI_API_KEY`.That is not a 401. No request was sent. - Variable set: Codex sends the value as-is in
Authorization: Bearer .... It does not strip quotes, spaces or line endings. A bad value gets a 401.
So a 401 with url: https://api.goiapi.com/... means the variable exists but its value is not a valid key. The usual reasons:
The names do not match. env_key = "GOIAPI_API_KEY" while you exported GOIAPI_KEY, and an older GOIAPI_API_KEY holding a revoked key is still around. On macOS and Linux, variable names are case-sensitive.
You set the key in a different terminal. export (bash, zsh) and $env: (PowerShell) only affect the current window. A new tab, or the VS Code integrated terminal, may not have the variable, or may have an old value.
You used setx on Windows and ran Codex right away. setx saves the variable for processes started after it runs. Windows that are already open keep the old value. The VS Code integrated terminal inherits its environment from when VS Code started, so quit VS Code completely and reopen it; a new terminal tab is not enough.
Check the variable without printing the key
Do not echo the whole key: it ends up in your scrollback and in screenshots. These one-liners only tell you whether the value starts with sk- and contains no quotes or whitespace.
macOS / Linux (bash or zsh):
[[ "$GOIAPI_API_KEY" == sk-* && "$GOIAPI_API_KEY" != *[\"\'[:space:]]* ]] && echo "Key looks clean" || echo "Key missing, wrong prefix, or extra characters"Windows PowerShell:
if ($env:GOIAPI_API_KEY -match '^sk-[^\s"'']+$') { 'Key looks clean' } else { 'Key missing, wrong prefix, or extra characters' }We ran both on December 5, 2026 against test values: sk-abc passed, while "sk-x", sk-abc with a trailing carriage return, and sk-a b all failed.
Cause 2: stray quotes or hidden characters in the key
This one is hard to spot because the key looks right at a glance. Quote marks end up inside the variable's value when:
- You use cmd.exe on Windows.
set GOIAPI_API_KEY="sk-..."keeps both double quotes in the value. We tested it on December 5, 2026:set T_Q="sk-x"printed back as"sk-x", whileset "T_Q=sk-x"printedsk-x. - You double-quote in bash.
export GOIAPI_API_KEY='"sk-..."'keeps the inner double quotes. - A
.envfile is loaded by a tool that keeps quotes, for exampledocker run --env-file, which takes each value literally. - The key came from a file saved on Windows and is read in Linux or WSL: the line ends with an invisible
\r.
On GoiAPI, a quoted key fails like a wrong key. When we sent Authorization: Bearer "sk-..." (with the quote marks) on December 5, 2026, the API returned HTTP 401 with "code": "invalid_api_key", exactly the response a made-up key gets.
Set the variable without stray characters:
# macOS / Linux
export GOIAPI_API_KEY="sk-..."# Windows PowerShell, current window only
$env:GOIAPI_API_KEY = "sk-..."
# Windows, saved for your user account (open a new window afterwards)
setx GOIAPI_API_KEY "sk-...":: cmd.exe: quote the whole assignment, not the value
set "GOIAPI_API_KEY=sk-..."In bash and PowerShell the double quotes above are shell syntax and do not end up in the value. cmd.exe is the exception, so copy its line exactly.
For a key read from a Windows-saved file, strip the line endings: export GOIAPI_API_KEY="$(tr -d '\r\n' < key.txt)".
Cause 3: Codex is not using your custom provider
If url: points at OpenAI, Codex is on its built-in provider. That provider uses the credentials saved by codex login (a ChatGPT sign-in or an OpenAI API key), not your GoiAPI key. Check these in order:
- The provider must be in your user-level file. According to OpenAI's advanced Codex configuration docs (checked December 5, 2026), Codex ignores
model_providerandmodel_providersin a project's.codex/config.tomland prints a startup warning. Put them in~/.codex/config.toml(on Windows, the.codexfolder in your user profile). If you setCODEX_HOME, Codex reads$CODEX_HOME/config.tomlinstead. - The file needs a top-level
model_providerline that matches the name aftermodel_providers.. Without it, the[model_providers.goiapi]table is defined but never used. model_providermust sit above every[...]table. In TOML, a line written after a table header such as[model_providers.goiapi]belongs to that table, not to the top level.- Do not reuse a reserved ID. Codex reserves
openai,ollama,lmstudioand a few other built-in names. Use your own, such asgoiapi. - If you use a profile, start Codex with it. Settings in
~/.codex/goiapi.config.tomlonly apply tocodex --profile goiapi. Since Codex 0.134.0,--profileno longer reads[profiles.<name>]tables fromconfig.toml, so profiles copied from older guides silently do nothing.
A working ~/.codex/config.toml for GoiAPI, matching the Codex CLI integration guide:
model = "gpt-6.1-sol"
model_provider = "goiapi"
[model_providers.goiapi]
name = "GoiAPI"
base_url = "https://api.goiapi.com/v1"
env_key = "GOIAPI_API_KEY"
wire_api = "responses"Avoid putting the key directly in the file with experimental_bearer_token. The Codex configuration reference calls it discouraged and recommends env_key. For the full setup, including install commands and a profile that leaves your ChatGPT sign-in alone, see Codex CLI custom provider: use your own API key.
Cause 4: base_url points to the wrong place
base_url decides where your key is sent.
| base_url | What happens | Status |
|---|---|---|
https://api.goiapi.com/v1 | Correct. Codex calls /v1/responses | No error if the key is valid |
https://api.goiapi.com (no /v1) | Codex calls /responses, which does not exist | 404, not 401 |
https://api.openai.com/v1 with a GoiAPI key | Your GoiAPI key is sent to OpenAI | 401 Incorrect API key provided |
We tested the second row on December 5, 2026: https://api.goiapi.com/responses returned HTTP 404 with Cannot POST /responses. If you see a 404 rather than a 401, fix base_url before you touch the key. Also do not add /responses to the end of base_url; Codex appends it.
Older guides sometimes set OPENAI_BASE_URL or OPENAI_API_BASE in the shell. The current Codex configuration docs do not list those variables; they use openai_base_url in config.toml for the built-in provider, and a named custom provider for anything else. If one of those old variables is still in your shell profile, remove it so it cannot confuse other tools.
wire_api: not a 401 cause, but often blamed
The configuration reference (checked December 5, 2026) says responses is the only supported wire_api value and the default when omitted. An old config with wire_api = "chat" fails when Codex loads the config, before any request goes out, so you see a config error instead of a 401. In the 0.174.0 source that error starts with:
`wire_api = "chat"` is no longer supported.
How to fix: set `wire_api = "responses"` in your provider config.Change it to wire_api = "responses" or delete the line. GoiAPI's endpoint for this is described in the OpenAI Responses API docs.
Cause 5: an expired ChatGPT sign-in
This applies only when you are not using a custom provider, so Codex runs on your ChatGPT account or an OpenAI API key. OpenAI's Codex authentication docs say credentials are cached in ~/.codex/auth.json or your OS credential store, and that Codex refreshes tokens automatically during use. When that refresh breaks (users commonly report this after copying auth.json to another machine or switching accounts), you get 401s even though it worked yesterday.
codex login status # show the active sign-in method
codex logout # clear the stored credentials
codex login # sign in againTo sign in with an OpenAI API key instead of ChatGPT, the docs pipe the key through stdin: printenv OPENAI_API_KEY | codex login --with-api-key. Exporting OPENAI_API_KEY alone is not enough, because the built-in openai provider has no env_key in the 0.174.0 source and uses the credentials stored by codex login.
Verify the key with curl before you rerun Codex
List models with the same variable your env_key names. Listing models does not take anything from your balance, and it tells you right away whether the key is valid.
macOS / Linux:
curl -s -w "\nHTTP %{http_code}\n" https://api.goiapi.com/v1/models -H "Authorization: Bearer $GOIAPI_API_KEY"Windows PowerShell (type curl.exe: in Windows PowerShell, curl is an alias for a different command):
curl.exe -s -w "\nHTTP %{http_code}\n" https://api.goiapi.com/v1/models -H "Authorization: Bearer $env:GOIAPI_API_KEY"How to read the result:
- HTTP 200 with
gpt-6.1-solin the list: the key and URL are fine. If Codex still returns 401, Codex is not reading this variable. Run Codex in the same window you ran curl in, and recheck cause 3. - HTTP 401 "Missing API key": the variable is empty or not set in this window.
- HTTP 401 "invalid or has been revoked": the variable has a value, but it is wrong. Run the quote check above, or create a new key in the dashboard.
- HTTP 403: the key is valid but restricted to other models or IP addresses. See per-key restrictions in Authentication.
401 vs 402, 403 and 429
These all get called "key errors", but the fixes differ:
| Code | Meaning | Fix |
|---|---|---|
| 401 | The key is not recognized | Fix the variable, env_key or base_url as above |
| 402 | The key is valid, but your balance is too low to hold funds for the request | Top up |
| 403 | The key is valid but not allowed this model or this IP | Change the key's restrictions |
| 429 | Too many requests, the key's spending limit reached, or the model is overloaded | Wait for the Retry-After header; for a spending-limit 429, raise the key's limit in the dashboard or wait for the next period, since retrying right away will not help |
If you use an OpenAI key and see insufficient_quota, that is a 429 quota error, not a 401; OpenAI insufficient_quota error covers it. Claude Code users with a similar error can read Claude Code says Invalid API key.
Does a 401 cost anything?
No. Per the error codes page, a failed request that returns no content is not charged, and a 401 is rejected before any model runs. Once Codex works, you pay for the tokens each request uses. GPT prices per 1M tokens from GoiAPI pricing, checked December 5, 2026:
| Model | API name | Input | Output |
|---|---|---|---|
| GPT-6 Luna | gpt-6-luna | $0.0208 | $0.1248 |
| GPT-6.1 Sol | gpt-6.1-sol | $0.13 | $0.78 |
| GPT-6.2 Sol | gpt-6.2-sol | $0.13 | $0.78 |
Each request that returns content has a small minimum charge, and prices can change, so check the pricing page before you start. For a fuller comparison see GPT-6 API pricing. You top up with USDT (TRC20 or BEP20) or Binance Pay, 5 to 4,000 USDT at a time, no credit card needed; OpenAI API access without a credit card explains the options. Top-ups are final and cannot be refunded, so add only what you plan to use.
FAQ
Which environment variable does Codex read the API key from?
It depends on the provider. A custom provider reads the variable named in its env_key (for example GOIAPI_API_KEY). The built-in OpenAI provider uses the credentials saved by codex login, not an OPENAI_API_KEY variable in your shell.
I am logged in, so why does Codex still return 401?
Look at url: in the error. If it points at OpenAI or chatgpt.com, run codex logout and then codex login to refresh the session. If it points at api.goiapi.com, your ChatGPT sign-in is irrelevant: the GoiAPI key in your environment variable is the problem.
What is the difference between "exceeded retry limit, last status: 401" and "unexpected status 401"?
Same authentication failure. "Exceeded retry limit" is how older Codex releases reported it; 0.174.0 prints "unexpected status 401". The fixes are identical.
How do I use Codex with a different base URL?
Define a custom provider in ~/.codex/config.toml with base_url, env_key and wire_api = "responses", and select it with a top-level model_provider line. The service must implement the Responses API at /v1/responses. The full walkthrough is in Codex CLI custom provider.
Can I just paste the key into config.toml?
You can with experimental_bearer_token, but OpenAI's docs discourage it. A key in a config file is easy to commit to Git or share by accident. Keep it in an environment variable and put only the variable's name in env_key.
Still getting 401?
If curl returns 200 and Codex still shows 401 with url: https://api.goiapi.com/..., send the request id from the error through the contact page. Never send your API key. New to GoiAPI? Follow the quickstart, create a separate key for Codex, and use the Codex CLI integration guide.
Disclosure: GoiAPI sells API access to the models mentioned in this article.


