Codex CLI API Key Setup Guide 2026

Codex CLI supports two authentication methods: ChatGPT OAuth login and OpenAI API Key. This guide covers both methods in full — how to get a key, how to configure it, multi-account management, security best practices, and fixing common auth errors.

Two Authentication Methods Compared

Before configuring anything, understand the differences and pick the right method for your situation:

Comparison ChatGPT Account Login OpenAI API Key
Command codex login codex login --with-api-key
Subscription needed Plus / Pro / Business required No ChatGPT subscription needed
Billing Included in subscription Pay per token used
Best for Existing ChatGPT Plus/Pro subscribers Developers / heavy API users
Multi-key support Re-login to switch accounts Use direnv for per-project keys
i

Only one authentication method can be active at a time, but switching is instant — just re-run the appropriate codex login command.

Method 1: ChatGPT Account Login

If you have a ChatGPT Plus, Pro, Business, Edu, or Enterprise subscription, you can authenticate directly with your account — no separate API Key management required.

Login steps

Terminal
# Start the OAuth flow
$ codex login

After running the command, Codex CLI will:

  1. Print an authorization URL and attempt to open it in your browser automatically
  2. Your browser opens the ChatGPT OAuth authorization page
  3. Log in with your ChatGPT account and click "Authorize"
  4. The browser redirects back to a local callback URL; the terminal shows login success

After successful login, the auth token is saved to ~/.codex/auth.json — you won't need to log in again on subsequent codex runs.

!

Note for users behind a proxy: The ChatGPT OAuth flow involves redirecting to chatgpt.com. If your proxy only applies to the terminal (not the browser), the OAuth page may not load. Make sure your browser proxy is also configured. See the Proxy / China Guide for details.

Verifying login

Terminal
# Launch codex and check the status indicator in the bottom-left
$ codex
# "● connected" in the status bar means authentication succeeded

# Or inspect the auth file directly (key is partially masked)
$ cat ~/.codex/auth.json

Method 2: OpenAI API Key

The API Key method is more flexible — no ChatGPT subscription required, fine-grained cost control, and support for per-project keys via environment variables.

Where to get an API Key

OpenAI API Keys are managed at platform.openai.com/api-keys:

  1. Log in to platform.openai.com
  2. Click "API keys" in the left sidebar
  3. Click "Create new secret key"
  4. Give the key a descriptive name (e.g. "codex-cli-dev") for easier management later
  5. Copy the key immediately — it is shown only once. After closing the dialog, you cannot view the full key again
!

API Keys are shown only once at creation time. If you close the dialog without copying, create a new key — old keys don't disappear, but you can no longer see their value (only revoke them).

Setting up your API Key

Two ways to configure the API Key with Codex CLI:

Option 1: via codex login command (recommended)

Terminal
$ codex login --with-api-key
# The CLI prompts you to paste your API Key
# The key is stored (encrypted) in ~/.codex/auth.json

Option 2: via environment variable

Terminal — current session only
# Temporary — applies only to the current shell session
$ export OPENAI_API_KEY=sk-proj-xxxxxxxxxxxxxxxx
$ codex "test connection"

To make it permanent, add it to your shell config file (~/.zshrc or ~/.bashrc):

Add to ~/.zshrc or ~/.bashrc (permanent)
# Open the file in an editor
$ nano ~/.zshrc

# Add this line at the end (replace with your actual key):
export OPENAI_API_KEY=sk-proj-xxxxxxxxxxxxxxxx

# Reload the config
$ source ~/.zshrc
!

Security note: Do not commit your .zshrc or .bashrc to a Git repo if it contains your API Key. For production projects, use direnv to manage keys per project.

Multi-Account / Multi-Key Management

If you need different API Keys for different projects (e.g. personal vs. work accounts), here are your options:

Where credentials are stored

Codex CLI stores the current active credential in ~/.codex/auth.json. You can inspect it (the key value is partially masked):

Terminal
$ cat ~/.codex/auth.json
# Outputs something like: {"type":"api-key","key":"sk-proj-xxx...xxx"}

Switching accounts

Re-run the appropriate codex login command to switch. The new credential overwrites the existing auth.json:

Terminal — switching auth methods
# Switch to ChatGPT OAuth login
$ codex login

# Switch to API Key
$ codex login --with-api-key

# Log out (removes stored credentials)
$ codex logout
# Or manually
$ rm ~/.codex/auth.json

Per-project API Keys with direnv

direnv is the cleanest solution for using different API Keys in different projects — it automatically loads environment variables when you enter a directory and unloads them when you leave:

Install direnv and set up a project
# Install direnv (macOS)
$ brew install direnv

# Add the hook to your shell config (zsh example)
$ echo 'eval "$(direnv hook zsh)"' >> ~/.zshrc
$ source ~/.zshrc

