n4nAI

Bring-your-own-key setup for Cursor and Cline

Step-by-step guide to bring your own key Cursor Cline setup using an OpenAI-compatible gateway, with config snippets and verification tips for engineers.

n4n Team5 min read1,130 words

Audio narration

Coming soon — every post will get a voice note here.

Setting up bring your own key Cursor Cline lets you point both editors at your own inference endpoint instead of the built-in subscriptions. This cuts cost, gives you model choice, and keeps your keys in your control. Below is a complete walkthrough using an OpenAI-compatible API, with runnable config and a verification step at the end.

Step 1: Provision an OpenAI-compatible key and endpoint

You need a single base URL that speaks the OpenAI chat completions protocol and a bearer token. You can use OpenAI directly, but a gateway avoids per-vendor key management. A gateway like n4n.ai exposes one OpenAI-compatible endpoint for 240+ models, with per-token metering and automatic fallback if a provider degrades.

Create your key and export it:

export BYOK_KEY="sk-your-gateway-key"
export BYOK_BASE="https://api.n4n.ai/v1"

If you run your own proxy, set BYOK_BASE to that URL. The key must be sent as Authorization: Bearer <key> on every request. Never commit this value to git; use a secrets manager or .env file with restrictive permissions.

Test the credential before touching editors:

curl "$BYOK_BASE/chat/completions" \
  -H "Authorization: Bearer $BYOK_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"say pong"}]}'

A valid response confirms the bring your own key Cursor Cline foundation is solid. If you get a 401, the key is rejected. If you get a 404, the model slug is wrong for that gateway.

Choosing a model catalog

Gateways map vendor models to their own IDs. Some use openai/gpt-4o, others use gpt-4o. Pull the gateway’s /v1/models endpoint to see exact strings:

curl "$BYOK_BASE/models" -H "Authorization: Bearer $BYOK_KEY"

Pick IDs that both Cursor and Cline can reference. Avoid models that require proprietary headers unless your gateway normalizes them.

Step 2: Configure Cursor to use your key

Cursor reads custom OpenAI credentials from its settings UI. Open Cursor, then Settings → Models. Toggle Override OpenAI Base URL and paste $BYOK_BASE. In the OpenAI API Key field, paste the value of BYOK_KEY.

If you prefer editing the config file directly, Cursor stores user settings at:

  • macOS: ~/Library/Application Support/Cursor/User/settings.json
  • Linux: ~/.config/Cursor/User/settings.json
  • Windows: %APPDATA%\Cursor\User\settings.json

Add or merge these keys:

{
  "cursor.openaiApiKey": "sk-your-gateway-key",
  "cursor.openaiBaseUrl": "https://api.n4n.ai/v1"
}

Restart Cursor after editing the file. The bring your own key Cursor Cline setup now routes all OpenAI-model traffic through your gateway.

Picking models in Cursor

Cursor lets you select the active model in the chat bar. With a gateway, any model ID the gateway supports works—gpt-4o, claude-3-5-sonnet, etc. If the gateway maps vendor names to its own catalog, use the exact ID from its docs. Cursor caches the model list on startup; if you add a new model upstream, restart the app.

Multiple projects, multiple keys

You can swap the cursor.openaiApiKey per workspace by using Cursor’s workspace settings (.cursor/settings.json in the project root). This is useful when one client pays for inference and another uses your own budget.

Step 3: Configure Cline to use your key

Cline (the VS Code AI coding agent) stores its config in VS Code’s settings.json. Open Preferences → Settings, search for cline, and edit the JSON directly:

{
  "cline.apiProvider": "openai",
  "cline.openAiApiKey": "sk-your-gateway-key",
  "cline.openAiBaseUrl": "https://api.n4n.ai/v1",
  "cline.model": "gpt-4o"
}

For a pure openai-compatible backend, apiProvider: "openai" with a custom openAiBaseUrl is sufficient. Cline will send standard /v1/chat/completions requests with the standard body shape.

If you want to use a model that requires Anthropic-style prompting, keep apiProvider: "openai-compatible" only if Cline’s version supports it; otherwise proxy the transform yourself. The bring your own key Cursor Cline approach is simplest when both tools speak the same OpenAI-shaped protocol.

Scoped keys and usage caps

Create a separate key for Cline if you want independent per-token metering. Most gateways let you set a monthly spend limit on the key. This prevents a long agent loop from burning your whole budget. In Cline’s settings, you can also lower cline.contextWindow to reduce token burn on large repos.

Cline advanced fields

Cline exposes cline.temperature and cline.maxTokens in newer builds. Set them explicitly to avoid surprising defaults:

{
  "cline.temperature": 0.2,
  "cline.maxTokens": 8192
}

