---
title: Build your startup's AI features on Vercel AI Gateway
description: Build customer-facing AI features with Vercel AI Gateway, including authentication, model fallbacks, usage attribution for each customer, data controls, and budgets.
keywords: ["AI Gateway","Startups","AI SDK"]
url: "https://vercel.com/kb/guide/startups-on-vercel-ai-gateway"
published: 2026-12-01
last_updated: 2026-12-01
authors: Ben Sabic
related_resources:
  - title: "Build your startup's product on Vercel Sandbox"
    url: "/kb/guide/startups-on-vercel-sandbox"
    description: "Build code interpreters, app previews, and upload-processing features with Vercel Sandbox, including authentication, persistence, security, and cost controls."
  - title: "Build AI agents with AI Gateway and AI SDK"
    url: "/kb/guide/ai-gateway-and-ai-sdk"
    description: "Build AI agents on Vercel with AI Gateway and AI SDK, then make them reliable, capable, and durable with Sandbox, Chat SDK, Vercel Connect, and Workflow."
  - title: "Cost-aware model routing with Vercel AI Gateway"
    url: "/kb/guide/cost-aware-model-routing-with-ai-gateway"
    description: "Send easy requests to a lower-cost model and escalate only the complex ones to a frontier model through AI Gateway, with budgets and spend tracking."
  - title: "How to control AI provider data handling with AI Gateway"
    url: "/kb/guide/control-ai-provider-data"
    description: "Prevent AI providers from training on your prompts, enforce zero data retention, and restrict providers and models with Vercel AI Gateway."
install_vercel_plugin: npx plugins add vercel/vercel-plugin
search_with_vercel_cli: npx vercel@latest kb search "<query>"
read_with_vercel_cli: "npx vercel@latest kb inspect startups-on-vercel-ai-gateway"
---

