AI Gateway Authentication, BYOK, Unified Billing, and Model Routing
How Cloudflare AI Gateway authenticates requests, stores provider keys, bills models, and routes Workers AI and third-party calls.
This page summarizes Cloudflare AI Gateway documentation: a proxy that adds logging, caching, rate limiting, and credential management when your apps call Workers AI or third-party model APIs.
AI Gateway: what it does and when you need it
Section titled “AI Gateway: what it does and when you need it”AI Gateway sits between your application and model providers. You point SDKs, Workers, or HTTP clients at gateway endpoints instead of calling OpenAI, Anthropic, or Workers AI directly.
Use AI Gateway to route requests across providers while maintaining a single interface: AI Gateway proxies requests to OpenAI, Anthropic, or Workers AI; built-in caching reduces costs for repeated queries; unified logging and analytics across all providers.
— Cloudflare, AI applications
You need a gateway when you want one place to observe cost and latency, enforce limits, store API keys safely, or switch models without rewriting app logic. Every AI Search instance is already tied to a gateway for embedding and reranking through external providers; Workers AI embedding and reranking on that product do not appear in gateway logs.
Authenticated Gateway: cf-aig-authorization vs Authorization
Section titled “Authenticated Gateway: cf-aig-authorization vs Authorization”AI Gateway can require a Cloudflare token on every call so strangers cannot burn your credits or fill log storage.
AI Gateway requires a valid Cloudflare API token for each request. This prevents unauthorized access and protects against invalid requests that can inflate log storage usage. When using the REST API, pass your Cloudflare API token in the standard Authorization header. When using provider-native endpoints at gateway.ai.cloudflare.com, use the cf-aig-authorization header instead.
— Cloudflare, Authenticated Gateway
| Entry point | Header for gateway auth | Typical base URL |
|---|---|---|
| REST API | Authorization: Bearer (Cloudflare API token) |
https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1/... |
| Provider-native passthrough | cf-aig-authorization: Bearer (gateway token) |
https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/... |
Worker env.AI binding |
No manual header | Pre-authenticated within the account |
For new integrations, Cloudflare recommends the REST API with the standard Authorization header. Provider-native URLs at gateway.ai.cloudflare.com remain supported with cf-aig-authorization.
Default gateway auto-creation
Section titled “Default gateway auto-creation”If you omit a gateway id, AI Gateway uses default and creates that gateway on the first authenticated request. Auto-created default turns authentication on, logging on, caching off, and rate limiting off. Only the id default auto-creates; any other id must exist before use. See Manage gateways.
Provider credentials: BYOK, Unified Billing, and request keys
Section titled “Provider credentials: BYOK, Unified Billing, and request keys”Upstream models still need credentials. AI Gateway resolves them in a fixed order.
When a request reaches AI Gateway, credentials are resolved in this order: Provider key on the request — if the request carries credentials AI Gateway recognizes for the provider and endpoint, AI Gateway uses those credentials. BYOK (stored key) — if no provider key is on the request and the gateway has a stored key for the provider under the default alias, that key is used. Unified Billing — if neither of the above applies and Unified Billing fallback is allowed, the request is served with Cloudflare-managed credentials and billed against your Cloudflare credit balance.
— Cloudflare, Unified Billing
BYOK (Store Keys): store keys in the dashboard
Section titled “BYOK (Store Keys): store keys in the dashboard”BYOK keeps provider API keys in Cloudflare Secrets Store instead of your source code.
Bring your own keys (BYOK) is a feature in Cloudflare AI Gateway that allows you to securely store your AI provider API keys directly in the Cloudflare dashboard. Instead of including API keys in every request to your AI models, you can configure them once in the dashboard, and reference them in your gateway configuration.
— Cloudflare, BYOK (Store Keys)
After BYOK is configured, omit provider auth headers so the gateway injects the stored key. If you still send a provider authorization header, AI Gateway forwards your value and does not substitute the stored key. You still need gateway authentication (cf-aig-authorization or REST Authorization) when the gateway requires it.
Multiple keys per provider use aliases. Passthrough requests can select a non-default alias with cf-aig-byok-alias. On Unified Billing paths such as env.AI.run() or /ai/v1/chat/completions, only the default alias is considered; other aliases do not block fall-through to Unified Billing.
API-created secrets must follow the name {gateway_id}_{provider_slug}_{alias} (for example my-gateway_anthropic_default).
Unified Billing and blocking wholesale fallback
Section titled “Unified Billing and blocking wholesale fallback”Unified Billing charges supported third-party models from prepaid AI Gateway credits. It requires an authenticated gateway. Workers AI through a gateway can use Standard billing (invoice at cycle end) or Unified billing (deduct credits in real time); set that when you create the gateway.
Turn on Require provider credentials (or send cf-aig-no-wholesale: true per request) to refuse Unified Billing when no request or stored key applies. Missing credentials then return HTTP 400 with error 2044.
Unified Billing on catalog or binding paths requires gateway authentication; without it, the request fails with error 2049.
How to call models: REST API, binding, and provider-native paths
Section titled “How to call models: REST API, binding, and provider-native paths”REST API: one Cloudflare auth surface
Section titled “REST API: one Cloudflare auth surface”The REST API lets you call any model — whether hosted on Cloudflare or by a third-party provider like OpenAI, Anthropic, or Google — through the same Cloudflare API, with all AI Gateway features — logging, caching, rate limiting, and more — applied automatically.
— Cloudflare, REST API
| Endpoint | Format | Workers AI (@cf/) |
|---|---|---|
POST /ai/run |
Envelope | Yes |
POST /ai/v1/chat/completions |
OpenAI chat | Yes (needs cf-aig-gateway-id) |
POST /ai/v1/responses |
OpenAI Responses | Model-dependent |
POST /ai/v1/messages |
Anthropic Messages | No |
Third-party models use author/model (for example openai/gpt-4.1, anthropic/claude-sonnet-4). Workers AI uses @cf/author/model and always requires cf-aig-gateway-id on REST calls.
Third-party REST traffic defaults to the default gateway unless you set cf-aig-gateway-id.
Workers binding: env.AI.run()
Section titled “Workers binding: env.AI.run()”Runs an inference request through AI Gateway. Accepts Workers AI models (@cf/ prefix) and third-party models (
{author}/{model}format).— Cloudflare, Workers Bindings
Pass gateway options in the third argument: id, skipCache, cacheTtl, cacheKey, collectLog, metadata. Third-party models on the binding use Unified Billing unless a BYOK key exists under the default alias.
Dynamic routes use model id dynamic/<route-name> and must set gateway.id to the gateway that owns the route. They accept OpenAI chat completions shape only; Anthropic Messages returns 400.
Provider-native URLs
Section titled “Provider-native URLs”SDKs and tools often set baseURL to paths like /anthropic, /openai, or /google-vertex-ai. Gateway auth is cf-aig-authorization; provider keys follow each vendor’s rules (Anthropic Messages needs x-api-key, not Authorization: Bearer, for request-supplied keys).
Complex providers:
- Amazon Bedrock: BYOK stores AWS JSON; gateway signs SigV4. You only send
cf-aig-authorizationwith BYOK. See Amazon Bedrock. - Google Vertex AI: BYOK stores service account JSON and region in the dashboard. See Google Vertex AI.
Model routing without code changes
Section titled “Model routing without code changes”Dynamic routing
Section titled “Dynamic routing”Dynamic routing defines flows (conditions, budgets, fallbacks) in the dashboard. Call them as dynamic/<route>. Authentication and BYOK upstream keys should be enabled before production use. Routes are scoped to one gateway; wrong gateway.id yields 404 against default.
Auto Router
Section titled “Auto Router”Auto Router picks a model when you send cloudflare/auto on compat chat completions or through env.AI.run("cloudflare/auto", ...). Response headers include cf-aig-routed-model, cf-aig-routing-reason, and cf-aig-routing-decision-id. Chat Completions and Responses API formats are supported; WebSockets are not yet supported.
OpenAI-compatible unified API
Section titled “OpenAI-compatible unified API”On compat endpoints, switch providers by changing the model string to provider/model (for example google-ai-studio/gemini-2.5-flash). See Unified API (OpenAI compat).
AI SDK and Workers: createAI
Section titled “AI SDK and Workers: createAI”For Vercel AI SDK and Agents createAI, agents/models/ai-sdk replaces deprecated ai-gateway-provider and workers-ai-provider.
Four model forms:
ai("@cf/...")— Workers AI via bindingai("anthropic/claude-opus-5.5")— catalog id (exact catalog spelling)ai("dynamic/support")— dynamic route on the configured gatewayai(anthropic("claude-opus-5-5"))— vendor model object to provider-native endpoint
Outside a Worker, use accountId, apiToken, and gateway. Token needs Workers AI Read for string ids and AI Gateway Run for model objects.
Gateway options (cacheTtl, metadata, eventId, byokAlias, vendorKey, skipCache, etc.) can sit on the provider, model, or per-call providerOptions.cloudflare; per-call wins.
Observability, cache, and metadata
Section titled “Observability, cache, and metadata”- Caching: set
cacheTtland optionalcacheKey; bypass withskipCache: true. - Logging metadata: attach
metadataandeventIdto group multi-step agent turns (custom metadata). - OpenTelemetry: optional
cf-aig-otel-trace-idandcf-aig-otel-parent-span-idon passthrough requests (OpenTelemetry).
Custom domains and Cloudflare Access
Section titled “Custom domains and Cloudflare Access”Custom domains let you call https://ai.example.com/... without account and gateway ids in the path. Cloudflare Access adds identity before requests reach the gateway; authenticated users can appear as cf.user_id in metadata. Coding agents such as Claude Code, OpenCode, and Cursor each need compatible base URLs and header patterns (REST vs cf-aig-authorization).
Common mistakes
Section titled “Common mistakes”| Symptom | Likely cause |
|---|---|
| 401 from provider | Wrong credential header for that endpoint (e.g. Anthropic Messages needs x-api-key) |
| Error 2044 | Require provider credentials on, or cf-aig-no-wholesale: true, with no request or BYOK key |
| Error 2049 | Unified Billing catalog call without gateway authentication |
| BYOK ignored | Provider authorization header still sent (including placeholders) |
| Dynamic route 404 | Route belongs to another gateway; set cf-aig-gateway-id or binding gateway.id |
| Wrong catalog model | Used vendor spelling (claude-opus-5-5) instead of catalog (anthropic/claude-opus-5.5) |
Full checks: Troubleshooting.
How to check this on your site
Section titled “How to check this on your site”-
Create or open a gateway in the Cloudflare dashboard under AI, then AI Gateway; note the gateway id and whether Authenticated Gateway is on.
-
Send a first REST API chat completion with your Cloudflare API token,
cf-aig-gateway-id: default(or your gateway id), and a Workers AI or catalog model id. -
If using BYOK, add a provider key under Provider Keys, then repeat the call without the provider’s API key header and confirm success per BYOK (Store Keys).
-
Open AI Gateway analytics and logs in the dashboard and confirm the request shows expected metadata, cache status, and model name.
-
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.