# In your project directory, create a .envrc file (DO NOT commit this!)
$ cd /path/to/your/project
$ echo 'export OPENAI_API_KEY=sk-proj-work-account-key' > .envrc
$ direnv allow .

# Make sure .envrc is in .gitignore
$ echo '.envrc' >> .gitignore

From now on, entering this directory automatically switches OPENAI_API_KEY to the project-specific key. Leaving the directory restores your global setting.

API Key Security Best Practices

A leaked API Key gives anyone unlimited access to your OpenAI balance. Build these habits from the start:

Never commit keys to a repository

  • Never run git add .env or any file containing an API Key
  • Add protection rules to every project's .gitignore: .env, .env.local, .envrc
  • Consider using gitleaks to scan commit history for leaked secrets
.gitignore — essential rules
# API keys and environment variable files
.env
.env.*
.envrc
*.key
*_secret*

Set API spending limits

At platform.openai.com/settings/organization/limits, configure spending controls:

  • Monthly budget: API calls return 429 after the monthly cap is reached
  • Usage alerts: Email notification when spending crosses a threshold

For individual developers, a monthly cap of $5–$20 provides good protection against accidental overuse.

How to immediately revoke a leaked key

If you suspect your API Key has been leaked (e.g., accidentally pushed to a public GitHub repo), act immediately:

  1. Log in to platform.openai.com/api-keys
  2. Find the compromised key and click "Revoke" — it is invalidated instantly
  3. Create a new key and update your local configuration
  4. If committed to GitHub, check if GitHub's secret scanning already flagged it — GitHub auto-notifies OpenAI of exposed keys which may trigger auto-revocation
  5. Optionally rewrite Git history with BFG Repo Cleaner or git filter-branch to remove the key from commit history
Terminal — update local key after revocation
# After revoking the old key, log in with the new one
$ codex login --with-api-key
# Paste your new API Key when prompted

Common Authentication Errors

401 Unauthorized

Meaning: The API Key is invalid, has been revoked, or is missing.

Fix:

  • Verify OPENAI_API_KEY is correctly set (no extra spaces or newlines)
  • Confirm the key's status shows as Active at platform.openai.com/api-keys
  • If using codex login --with-api-key, re-run it and paste the key again
Terminal — diagnose key issues
# Check that the env var is set (won't display the full key)
$ echo ${OPENAI_API_KEY:0:10}...
# Should print: sk-proj-xx...

# Test the key directly with curl
$ curl https://api.openai.com/v1/models \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -s | head -c 200

403 Forbidden: Geographic restriction

Meaning: The API request came from a region where OpenAI service is not available.

Fix: Configure HTTPS_PROXY to route the API request through a proxy server in a supported region:

Terminal
$ export HTTPS_PROXY=http://127.0.0.1:7890
$ codex "test connection"

See the Proxy / China Guide for full configuration details.

Authentication required

Meaning: Codex CLI cannot find any valid credentials — you haven't completed authentication.

Fix: Run codex login (for ChatGPT OAuth) or codex login --with-api-key (for API Key) to complete authentication, then retry.

Insufficient quota / Rate limit exceeded

Meaning: Your account has hit its monthly spending cap, or you've exceeded rate limits.

Fix: Check your usage and billing at platform.openai.com/usage. If you hit the monthly budget limit, increase it or wait until the next billing cycle. For rate limits, add delays between requests or upgrade to a higher usage tier.

FAQ

Can I have both API Key and ChatGPT login active at the same time?

No — only one authentication method is active at a time. Both are stored in ~/.codex/auth.json, and running either login command overwrites the previous credential. To use different keys per project without re-running the login command each time, use direnv to set OPENAI_API_KEY per directory — this takes precedence over the stored credential.

Can I use Codex CLI with a free OpenAI account?

The ChatGPT OAuth login requires a Plus, Pro, Business, Edu, or Enterprise subscription — free accounts cannot use it. The API Key method doesn't require a ChatGPT subscription, but the OpenAI platform account needs a payment method attached (new accounts typically get $5 in free credits to get started). If you want to try Codex CLI at low cost, create an OpenAI platform account and use the API Key authentication method.

Do API Keys expire?

OpenAI API Keys don't expire automatically. They become invalid when: (1) you manually revoke the key at platform.openai.com/api-keys; (2) your account balance is zero with no payment method attached; (3) the key is detected in a public repository — OpenAI (and GitHub's secret scanning integration) may auto-revoke it. Check your key status periodically at platform.openai.com/api-keys, and always set a monthly spending limit as a safety net.

How do I know which account or key is currently active?

Inspect ~/.codex/auth.json — it shows the auth type and a partially masked key value. You can also run codex and look at the TUI status bar at the bottom left. If your version supports it, codex whoami displays the currently active authentication details.