Skip to content

Authenticated Gateway

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.

Setting up Authenticated Gateway using the dashboard

  1. Go to the Settings for the specific gateway you want to enable authentication for.
  2. Select Create authentication token to generate a custom token with the required Run permissions. Be sure to securely save this token, as it will not be displayed again.
  3. Include the API token in each request:
    • If using the REST API (/ai/run), include your Cloudflare API token in the standard Authorization header.
    • If using provider-native endpoints at gateway.ai.cloudflare.com, use the cf-aig-authorization header.
  4. Return to the settings page and toggle on Authenticated Gateway.

Example requests

Terminal window
curl -X POST "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions" \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
--header "Content-Type: application/json" \
--data '{"model": "openai/gpt-4.1-mini", "messages": [{"role": "user", "content": "What is Cloudflare?"}]}'

Using the OpenAI SDK:

JavaScript
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: CLOUDFLARE_API_TOKEN,
baseURL: `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/ai/v1`,
});
const response = await openai.chat.completions.create({
model: "openai/gpt-4.1-mini",
messages: [{ role: "user", content: "What is Cloudflare?" }],
});

Using the Vercel AI SDK:

JavaScript
import { createOpenAI } from "@ai-sdk/openai";
const openai = createOpenAI({
apiKey: CLOUDFLARE_API_TOKEN,
baseURL: `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/ai/v1`,
});

Expected behavior

The following table outlines gateway behavior based on the authentication settings and header status:

Authentication SettingHeader InfoGateway StateResponse
OnHeader presentAuthenticated gatewayRequest succeeds
OnNo headerErrorRequest fails due to missing authorization
OffHeader presentUnauthenticated gatewayRequest succeeds
OffNo headerUnauthenticated gatewayRequest succeeds