Lower temperature yields more deterministic refactors; higher helps brainstorming.

Step 4: Route models and forward cache hints

Once both editors hit the same endpoint, you can centralize routing. Gateways that honor client routing directives let you pin a model per request via header or body field. For example, n4n.ai forwards provider cache-control hints, so if you send cache_control in the messages, it passes through to Anthropic or OpenAI.

To leverage prompt caching in Cline, structure your system prompt with a cache marker (Anthropic style):

{
  "model": "claude-3-5-sonnet",
  "messages": [
    {"role": "system", "content": "You are a Rust expert.", "cache_control": {"type": "ephemeral"}},
    {"role": "user", "content": "Fix the borrow checker error."}
  ]
}

Cursor’s UI does not expose cache headers, but if your gateway supports default caching policies, they apply automatically to repeated system prefixes.

Fallback behavior

When a provider is rate-limited, a gateway with automatic fallback shifts the request to a equivalent model. Your editors do not need to handle 429s. You will see slightly different latency but no failed calls. This is why the bring your own key Cursor Cline pattern is more resilient than hardcoding vendor keys.

Header injection via local proxy

If you need to add routing headers that the editors don’t support, run a tiny local proxy:

from http.server import BaseHTTPRequestHandler, HTTPServer
import urllib.request, os

class H(BaseHTTPRequestHandler):
    def do_POST(self):
        length = int(self.headers['Content-Length'])
        body = self.rfile.read(length)
        req = urllib.request.Request(
            os.environ['BYOK_BASE'] + self.path,
            data=body,
            headers={'Authorization': 'Bearer ' + os.environ['BYOK_KEY'],
                     'Content-Type': 'application/json',
                     'X-Route-Model': 'auto'})
        resp = urllib.request.urlopen(req)
        self.send_response(resp.status)
        self.end_headers()
        self.wfile.write(resp.read())

HTTPServer(('127.0.0.1', 8080), H).serve_forever()

Point Cursor and Cline at http://127.0.0.1:8080/v1. This keeps the bring your own key Cursor Cline chain fully under your control.

Step 5: Verify the setup

Verification should be independent of the UI.

Cursor: Open a new chat, select an OpenAI-model, and ask: “Write a Python function that reverses a string.” If it returns code, the key works. For deeper confirmation, check ~/.cursor/logs/ for outgoing domains; you should see your gateway, not api.openai.com.

Cline: In VS Code, open the Cline panel and run: “List the files in the current directory.” The agent will call your gateway. Check the gateway’s usage dashboard for a new token line item tied to the Cline key.

Endpoint smoke test: Run the curl from Step 1 again, but with the exact model ID you configured in the editors. If both editors and curl return completions, the chain is proven.

curl "$BYOK_BASE/chat/completions" \
  -H "Authorization: Bearer $BYOK_KEY" \
  -d '{"model":"gpt-4o","messages":[{"role":"user","content":"return 1+1"}]}'

Expect a JSON choices array. Any 401 means the key is wrong; 404 means the model ID is unknown to the gateway.

Token metering check

Most gateways return usage in the response body. Print it:

curl -s "$BYOK_BASE/chat/completions" \
  -H "Authorization: Bearer $BYOK_KEY" \
  -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"hi"}]}' \
  | python -m json.tool | grep usage -A5

If you see prompt_tokens and completion_tokens, metering works. This is the final proof that the bring your own key Cursor Cline wiring is live.

Troubleshooting

401 Unauthorized — Key not sent as bearer, or copied with whitespace. Use echo $BYOK_KEY | tr -d '\n'.

404 Model not found — Your gateway may use slug names like openai/gpt-4o. Check its model list.

CORS errors in Cursor — Cursor makes browser-side requests for some features. Ensure your gateway sends Access-Control-Allow-Origin: * or whitelists the Cursor origin.

Cline stalls — If apiProvider is set to anthropic but base URL is OpenAI-shaped, requests hang. Switch to openai.

High latency — Fallback may be routing to a slower region. Pin a model explicitly or check gateway status.

Why this beats native subscriptions

The bring your own key Cursor Cline setup gives you one billing relationship, one key to rotate, and access to every model the gateway supports. You can switch from GPT-4o to Claude mid-session without re-authenticating. When a vendor has an outage, fallback keeps your IDE usable.

Set it up once, meter per project, and keep your inference stack under your own control.

Tagsbyokcursorclineapi-keys

Written by

n4n Team

The team building n4n — a single OpenAI-compatible API in front of 240+ models, with automatic fallback, load balancing and pay-per-token metering.

More from n4n Team →

All best api for coding assistants & ai ides posts →