Fix OpenCode Model Auth & Rate Limit Errors on OpenRouter
In this article
If you use OpenCode with OpenRouter as your model provider, you've likely hit authentication failures or rate limit errors mid-session. These usually stem from a missing or expired API key, incorrect environment variable names, or hitting your OpenRouter tier's request cap. This guide walks you through diagnosing and fixing both error types, from verifying your key to configuring retry logic.
What You'll Need
- Your OpenRouter API key (from
openrouter.ai/keys) - Access to your terminal or command line
- Your OpenCode configuration file location (typically
~/.config/opencode/on Linux/macOS, or%USERPROFILE%\.config\opencode\on Windows) - Optional: a text editor to modify config files
Step-by-Step
- Confirm your OpenRouter API key is valid
Visitopenrouter.ai/keysand check that your key exists and hasn't been revoked. If you see no keys, create a new one. Copy the key exactly – it starts withsk-or-. - Set the environment variable correctly
OpenCode reads theOPENROUTER_API_KEYenvironment variable. In your terminal, run:
(On Windows Command Prompt:echo $OPENROUTER_API_KEYecho %OPENROUTER_API_KEY%)
If it's empty or wrong, set it permanently. On Linux/macOS, add this to your~/.bashrcor~/.zshrc:
Then runexport OPENROUTER_API_KEY="your_key_here"source ~/.bashrc(or restart your terminal). On Windows, usesetx OPENROUTER_API_KEY "your_key_here"and restart your terminal. - Verify OpenCode picks up the key
Runopencode auth list(oropencode auth statusin newer versions) to see which providers are configured. You should see OpenRouter listed as authenticated. If not, runopencode auth loginand choose OpenRouter, then paste your key when prompted. - Check your OpenCode config for hardcoded keys
Open~/.config/opencode/config.json(oropencode.jsonin your project). Look for aprovidersection with anapiKeyfield. If it's there, update it to your current key. Also ensure the model name is correct – for example,openrouter/anthropic/claude-3.5-sonnet(the format isprovider/model). - Test a simple request directly
Run a minimal OpenCode command:
If this works, your auth is fine. If you get a 401 error, your key is still wrong or missing.opencode run "Say hello" --model openrouter/anthropic/claude-3.5-sonnet - Handle rate limit errors (429)
OpenRouter rate limits depend on your account tier (free vs paid). If you hit a 429, you have three options:- Wait and retry – the error message usually includes a
Retry-Afterheader in seconds. - Switch to a less busy model – some models have separate rate limits.
- Upgrade your OpenRouter plan for higher limits.
config.json, add:
This tells OpenCode to retry up to 3 times with a 5-second delay between attempts.{ "provider": { "openrouter": { "maxRetries": 3, "retryDelay": 5000 } } } - Wait and retry – the error message usually includes a
- Restart OpenCode completely
After any config or environment change, close all OpenCode sessions and start a new terminal window. Environment variables set withexportonly apply to the current shell. - Clear any cached credentials
If you previously used a different provider or key, OpenCode may cache old auth. Delete the auth cache file (often~/.local/share/opencode/auth.jsonon Linux,~/Library/Application Support/opencode/auth.jsonon macOS) and re-runopencode auth login.
Common Mistakes
- Using the wrong environment variable name – Some tools use
OPENROUTER_API_KEY, others useOPENROUTER_KEY. OpenCode specifically expectsOPENROUTER_API_KEY. - Copying the key with extra spaces or newline – When pasting into a terminal, a trailing newline can break the key. Use
echo -nto test. - Hardcoding a key in a shared config file – If you commit
config.jsonto a repo, your key leaks. Use environment variables instead. - Ignoring the model name prefix – OpenCode requires
openrouter/before the model name. Omitting it causes a "model not found" error that looks like an auth issue. - Assuming rate limits are per-model – OpenRouter's free tier has a global limit (e.g., 50 requests/day). Check your usage on the OpenRouter dashboard.
Tips
- Use a dedicated key for OpenCode, not one shared with other apps – this makes it easier to revoke if needed.
- Set a generous
maxRetries(3-5) and a delay of at least 2000ms to avoid hammering the API during transient rate limits. - Monitor your OpenRouter usage page to see real-time request counts and which models are consuming your quota.
- If you're on a free tier, consider using a cheaper or faster model (like
openrouter/meta-llama/llama-3.1-8b-instruct) for routine tasks to stay under limits. - Keep your OpenCode version updated – auth handling and retry logic improve frequently.
Troubleshooting
Still getting 401 after following steps?
- Run
opencode auth listand confirm the key is shown. If it shows a different key, useopencode auth logoutthen re-login. - Check if your key has expired – OpenRouter keys don't expire by default, but you may have regenerated it.
- Try using the key directly in a curl command:
If this returns an error, your key is invalid.curl https://openrouter.ai/api/v1/auth/key -H "Authorization: Bearer $OPENROUTER_API_KEY"
Rate limit persists even after waiting?
- Check your OpenRouter dashboard for the exact limit and your current usage. Free tier limits reset daily (UTC).
- If you're using a proxy or VPN, OpenRouter may see shared IPs and apply stricter limits. Try disabling it.
- Some models have separate limits – switch to a less popular model temporarily.
OpenCode says "provider not found"
- Ensure you're using the exact provider string:
openrouter(all lowercase). - Check your OpenCode version – older versions may not support OpenRouter natively. Update via your package manager.
Frequently Asked Questions
Q: Does OpenCode support OpenRouter out of the box?
A: Yes, OpenCode has built-in support. You just need to set the API key and use the openrouter/ prefix in model names.
Q: Why do I get a 401 even with a valid key?
A: Usually because the environment variable isn't set in the same shell, or the key has a typo. Double-check with echo and re-login.
Q: How do I increase my rate limit on OpenRouter?
A: Rate limits are tied to your OpenRouter account tier. You can add credits or subscribe to a paid plan to raise limits. Free tier limits are shown on your dashboard.
Q: Can I use multiple providers with OpenCode?
A: Yes, OpenCode supports multiple providers simultaneously. You can set API keys for each and specify the provider per model.
Q: What does the error "model_not_found" mean?
A: It means the model name you specified doesn't exist on OpenRouter. Check the model list at openrouter.ai/models and use the exact slug.
Q: Is there a way to test my OpenRouter key without OpenCode?
A: Yes, you can use curl to hit the API directly. A simple request to /api/v1/models with your key as a Bearer token should return a list of models.