[Vercel AI Gateway](https://vercel.com/docs/ai-gateway) is a hosted API that sends your product's model requests to providers such as OpenAI, Anthropic, and Google through one credential. It retries failed requests on other providers and records what each request cost, so your team doesn't operate a proxy.

Your backend still authenticates customers, enforces their quotas, and decides what data enters a prompt. AI Gateway handles model routing and usage records for those requests. If you're still choosing a gateway, [compare AI gateways](https://vercel.com/i/best-ai-gateways).

## Decide whether AI Gateway fits your product

AI Gateway is [generally available](https://vercel.com/blog/ai-gateway-is-now-generally-available), and every Vercel team has a free tier and a paid tier. Your backend calls `https://ai-gateway.vercel.sh` through the [AI SDK](https://vercel.com/docs/ai-gateway/sdks-and-apis/ai-sdk), an [OpenAI or Anthropic SDK](https://vercel.com/docs/ai-gateway/sdks-and-apis), or plain HTTP, and it doesn't need to run on Vercel. AI Gateway adds [no markup to token prices](https://vercel.com/docs/ai-gateway/pricing), including BYOK inference billed by your provider. Optional gateway features and BYOK without fallback have separate fees.

For each request, AI Gateway chooses a provider that serves the model, based on recent uptime and latency, and tries another when that one is unavailable. It records the status, provider, latency, token usage, cost, and every routing attempt. Your code names a model as `creator/model-name`, such as `anthropic/claude-sonnet-5`, so switching models is a one-string change.

AI Gateway fits when your product depends on more than one model or provider, or when a provider outage would reach your customers. For how a gateway differs from a model router or an API gateway, read [what an AI gateway is](https://vercel.com/i/what-is-an-ai-gateway). Configure routing, usage attribution, and caching for the feature you are building:

| Product pattern                                    | What AI Gateway does                                                               | Main settings                              |
| -------------------------------------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------ |
| Customer-facing feature that has to stay available | Tries the model's other providers, then your fallback models, when a request fails | `models`, `order`                          |
| Usage attribution and billing for each customer    | Records spend against the user ID and tags you send with each request              | `user`, `tags`, `gateway.getSpendReport()` |
| Lower cost for each request as volume grows        | Applies each provider's prompt caching and ranks providers by price                | `caching: 'auto'`, `sort: 'cost'`, BYOK    |

[Zo Computer](https://vercel.com/blog/how-zo-computer-improved-ai-reliability-20x-on-vercel) is an 8-person company that moved model calls to the AI SDK and AI Gateway. The gateway handles retries, fallback routing, and provider health monitoring that previously ran in Zo's codebase. Zo reports its retry rate fell from 7.5% to 0.34% during a rollout comparing Vercel and non-Vercel routes in parallel.

### Check hosting and application requirements

AI Gateway runs on Vercel's infrastructure and forwards each request to a model provider. If your gateway must run inside your own network, choose a self-hosted option. For a product that will keep using one model from one provider, [calling the provider directly](https://vercel.com/i/ai-gateway-vs-openai-api-direct) also removes a routing layer.

Your application handles storage and customer access:

- [Cache complete responses](https://vercel.com/docs/ai-gateway/models-and-providers/automatic-caching#cache-responses-in-your-application) in your application to reuse an answer. AI Gateway's prompt caching reduces inference costs without saving responses.
  
- Store prompts and outputs needed for evaluations in your own system. AI Gateway deletes that content after each request; [its logs](https://vercel.com/docs/ai-gateway/observability-and-spend/logs) keep metadata.
  
- Check each customer's allowance in your application before making a model call. [Gateway budgets](https://vercel.com/docs/ai-gateway/observability-and-spend/budgets) cap spend for team, project, API-key, and member scopes; sending a customer ID for reporting does not create a customer quota.
  

## Prerequisites

Before you begin, make sure you have:

- A [Vercel account](https://vercel.com/signup).
  
- AI Gateway Credits for your selected models. The free tier supports a [subset of models](https://vercel.com/ai-gateway/models?freeTier=true) with lower per-model rate limits. Other models and all requests using your own provider keys require [purchased credits](https://vercel.com/docs/ai-gateway/pricing).
  
- An existing Next.js App Router project with AI SDK 7.
  

For local development, use Node.js 24+ and the latest [Vercel CLI](https://vercel.com/docs/cli).

## Build with your agent

Use this prompt in your application's repository to add model fallbacks, usage attribution for each customer, or lower-cost requests with AI Gateway.

### Agent prompt

```txt
Help me add an AI feature to this application with Vercel AI Gateway, using https://vercel.com/kb/guide/startups-on-vercel-ai-gateway and its linked documentation. Read and follow the guide using the Vercel CLI: `npx vercel@latest kb inspect startups-on-vercel-ai-gateway`.

Inspect the repository and its dependencies first. If the intended feature isn't clear, ask whether I want a customer-facing feature with model fallbacks, usage attribution for each customer, or lower-cost requests with prompt caching. Implement the selected pattern using the application's existing framework and conventions.

1. Configure server-side AI Gateway authentication for local development and deployment. Use Vercel OIDC when available, and explain any required environment variables without printing secrets.
2. Apply the application's authentication, rate limiting, and input validation before each model call. Take the customer ID from the authenticated session, never from the client. Identify missing application-specific integrations instead of inventing them.
3. Call models through AI Gateway with the AI SDK version the repository already uses, or AI SDK 7 if it has none. Check every model and provider slug against the AI Gateway model catalog before using it.
4. For customer-facing routes, set fallback models and a provider order, and return a safe stream error when every attempt fails. Distinguish retries before streaming from failures after output begins. Avoid the `only` filter unless I name a requirement for specific providers.
5. Attach an opaque customer ID and feature tags to each request. Keep prompt text, personal data, and credentials out of them. Record each request's reported cost with the customer ID in the application's own storage. Keep Gateway keys on the server, and restrict spend reports to trusted staff because they cover the team.
6. Ask which data policies the feature needs, then apply zero data retention and disallow prompt training on the requests that need them. Handle the case where no provider qualifies.
7. Type-check the implementation and test success, provider failure, HTTP 402, and HTTP 429 paths. Use local mocks where needed and distinguish those results from live AI Gateway requests.

Return the changed files, required configuration, checks performed, and remaining deployment steps. Explain the relevant plan requirements, add-on charges, and usage costs before running live requests.

To find other KB guides, such as ones on related topics or next steps, search the Vercel Knowledge Base with the Vercel CLI: `npx vercel@latest kb search "<topic>"`
```

## Set up authentication

Every request to AI Gateway needs an [AI Gateway API key or a Vercel OIDC token](https://vercel.com/docs/ai-gateway/authentication-and-byok). Applications deployed on Vercel can use the project's OIDC token, which leaves no long-lived key to store.

Install the AI SDK in your Next.js project:

**pnpm**

```bash
pnpm i ai
```

**npm**

```bash
npm i ai
```

**yarn**

```bash
yarn add ai
```

**bun**

```bash
bun add ai
```

Run these commands from your project directory. Link an existing Vercel project or create one when prompted:

```bash
vercel link
vercel env pull
```

`vercel env pull` saves a `VERCEL_OIDC_TOKEN` in `.env.local` for the AI SDK. [Development tokens expire after 12 hours](https://vercel.com/docs/ai-gateway/authentication-and-byok/oidc), so rerun the command to refresh them. On Vercel, the SDK retrieves and refreshes tokens per request.

Create `app/api/gateway-check/route.ts` for a local authentication test, then delete it before deployment because it has no access checks. Each call uses AI Gateway Credits; teams without purchased credits must choose a [free-tier model](https://vercel.com/ai-gateway/models?freeTier=true):

```typescript
import { generateText } from 'ai';

export async function GET() {
  const { text } = await generateText({
    model: 'openai/gpt-6-astra',
    prompt: 'Reply with the word ready.',
  });

  return Response.json({ text });
}
```

Start the development server:

**pnpm**

```bash
pnpm dev
```

**npm**

```bash
npm run dev
```

**yarn**

```bash
yarn dev
```

**bun**

```bash
bun dev
```

From another terminal, request the route:

```bash
curl http://localhost:3000/api/gateway-check
```

The response is a JSON object with a `text` field, and the wording varies by model. The AI SDK sends plain string model IDs through AI Gateway, so the route names no provider. The request also appears in [AI Gateway Logs](https://vercel.com/docs/ai-gateway/observability-and-spend/logs) with its model, provider, token usage, and cost, which can take about 90 seconds.

The AI SDK uses a non-empty `AI_GATEWAY_API_KEY` ahead of the OIDC token, even when the key is invalid. To use OIDC in a deployment, remove that variable from the project's environment variables.

### Authenticate outside Vercel

Use an [AI Gateway API key](https://vercel.com/docs/ai-gateway/authentication-and-byok/api-keys) when your backend runs on another cloud or in CI. The Vercel CLI creates the key under its current team scope, so change teams with [`vercel switch`](https://vercel.com/docs/cli/switch) first if you belong to more than one. Then create the key:

```bash
vercel ai-gateway api-keys create --name backend-production
```

The CLI prints the key once. Save it as `AI_GATEWAY_API_KEY` in your backend's secret store, where the AI SDK reads it. [Python](https://vercel.com/docs/ai-gateway/sdks-and-apis/python), [Go](https://vercel.com/docs/ai-gateway/sdks-and-apis/go), and other backends connect with an OpenAI or Anthropic SDK by changing its base URL.

Keys stay valid until you revoke them or they reach an expiration you set. When the team member who created a key leaves your team, Vercel deactivates that key, so replace a departing teammate's production keys before they go.

### Use your own provider keys

If your startup has credits or negotiated pricing with a provider, add that provider's key with [Bring Your Own Key (BYOK)](https://vercel.com/docs/ai-gateway/authentication-and-byok/byok). AI Gateway then uses your credentials first for that provider and adds no markup, and the provider bills you directly. Your application still authenticates to AI Gateway with its API key or OIDC token.

BYOK is available on the paid tier and needs purchased AI Gateway Credits and a positive balance. **Fallback to Vercel Keys** is enabled by default, allowing a failed request on your credentials to retry with Vercel's provider keys and charge that usage to your credits.

Turning fallback off prevents those retries and adds a $0.20 fee per 1,000 successful requests served by your credentials. Enabled add-on charges still apply, and requests without a positive balance receive a `402`.

## Keep a customer-facing feature available

Support assistants and in-product chat fail in front of a customer when their one provider returns an error or a rate limit. AI Gateway already retries a failed request on the model's other providers. In the [AI Gateway production index](https://vercel.com/blog/ai-gateway-production-index) published in May 2026, roughly 3.5% of requests on AI Gateway completed after a fallback. Add [fallback models](https://vercel.com/docs/ai-gateway/models-and-providers/model-fallbacks) for the case where every provider of your primary model fails.

Create `app/api/chat/route.ts` for the streaming feature. Authentication, rate limiting, and input validation depend on your application and are omitted here. Add those checks to this and the other feature routes before deployment:

```typescript
import { streamText } from 'ai';

export async function POST(request: Request) {
  const { prompt } = await request.json();

  const result = streamText({
    model: 'anthropic/claude-sonnet-5',
    prompt,
    providerOptions: {
      gateway: {
        models: ['openai/gpt-6-astra', 'google/gemini-3.1-pro-preview'],
        order: ['anthropic', 'bedrock'],
      },
    },
  });

  return result.toUIMessageStreamResponse({
    onError: () => "We couldn't complete your request. Please try again later.",
  });
}
```

With your development server running, send a prompt:

```bash
curl http://localhost:3000/api/chat \
  -H 'Content-Type: application/json' \
  -d '{"prompt":"How do I reset my password?"}'
```

The route streams its response. AI Gateway tries `anthropic/claude-sonnet-5` on Anthropic, then on Amazon Bedrock, then on the model's remaining providers. If all of them fail, it tries `openai/gpt-6-astra` and then `google/gemini-3.1-pro-preview`, each on the providers that serve it. To see which model and provider answered, select the request in AI Gateway Logs, which lists every routing attempt.

These options decide where a request can go:

- `models` lists fallback models in the order to try them. AI Gateway moves to the next model only after all providers for the current one fail.
  
- [`order`](https://vercel.com/docs/ai-gateway/models-and-providers/provider-filtering-and-ordering) names the providers to try first for each model. Providers you leave out stay available after the listed ones, so failover still works. Providers that hold the conversation's prompt cache can go ahead of your order.
  
- `only` limits routing to the providers you name. Use it when a requirement restricts provider choice; the request fails if every allowed provider is unavailable or rate limited.
  

Test your prompts against every fallback model, because any of them can answer a request. The AI SDK's `maxRetries` retries retryable failures while starting a model call, up to twice by default.

Once streaming begins, errors arrive through the stream and its HTTP status may already be `200`. Use `onError` in `toUIMessageStreamResponse()` to provide a safe message, and have your client handle the stream's error event. AI SDK 7 also supports opt-in `streamRetries`, but a retried step can append repeated partial text. See [streaming error handling](https://ai-sdk.dev/docs/ai-sdk-core/error-handling).

Y Combinator-backed [Interfaze](https://vercel.com/blog/how-interfaze-serves-50-million-requests-a-month-on-vercel) uses AI Gateway to choose providers and fail over after errors or rate limits. For a feature that also needs tools, structured output, and durable steps, [build an agent](https://vercel.com/kb/guide/ai-gateway-and-ai-sdk) with AI Gateway and the AI SDK.

## Attribute usage to each customer

Usage-based pricing and margin tracking both depend on knowing what each customer's requests cost. AI Gateway records spend against a `user` and `tags` that you attach to a request, and [Custom Reporting](https://vercel.com/docs/ai-gateway/observability-and-spend/custom-reporting) returns the totals.

> **Note:**
>
> Custom Reporting bills $0.075 per 1,000 tag or user ID writes and $5 per 1,000 report queries from your AI Gateway Credits. Each distinct tag and user ID counts separately, so a request with one of each incurs two writes.

Create `app/api/summarize/route.ts`. The `getCustomerId()` function in this file trusts a request header so that you can test the route locally. Replace it with your application's session lookup before you deploy, because a customer ID that comes from the client lets one customer's usage count against another:

```typescript
import { generateText } from 'ai';

// Replace with your application's session lookup. This version trusts a
// request header so that you can test the route locally.
async function getCustomerId(request: Request): Promise<string | null> {
  return request.headers.get('x-customer-id');
}

export async function POST(request: Request) {
  const customerId = await getCustomerId(request);
  if (!customerId) {
    return Response.json({ error: 'Not signed in.' }, { status: 401 });
  }

  const { text: input } = await request.json();

  const result = await generateText({
    model: 'anthropic/claude-sonnet-5',
    prompt: `Summarize this text in three sentences:\n\n${input}`,
    providerOptions: {
      gateway: {
        user: customerId,
        tags: ['feature:summarize'],
      },
    },
  });

  const gatewayMetadata = result.providerMetadata?.gateway;

  return Response.json({
    text: result.text,
    cost: gatewayMetadata?.cost ?? null,
    generationId: gatewayMetadata?.generationId ?? null,
  });
}
```

Send a request for a test customer:

```bash
curl http://localhost:3000/api/summarize \
  -H 'Content-Type: application/json' \
  -H 'x-customer-id: customer_123' \
  -d '{"text":"AI Gateway routes model requests across providers '\
'and records what each request cost."}'
```

The JSON response includes the summary in `text`, the reported cost in `cost`, and a `generationId`. In production, store that cost with the authenticated customer ID in your usage table. Account for enabled add-on charges separately.

- `user` accepts one opaque internal account ID of up to 256 characters. Keep prompt text and credentials out of it.
  
- `tags` accepts up to 10 tags of 1 to 64 characters for details such as the feature or plan. One user ID and one tag incur two writes.
  
- `gateway.cost` provides the cost reported for the generation. Use the generation ID to reconcile that record with your usage data; it is not a complete invoice for enabled Gateway features.
  

[Aperture](https://vercel.com/blog/how-tailscale-built-a-customer-facing-model-router-on-ai-gateway) is Tailscale's customer-facing model router, built on AI Gateway. Because AI Gateway returns cost and usage on every request, Aperture shows spend to customers without Tailscale maintaining price tables for each provider. To offer your own customers a choice of models, [build a model router](https://vercel.com/kb/guide/how-to-build-your-own-ai-model-router) on the same routes.

### Report spend by customer

Create `scripts/usage.mjs` to query team spend from a trusted terminal or scheduled job. Reporting is available on Pro and Enterprise, excluding Pro trials, and each query covers your team's requests:

```javascript
import { gateway } from 'ai';

const [startDate, endDate] = process.argv.slice(2);
const isDate = value => {
  if (!/^\d{4}-\d{2}-\d{2}$/.test(value ?? '')) return false;
  const date = new Date(`${value}T00:00:00Z`);
  return !Number.isNaN(date.getTime()) &&
    date.toISOString().slice(0, 10) === value;
};

if (!isDate(startDate) || !isDate(endDate) || startDate > endDate) {
  throw new Error('Pass valid start and end dates as YYYY-MM-DD, in order.');
}

const report = await gateway.getSpendReport({
  startDate,
  endDate,
  groupBy: 'user',
});

console.log(JSON.stringify(report.results, null, 2));
```

Run the script from your project directory, replacing the dates with a range that includes your test request. Each run makes a billed report query. The command loads the local OIDC token from `.env.local`:

```bash
node --env-file=.env.local scripts/usage.mjs 2026-12-01 2026-12-31
```

The script prints one row for each `user`, including `totalCost` and `requestCount`. Dates are inclusive and use UTC, and requests can take a few minutes to appear. `totalCost` tracks charged inference spend and is zero for BYOK, while `marketCost` includes BYOK at market prices.

For scheduled reports, configure a [server-side Gateway key](#authenticate-outside-vercel) because a locally pulled OIDC token expires after 12 hours. Store the report rows to avoid repeating billed queries, and reconcile them with your invoice for Gateway fees and add-ons.

### Bill customers and enforce their limits

#### Send usage to your billing system

If you use Stripe Billing Meters, AI Gateway can [send token usage to Stripe](https://vercel.com/docs/ai-gateway/ecosystem/stripe-billing) after a successful response. Creating the required meter needs Stripe's private preview for `model` and `token_type` dimensions; existing configured meters still work.

Set the meter's event name to `token-billing-tokens`, then send `stripe-customer-id` and a server-side `stripe-restricted-access-key` with permission to write meter events. Metering is non-blocking, so an event failure does not prevent the customer receiving the response.

For new billing integrations, Stripe recommends Metronome. AI Gateway's Stripe headers do not send Metronome events, so record response usage in your application and deliver it through your billing integration. Use that approach with other billing systems too.

#### Enforce customer allowances

AI Gateway budgets apply to your team, a project, an API key, or a team member. Check each customer's recorded spend in your application before the model call, and return an error when they pass their quota.

You can assign a separate server-side key to each customer and give it [its own budget](https://vercel.com/docs/ai-gateway/observability-and-spend/budgets#api-key-budgets), but keep those keys on your backend. Keys can also authenticate access to [team-wide spend reports](https://vercel.com/docs/ai-gateway/observability-and-spend/custom-reporting), so expose customer usage through an application endpoint that verifies who can read it.

## Lower the cost of each request

Document Q&A sends the same document with every question, which suits [prompt caching](https://vercel.com/docs/ai-gateway/models-and-providers/automatic-caching). Create `app/api/ask/route.ts`, and limit the size of `document` in your own code before you deploy it:

```typescript
import { generateText } from 'ai';

export async function POST(request: Request) {
  const { document, question } = await request.json();

  const result = await generateText({
    model: 'anthropic/claude-sonnet-5',
    instructions: `Answer questions using only this document:\n\n${document}`,
    prompt: question,
    providerOptions: {
      gateway: {
        caching: 'auto',
        sort: 'cost',
        tags: ['feature:document-qa'],
      },
    },
  });

  return Response.json({
    text: result.text,
    cacheReadTokens: result.usage.inputTokenDetails.cacheReadTokens ?? 0,
  });
}
```

Create a test document that is long enough for a provider to cache:

```bash
awk '
BEGIN {
  for (i = 1; i <= 400; i++) {
    print "Deployment check " i ": Production deployments require " \
      "two approving reviewers and all automated checks to pass before release."
  }
}' > deployment-runbook.txt
```

With jq installed, send the same document twice to test cache reuse:

```bash
jq -n --rawfile document deployment-runbook.txt '{
  "document": $document,
  "question": "What is required before a production deployment?"
}' | curl http://localhost:3000/api/ask \
  -H 'Content-Type: application/json' \
  --data-binary @-
```

In the second response, a `cacheReadTokens` value above 0 confirms that the provider read part of the prompt from its cache. Zero can mean a cache miss, a prompt the provider won't cache, or missing usage details from the provider.

- `caching: 'auto'` adds cache markers for providers that need them, such as Anthropic and MiniMax. OpenAI, Google, and DeepSeek cache repeated prompt prefixes on their own. In both cases, cached input tokens are billed at the provider's reduced cache-read rate.
  
- `sort: 'cost'` tries the providers that serve the model from the lowest estimated cost up. Providers with degraded health are pushed down the order, and a provider that already holds a conversation's cache can go first.
  

The route puts the document in `instructions` and the question in `prompt`, because caching reuses a prompt prefix and [request-specific content belongs after the stable part](https://vercel.com/i/prompt-caching-across-providers). With Anthropic's default five-minute cache, one read of the same prefix before it expires offsets the higher cache-write cost. Leave `caching` unset for requests that never repeat.

Three other changes lower cost:

- Move tasks to a lower-priced model where it meets your quality bar. The [model catalog](https://vercel.com/ai-gateway/models) lists each model's price for each provider, and [some models cost less through AI Gateway](https://vercel.com/docs/ai-gateway/pricing/discounts) than the provider's list price. To send simpler requests to a cheaper tier and escalate the rest, set up [cost-aware model routing](https://vercel.com/kb/guide/cost-aware-model-routing-with-ai-gateway).
  
- Use BYOK to spend provider credits or access negotiated rates. Eligible [ChatGPT](https://vercel.com/i/chatgpt-api-credits-ai-gateway) and [Claude](https://vercel.com/i/claude-api-credits-ai-gateway) subscription API credits stay with the provider and are accessed through that organization's key.
  
- Ask about [volume discounts](https://vercel.com/docs/ai-gateway/pricing/discounts) once your spend supports a commitment. Custom discounts on token spend vary by model and spend.
  

[Featured](https://vercel.com/blog/how-featureds-users-make-100k-media-pitches-per-month-on-vercel) has three engineers and reports routing across 17 models through the AI SDK and AI Gateway, where swapping a provider is a configuration change. Before you move production traffic to an open-weight model, read about [license conditions and what changes when you swap models](https://vercel.com/i/open-weight-models).

## Control where customer data goes

Larger customers ask where their prompts go, who keeps them, and whether a model trains on them. AI Gateway doesn't retain the prompts or responses in your requests. It deletes that content when a request completes and keeps [request metadata](https://vercel.com/docs/ai-gateway/faq#what-does-ai-gateway-log-about-my-requests), such as the model, provider, token usage, cost, and duration. Vercel doesn't train on your prompts.

What a provider does with a request is a separate question, and these controls decide which providers can receive it:

| Control                                                                                                                            | Effect                                                                           | Plan and cost                                                                                  |
| ---------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| [`zeroDataRetention: true`](https://vercel.com/docs/ai-gateway/security-and-compliance/zdr) on a request                           | Routes only to providers with a zero data retention (ZDR) agreement              | Pro, Enterprise, or purchased credits. No additional cost.                                     |
| Team-wide ZDR                                                                                                                      | Applies ZDR routing across the team, except keys with an owner-granted exemption | Pro, Enterprise, or purchased credits. $0.10 per 1,000 billed requests.                        |
| [`disallowPromptTraining: true`](https://vercel.com/docs/ai-gateway/security-and-compliance/disallow-prompt-training) on a request | Routes only to providers that don't train on your prompts                        | All teams. No additional cost.                                                                 |
| [Model allowlist](https://vercel.com/docs/ai-gateway/security-and-compliance/model-allowlist)                                      | Rejects requests for models you haven't approved with a `403`                    | Pro and Enterprise. $0.10 per 1,000 billed requests.                                           |
| [Provider allowlist](https://vercel.com/docs/ai-gateway/security-and-compliance/provider-allowlist)                                | Removes providers you haven't approved from routing                              | Pro and Enterprise. $0.10 per 1,000 billed requests, charged once when both allowlists are on. |

Pro trials need purchased credits for ZDR and cannot use the team allowlists. Team owners can issue API keys exempt from team settings, so include those exceptions when reviewing which credentials can process customer data.

To apply both data policies to one feature, add them to the model call. This excerpt replaces the `providerOptions` in `app/api/summarize/route.ts`:

```typescript
providerOptions: {
  gateway: {
    user: customerId,
    tags: ['feature:summarize'],
    zeroDataRetention: true,
    disallowPromptTraining: true,
  },
},
```

With both policies enabled, requests using Vercel's provider keys go only to providers that meet both requirements. Successful ZDR responses include `enabledZeroDataRetention: true` in the gateway metadata. An ineligible team receives a `403`; if no qualifying provider serves the model, the request fails with a `400`. Handle those errors without retrying outside the required policies.

State these limits when a customer asks about ZDR:

- ZDR relies on providers' stated policies or agreements with Vercel.
  
- Provider-run tools, including web search, fall outside ZDR coverage.
  
- AI Gateway excludes short-lived prompt caches from retained data.
  
- With BYOK, your provider agreement governs. AI Gateway skips your keys under ZDR unless a team owner marks them as compliant; the prompt-training filter does not apply to BYOK requests.
  

Only team owners can change the allowlists. Once one is on, new models and providers that AI Gateway adds start disabled. The provider allowlist also removes failover to the providers you disable, so keep at least one provider enabled for each model you depend on.

[Pin the inference region](https://vercel.com/docs/ai-gateway/security-and-compliance/regional-inference) when a customer requires model execution in a particular location. Requests fail if AI Gateway cannot honor the region, but this setting does not choose where the gateway receives them; that requires separate regional hosting. Gateway-run web search can send data outside the region, and the provider's regional rate may be higher.

To write the policy for each feature before you configure it, follow the guide on [controlling provider data handling](https://vercel.com/kb/guide/control-ai-provider-data). [Okara](https://vercel.com/blog/how-okara-runs-cmo-agents-for-120000-companies-on-vercel) is a team of four and reports using AI Gateway's ZDR support for its privacy-sensitive secure chat.

### Scope credentials and identify end users

Keep AI Gateway credentials on the server, and create one API key for each service or environment, with an expiration for temporary work. [Mercor](https://vercel.com/blog/how-mercor-ships-internal-apps-and-billions-of-production-tokens-on-one-platform) gives its engineers per-user keys that carry expiration dates and spend limits.

Set the gateway's [`safetyIdentifier`](https://vercel.com/docs/ai-gateway/security-and-compliance/safety-identifiers) to an opaque end-user ID of up to 64 characters, such as a hash of your internal ID. AI Gateway forwards it to supported providers, including OpenAI and Anthropic, so they can investigate abuse and decide how to enforce their policies.

## Control what you spend

When Vercel's provider keys serve a request, AI Gateway deducts the usage charge from your [AI Gateway Credits](https://vercel.com/docs/ai-gateway/pricing) balance at the listed rate for the model and provider. BYOK inference is billed by your provider, while applicable AI Gateway fees and add-ons draw from your Gateway balance. You're responsible for any payment processing fees that apply, and purchased credits expire one year after purchase.

Every team starts on the free tier, which is a monthly included credit for a subset of models with lower rate limits. The credit starts with your first request and needs a valid payment method on the team. Purchasing credits moves your team to the paid tier, where the monthly free credit no longer applies.

Every request needs a positive credit balance, including BYOK requests. For a production app, select your credits balance in the AI Gateway dashboard, then **Change** next to **Auto-reload**, and set **When balance falls below** and **Reload to target balance**. Auto-reload is off by default. Once it's on, AI Gateway charges your payment method each time the balance drops below the threshold.

### Set budgets

[Budgets](https://vercel.com/docs/ai-gateway/observability-and-spend/budgets) limit spend for your team, a project, an API key, or a team member, with a daily, weekly, or monthly refresh. Team owners and members with the AI Gateway Budget Manager permission can set the team budget.

> **Warning:**
>
> When a team budget is exceeded, AI Gateway rejects every request from your team with a `402` until the budget resets or you raise it. Set the limit above your expected spend, so that it stops a runaway loop and leaves normal traffic alone.

Set a team budget with the CLI, replacing `500` with your monthly limit in dollars. The new limit appears on the AI Gateway **Budgets** page:

```bash
vercel ai-gateway budgets set team --amount 500 --refresh-period monthly
```

AI Gateway checks budgets when each request starts, so in-flight requests can complete after a limit is crossed and total spend can exceed it. Changes to a budget can take a few minutes to apply. Spend alerts are off by default; choose 50%, 75%, or 100% email thresholds when you add or edit a budget.

BYOK token spend is excluded by default, but `--include-byok` can include it in an API key's quota when you create the key. The fee for BYOK without fallback counts toward budgets either way. Keep provider-side spending controls for charges on your own provider account.

In your routes, treat a `402` with the type `quota_for_entity_exceeded` as a budget rejection. Return your own message, and don't retry the request with another key.

### Track spend

The AI Gateway Overview charts spend over time, and [Logs](https://vercel.com/docs/ai-gateway/observability-and-spend/logs) show each request's cost. Use `user` and `tags` to [attribute spend to customers and features](#attribute-usage-to-each-customer). For runaway agent loops and budgets for each key, read about [LLM cost management](https://vercel.com/i/llm-cost-management-track-control-model-spend).

### Get credits through Vercel's startup programs

#### Vercel startups program

The [Vercel startups program](https://vercel.com/startups) accepts companies affiliated with an approved Startups Partner, such as an accelerator or venture firm. Eligible startups have raised a Series A or less, apply within 12 months of their latest funding round, and have not received Vercel for Startups credits before.

Startups accepted on or after August 6, 2026 receive a Flexible Commitment Amount of up to $30,000 that can cover AI Gateway usage; earlier legacy credits cannot. The [AI Gateway allocation](https://vercel.com/startups/credits) is capped at 50%, with excess usage billed at standard rates. Confirm how that cap applies to your allocation with the startups team before budgeting.

#### Vercel X

[Vercel X](https://vercel.com/x) is a six-week, in-person accelerator for pre-seed founders building AI companies. It takes no equity and offers a program-wide pool of more than $9M in Vercel and partner credits for hosting, compute, and model API usage. Confirm AI Gateway credit coverage and application dates with the program team.

## Plan for limits as you grow

Rate limits depend on your tier:

|               | Free tier                  | Paid tier                                              |
| ------------- | -------------------------- | ------------------------------------------------------ |
| Models        | Free-tier-eligible models  | All available models                                   |
| Rate limits   | Lower limit for each model | Free tier limits removed. Provider limits still apply. |
| Higher limits | Not available              | Available on request                                   |
| Credits       | Monthly included credit    | Purchased AI Gateway Credits                           |
| BYOK          | Not available              | Available                                              |

AI Gateway publishes no fixed numbers for [rate limits](https://vercel.com/docs/ai-gateway/rate-limits), because they can change. Rate-limited requests get a `429`, which can come from AI Gateway or from the upstream provider. The same request can succeed later without changes, so retry it and honor the `retry-after` header when it's present. For retryable failures before streaming begins, the AI SDK makes up to two retries by default.

Provider limits apply on both tiers, and BYOK requests run under your own provider account's limits. If a limit still constrains a paid-tier workload, [contact sales](https://vercel.com/contact/sales) to request a higher one. Mercor reports routing 18 million requests and 63 billion tokens through AI Gateway in its first 10 days without hitting rate limits.

These fixed limits also apply:

- Each request takes up to 10 tags and one `user`.
  
- Each provider takes up to 10 BYOK keys.
  
- Logs keep routing attempt details for 30 days.
  
- Upgrade to AI SDK 6 or later before AI Gateway stops accepting AI SDK 5 requests on January 8, 2027.
  

## Troubleshooting

| What you observe                                             | What to check                                                                                                                                           |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Local requests fail with an authentication error             | The development OIDC token is missing or has expired, which happens after 12 hours. Run `vercel env pull` again.                                        |
| A deployment returns `401` although OIDC is set up           | `AI_GATEWAY_API_KEY` is set and takes priority over OIDC, even when the key is invalid or revoked. Remove it or replace it.                             |
| `402` with a type other than `quota_for_entity_exceeded`     | The team has no positive credit balance. Add AI Gateway Credits. BYOK requests need a balance too.                                                      |
| `402` with `quota_for_entity_exceeded`                       | A team, project, API key, or member budget reached its limit. Wait for it to refresh, or raise it.                                                      |
| `403` that names a payment method or the free tier           | Free credits need a valid payment method on the team and cover a subset of models. Add a payment method, choose a free-tier model, or purchase credits. |
| `403` with a message that names team restrictions            | The model or provider allowlist blocks the request. Choose an allowed model, or ask a team owner to update the allowlist.                               |
| `429`                                                        | An AI Gateway or provider rate limit was exceeded. Retry after a short wait.                                                                            |
| The spend-report script fails on a Hobby team or a Pro trial | The reporting endpoint requires Pro or Enterprise; Pro trials cannot query it.                                                                          |

## Next steps

- Add tools, structured output, and durable steps to your routes with [AI Gateway and the AI SDK](https://vercel.com/kb/guide/ai-gateway-and-ai-sdk)
  
- Send routine requests to a lower-cost model with [cost-aware model routing](https://vercel.com/kb/guide/cost-aware-model-routing-with-ai-gateway)
  
- Write a data policy for each feature and [control provider data handling](https://vercel.com/kb/guide/control-ai-provider-data)
  
- Offer your customers a choice of models by [building a model router](https://vercel.com/kb/guide/how-to-build-your-own-ai-model-router)
  
- Run model-written code for your customers with [Vercel Sandbox](https://vercel.com/kb/guide/startups-on-vercel-sandbox)
  
- Check current token prices and add-on charges on the [AI Gateway pricing page](https://vercel.com/docs/ai-gateway/pricing)
  

## Frequently asked questions

### Is Vercel AI Gateway free to start with?

Yes. Every Vercel team has an AI Gateway free tier with a monthly included credit, which covers a subset of models at lower rate limits and requires a valid payment method on the team. On either tier, AI Gateway charges the provider's list price for tokens with no markup. Once a team purchases AI Gateway Credits, the monthly free credit stops.

### Do I have to deploy my app on Vercel to use AI Gateway?

No. An AI Gateway API key authenticates requests from any server, cloud, or CI environment, and a Vercel account is needed only to create the key and manage billing. Applications deployed on Vercel can authenticate with the project's OIDC token and skip the key.

### Can Vercel AI Gateway bill my customers for their AI usage?

AI Gateway records usage against the customer ID you send, and Custom Reporting groups spend by that ID. Its Stripe integration can emit token usage to an existing Billing Meters setup; creating the required dimensioned meter needs Stripe's private preview access. Your billing system creates invoices, and your application checks customer allowances before model calls. Sending a reporting ID does not create a customer budget.

### Does Vercel AI Gateway store my customers' prompts?

No. AI Gateway deletes prompt and response content when a request completes and keeps metadata such as the model, provider, token usage, and cost. Zero data retention routing restricts supported model requests to providers with a ZDR commitment. Provider-run tools and prompt caches have separate retention limits, and BYOK requests follow your own provider agreement.

## Related Resources

- [Build your startup's product on Vercel Sandbox](/kb/guide/startups-on-vercel-sandbox): Build code interpreters, app previews, and upload-processing features with Vercel Sandbox, including authentication, persistence, security, and cost controls.
- [Build AI agents with AI Gateway and AI SDK](/kb/guide/ai-gateway-and-ai-sdk): Build AI agents on Vercel with AI Gateway and AI SDK, then make them reliable, capable, and durable with Sandbox, Chat SDK, Vercel Connect, and Workflow.
- [Cost-aware model routing with Vercel AI Gateway](/kb/guide/cost-aware-model-routing-with-ai-gateway): Send easy requests to a lower-cost model and escalate only the complex ones to a frontier model through AI Gateway, with budgets and spend tracking.
- [How to control AI provider data handling with AI Gateway](/kb/guide/control-ai-provider-data): Prevent AI providers from training on your prompts, enforce zero data retention, and restrict providers and models with Vercel AI Gateway.

## More AI Gateway guides

- [Vercel AI Gateway vs Datadog AI Gateway](/kb/guide/vercel-ai-gateway-vs-datadog-ai-gateway): Compare Vercel AI Gateway and Datadog AI Gateway as LLM gateways, including providers, routing, access control, spend limits, guardrails, and observability.
- [Migrate from Neon AI Gateway to Vercel AI Gateway](/kb/guide/neon-aig-to-vercel-aig): Swap Neon's per-branch base URL and credential for Vercel's, map each short model ID to a creator/model slug, and replace the Gemini endpoint, rate limits, and daily spend cap.
- [Migrate from Netlify AI Gateway to Vercel AI Gateway](/kb/guide/netlify-aig-to-vercel-aig): Replace Netlify's injected provider keys and base URLs with a Vercel AI Gateway credential, map each model to a creator/model slug, and move Gemini SDK calls to a supported API.

## Reference Architecture

Choose a stack and work through the decisions behind it, with curated documentation, guides, templates, and courses to help you build.

- [Agent stack](/kb/architecture/agents): Build and operate agents with models, tools, and durable workflows.
- [Web applications](/kb/architecture/web): Choose rendering, data, authentication, and caching approaches.
- [Backends](/kb/architecture/backends): Choose a runtime, connect services, and run background work.

[Browse all stacks](/kb/architecture)

## Build with prompts

Build an app, extend an agent, or improve your project with ready-to-use prompts for your coding agent.

[Browse the prompt library](/kb/prompts) · [Read the Markdown index](/kb/prompts.md)

## Search guides from your terminal

Search the Knowledge Base and read guides as Markdown with the Vercel CLI. No login required.

```bash
# Find guides by keyword
npx vercel@latest kb search "rewrites and redirects"
npx vercel@latest kb search "AI SDK streaming"

# Show the latest guides
npx vercel@latest kb

# Print a guide as Markdown, by slug or URL
npx vercel@latest kb inspect <guide>
```
