---
title: Migrate from Netlify AI Gateway to Vercel AI Gateway
description: 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.
keywords: ["Netlify","AI Gateway","AI SDK","Netlify Functions"]
url: "https://vercel.com/kb/guide/netlify-aig-to-vercel-aig"
published: 2026-11-25
last_updated: 2026-11-25
authors: Ben Sabic
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 netlify-aig-to-vercel-aig"
---

Move supported model calls from Netlify AI Gateway to [Vercel AI Gateway](https://vercel.com/docs/ai-gateway) by updating the endpoint, gateway credential, and model ID. You can keep a supported OpenAI or Anthropic client, but check the request options and response fields your application uses against the [API reference](https://vercel.com/docs/ai-gateway/sdks-and-apis).

Netlify injects provider credentials and base URLs at runtime, so configure migrated clients explicitly while other calls keep using Netlify. Google Gen AI calls need a different API format; check OpenRouter SDK compatibility before deciding whether to replace that client. Your application can stay on Netlify, but replace its credit-based gateway rate limit before moving affected traffic.

## Prerequisites

Before you begin, make sure you have:

- Access to a [Vercel account](https://vercel.com/signup) for API keys and billing. OIDC authentication also needs a Vercel project.
  
- 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).
  
- AI SDK 6 or 7 if your app uses the AI SDK, preferably version 7.
  
- Access to your Netlify team and project to review environment variables, AI features settings, and AI inference usage.
  

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

## Migrate with your agent

Use this prompt in your application's repository to migrate Netlify AI Gateway calls. It asks your agent to preserve existing behavior, identify missing replacements, and verify each change before cutover.

### Agent prompt

```txt
Migrate this repository from Netlify AI Gateway to Vercel AI Gateway. Read and follow the migration guide using the Vercel CLI: `npx vercel@latest kb inspect netlify-aig-to-vercel-aig`.

Inspect code and configuration first. Inventory zero-argument provider clients, REST calls built from injected base URLs, Google Gen AI and OpenRouter SDK calls, AI SDK providers, model IDs, and the provider and NETLIFY_AI_GATEWAY_* environment variables each call reads. Identify provider keys and base URLs set in Netlify, AI features settings, and rate limiting rules. Ask for missing settings and use credential placeholders.

Make scoped changes to supported calls. Resolve each model against the Vercel catalog and preserve prompts, tools, output handling, and fallback behavior. Keep unsupported calls on Netlify and explain what blocks them. Pass the Vercel credential and base URL to each migrated client explicitly. Don't add, remove, or overwrite provider environment variables used by unmigrated calls. Preserve existing values and let Netlify continue injecting credentials where it already does. For AI SDK calls, use explicit gateway() models during migration. Keep embedding-model changes separate from the gateway migration.

Account for rate limits, retention, logging, retries, and timeout behavior before a call moves. Adapt request bodies and conversation history where the APIs differ. Use the chosen API key or OIDC authentication path and identify environment or dashboard setup I must complete. Keep secrets out of code and output.

Run the available local checks and test the application's relevant request paths, including streaming, tool calls, fallbacks, and rejected requests. Ask before running billable model calls or changing production traffic. Preserve Netlify environment variables and AI features settings for rollback.

Report changed files, model and policy mappings, and check results. List unresolved differences and give a staged cutover plan that preserves rollback.
```

## How Netlify AI Gateway features map to Vercel AI Gateway

Before changing endpoints, record the gateway policies each call relies on. Use this table to identify settings you can map directly and features that need an [application replacement](#what-doesn%27t-map-from-netlify-ai-gateway). Complete those replacements before sending production traffic through the new path.

| Netlify AI Gateway                                                                       | Vercel AI Gateway                                                                                                                                                                                | What you change                                                                                             |
| ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- |
| Injected provider keys and base URLs                                                     | An AI Gateway API key or Vercel OIDC token                                                                                                                                                       | Create a credential and pass it to each client with the base URL                                            |
| Credit billing, at 180 credits per $1 of model usage                                     | AI Gateway Credits, with no markup on tokens                                                                                                                                                     | Purchase credits                                                                                            |
| Rate limit per team, in credits per minute                                               | No equivalent. Vercel sets [rate limits](https://vercel.com/docs/ai-gateway/rate-limits) per tier, and [budgets](https://vercel.com/docs/ai-gateway/observability-and-spend/budgets) limit spend | Limit request rate in your application                                                                      |
| Plan credit pool, shared with the rest of your Netlify usage                             | Budgets for a team, project, API key, or team member                                                                                                                                             | Set a budget for each credential or project                                                                 |
| Team-level AI inference usage chart                                                      | Overview charts and Logs, plus the [Custom Reporting API](https://vercel.com/docs/ai-gateway/observability-and-spend/custom-reporting) on Pro and Enterprise                                     | Review usage for each request, and add `user` and `tags` to group it                                        |
| Existing fallback logic and routing options                                              | [`models`](https://vercel.com/docs/ai-gateway/models-and-providers/model-fallbacks) in `providerOptions.gateway`, with `order`, `only`, and `sort` for providers                                 | Optional. Send one request with a fallback list                                                             |
| Prompt caching, with limits for each provider                                            | [Prompt caching](https://vercel.com/docs/ai-gateway/models-and-providers/automatic-caching) with `caching: 'auto'`                                                                               | Set `caching: 'auto'`, or keep your own cache markers                                                       |
| ZDR-only routing for models served through OpenRouter                                    | [Per-request ZDR](https://vercel.com/docs/ai-gateway/security-and-compliance/zdr#per-request-zero-data-retention)                                                                                | Preserve retention requirements and check provider eligibility                                              |
| No stored prompts or model outputs by default                                            | [Logs](https://vercel.com/docs/ai-gateway/observability-and-spend/logs) with request metadata only                                                                                               | Review any enhanced troubleshooting logging enabled with Netlify. Keep application prompt logging if needed |
| Your own provider keys in environment variables, which opt a provider out of the gateway | [BYOK](https://vercel.com/docs/ai-gateway/authentication-and-byok/byok), per team                                                                                                                | Add each key in the Vercel dashboard                                                                        |
| Google Gen AI SDK clients                                                                | AI SDK or OpenAI-compatible API                                                                                                                                                                  | Adapt request and response handling                                                                         |
| OpenRouter SDK chat calls                                                                | Chat Completions endpoint                                                                                                                                                                        | Check SDK compatibility or use the OpenAI SDK or AI SDK                                                     |

## Steps

### 1\. Find how your app calls Netlify AI Gateway

Netlify AI Gateway needs no key or URL in your code. When a Netlify Function or Edge Function starts, [Netlify sets a key and a base URL for each provider](https://docs.netlify.com/build/ai-gateway/overview/) as environment variables, and the providers' official client libraries read them. Your call sites may therefore contain no gateway reference at all. On Netlify, `new OpenAI()` with no arguments calls Netlify AI Gateway unless you've set those variables yourself. Server-side code in a framework such as Next.js or Astro gets the same variables, because Netlify packages it into functions during the build.

One codebase can reach Netlify AI Gateway through several of these integrations:

| Integration                | Recognize it by                                                                                   | Migration step                 |
| -------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------ |
| OpenAI SDK                 | `new OpenAI()` with no key or base URL, which reads `OPENAI_API_KEY` and `OPENAI_BASE_URL`        | 4                              |
| Anthropic SDK              | `new Anthropic()`, which reads `ANTHROPIC_API_KEY` and `ANTHROPIC_BASE_URL`                       | 4                              |
| Google Gen AI SDK          | `new GoogleGenAI({})`, which reads `GEMINI_API_KEY` and `GOOGLE_GEMINI_BASE_URL`                  | 4, in another API format       |
| OpenRouter SDK             | `new OpenRouter()`, which reads `OPENROUTER_API_KEY` and `OPENROUTER_BASE_URL`                    | 4, after a compatibility check |
| TypeSafe SDK               | `new TypeSafeClient()`, which reads `TYPESAFE_API_KEY` and `TYPESAFE_BASE_URL`                    | 4                              |
| REST call                  | `fetch` to a URL built from a base-URL variable, such as `${OPENAI_BASE_URL}/v1/chat/completions` | 4                              |
| Explicit gateway variables | `NETLIFY_AI_GATEWAY_KEY` and `NETLIFY_AI_GATEWAY_URL` passed to a client                          | 4 or 5                         |
| AI SDK provider            | An `@ai-sdk/` provider package that is given a Netlify key and base URL                           | 5                              |

Netlify configures `@openrouter/sdk` 1.2.43 and later automatically.

Netlify sets a provider's pair only when you haven't set either variable for the project or team. For Gemini, `GOOGLE_API_KEY` and `GOOGLE_VERTEX_BASE_URL` also prevent injection. Review these variables at both levels to identify calls using Netlify's credentials or your own. Netlify also injects `NETLIFY_AI_GATEWAY_KEY` and `NETLIFY_AI_GATEWAY_URL` for explicit gateway configuration.

From your repository root, find clients and environment-variable references:

```bash
git grep -n -F \
  -e 'new OpenAI(' \
  -e 'new Anthropic(' \
  -e 'new GoogleGenAI(' \
  -e 'new OpenRouter(' \
  -e 'new TypeSafeClient(' \
  -e '@typesafe-ai/sdk' \
  -e 'OPENAI_API_KEY' \
  -e 'OPENAI_BASE_URL' \
  -e 'ANTHROPIC_API_KEY' \
  -e 'ANTHROPIC_BASE_URL' \
  -e 'GEMINI_API_KEY' \
  -e 'GOOGLE_GEMINI_BASE_URL' \
  -e 'GOOGLE_API_KEY' \
  -e 'GOOGLE_VERTEX_BASE_URL' \
  -e 'OPENROUTER_API_KEY' \
  -e 'OPENROUTER_BASE_URL' \
  -e 'TYPESAFE_API_KEY' \
  -e 'TYPESAFE_BASE_URL' \
  -e 'META_API_KEY' \
  -e 'META_BASE_URL' \
  -e 'NETLIFY_AI_GATEWAY_' \
  -e '@ai-sdk/'
```

Use the search to inventory tracked files, then inspect each match. Results can include clients that already pass your own provider key and historical examples. Follow clients to their call sites, and include untracked source in your review.

The `NETLIFY_AI_GATEWAY_` pattern matches every variable with that prefix. Netlify's [providers endpoint](https://api.netlify.com/api/v1/ai-gateway/providers) lists `META_API_KEY` and `META_BASE_URL` for Meta models. If your code checks `process.env.OPENAI_BASE_URL` to detect the gateway, update that condition for migrated clients.

For each Netlify AI Gateway call site, record the model, the client and API format, and the variables it reads.

### 2\. Create a Vercel AI Gateway credential

Vercel AI Gateway requires an [AI Gateway API key](https://vercel.com/docs/ai-gateway/authentication-and-byok/api-keys) or Vercel OIDC token. Use an API key while your app stays on Netlify, or the project's OIDC token on Vercel. Provider keys alone cannot authenticate gateway requests.

#### Create an API key

API keys work from any environment. On the [AI Gateway API Keys page](https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai-gateway%2Fapi-keys&title=AI+Gateway+API+Keys), click **Create key**, name the key, and copy its value. You can't retrieve the value again. To create the key with the Vercel CLI instead, run:

```bash
vercel ai-gateway api-keys create --name my-api-key
```

Store the value as `AI_GATEWAY_API_KEY` in each environment that calls a model. On Netlify, add it to the project's or team's environment variables. For local development, add it to the `.env.local` env file:

```text
AI_GATEWAY_API_KEY=your_ai_gateway_api_key
```

Replace `your_ai_gateway_api_key` with the key's value, and keep the file out of version control. Framework dev commands such as `next dev` read variables from this file. Standalone Node.js and Python scripts don't load it, so export the variable in the shell that runs the script, or load the file in your code.

Netlify's AI Gateway credentials [exist only at runtime](https://www.netlify.com/knowledge-base/how-to-call-openai-claude-or-gemini-without-api-keys/), so build scripts, prerendering, and build plugins get none. An AI Gateway API key has no such restriction. If you moved model calls out of the build for that reason, a build step can call Vercel AI Gateway once `AI_GATEWAY_API_KEY` is set in the build environment.

#### Use OIDC on Vercel deployments

An application deployed on Vercel can authenticate with its project's [OIDC token](https://vercel.com/docs/ai-gateway/authentication-and-byok/oidc). This avoids depending on a team member's API key, which Vercel deactivates when its creator leaves the team. An application that stays on Netlify uses an API key.

The AI SDK first checks the `apiKey` passed to `createGateway()`, then `AI_GATEWAY_API_KEY`, then OIDC. Even an invalid, non-empty API key takes priority. Remove both explicit API-key settings from the migrated client to use OIDC.

For local development, link your directory to the Vercel project:

```bash
vercel link
```

Pull the development environment variables, including the local OIDC token:

```bash
vercel env pull
```

The local token is valid for 12 hours. Run `vercel env pull` again to refresh it.

#### Check the credential

Before changing application code, set `GATEWAY_TOKEN` to your AI Gateway API key or the current `VERCEL_OIDC_TOKEN` value from `.env.local`:

```bash
export GATEWAY_TOKEN="your_selected_credential"
```

Test the token with a request billed to your AI Gateway Credits:

```bash
curl --fail-with-body \
  https://ai-gateway.vercel.sh/v1/chat/completions \
  -H "Authorization: Bearer $GATEWAY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-5",
    "messages": [
      {"role": "user", "content": "Why is the sky blue?"}
    ]
  }'
```

Expect a JSON chat completion. For a `401`, `402`, or `403` response, see [troubleshooting](#troubleshooting). The `GATEWAY_TOKEN` variable is only for this test; application clients use the API key or OIDC setup above.

### 3\. Resolve each model ID against the catalog

Vercel AI Gateway uses `creator/model` slugs in every API format. Netlify uses provider-native names for directly served models and `creator/model` IDs for models served through OpenRouter. Check every ID against Vercel's catalog, even when it already has two parts. For example, `x-ai/grok-4.5` maps to `spacexai/grok-4.5`.

Fetch the catalog to match gateway slugs with provider-native model IDs:

```bash
curl -s https://ai-gateway.vercel.sh/v1/models/catalog
```

Read the catalog's `models` array. Each entry includes a `slug` and provider mappings with `provider` and `providerModelId` fields.

1. Keep an exact slug match after checking it identifies the intended model.
   
2. Otherwise, find all case-insensitive `providerModelId` matches.
   
3. If several slugs match, compare their type and version in the [model list](https://vercel.com/ai-gateway/models). Choose the standard slug when the only alternative is its `-fast` variant. [Fast mode](https://vercel.com/docs/ai-gateway/models-and-providers/fast-mode) uses a faster serving path at a higher per-token cost.
   

If you can't identify an equivalent model, keep the call on Netlify until you've tested a replacement. Don't substitute a similar name.

Keep the embedding model, dimensions, and input settings unchanged during migration. If the model is available through Vercel AI Gateway's [embeddings API](https://vercel.com/docs/ai-gateway/sdks-and-apis/openai-chat-completions/embeddings), test it against your existing index.

If you change embedding models, regenerate the stored embeddings before querying them with the new model. Different models can produce incompatible vectors even when their dimensions match; a dimension mismatch can cause the index to reject the query.

Record each call's resolved slug or why it must remain on Netlify.

### 4\. Set the base URL and credential in each client

Keep the API format your code already uses. Vercel AI Gateway has one base URL for each client family:

| Client                                                                          | Base URL                                |
| ------------------------------------------------------------------------------- | --------------------------------------- |
| OpenAI SDK, or an HTTP client that sends Chat Completions or Responses requests | `https://ai-gateway.vercel.sh/v1`       |
| Anthropic SDK, or an HTTP client that sends Messages requests                   | `https://ai-gateway.vercel.sh`          |
| TypeSafe SDK                                                                    | `https://ai-gateway.vercel.sh/typesafe` |

Pass the Vercel credential and base URL directly to each migrated client. Leave Netlify's provider environment variables in place for clients that haven't moved.

Setting `OPENAI_API_KEY` or `OPENAI_BASE_URL` disables Netlify's injection for that provider. Zero-argument clients then read your replacement values. Explicit arguments keep both gateway paths separate.

For OpenAI Responses over HTTP, send previous turns in `input`. AI Gateway's `gen_` IDs identify requests for observability and cannot substitute for provider response IDs. Use `previous_response_id` to continue turns on the same WebSocket connection. Check [Responses parameters](https://vercel.com/docs/ai-gateway/sdks-and-apis/responses#parameters) before moving a conversation that relies on stored response history.

The credential goes in `Authorization: Bearer`. Netlify meters and rate-limits AI Gateway usage for the whole team. To track applications or environments separately on Vercel, give each one an API key with its own budget.

Project budgets count requests authenticated with that project's OIDC token or an [API key scoped to the project](https://vercel.com/docs/ai-gateway/authentication-and-byok/api-keys#create-a-key). An unscoped key doesn't count toward the project budget, even when a deployment in that project uses it.

#### OpenAI SDK in TypeScript

These clients use the `openai` package. If your app doesn't have it yet, install it:

**pnpm**

```bash
pnpm add openai
```

**yarn**

```bash
yarn add openai
```

**npm**

```bash
npm install openai
```

**bun**

```bash
bun add openai
```

On Netlify, the client takes no arguments. This excerpt from Netlify's example shows the constructor and the variables the SDK reads:

```typescript
import OpenAI from 'openai';

const openai = new OpenAI();
// No API key or base URL configuration needed - automatically uses:
// process.env.OPENAI_API_KEY and process.env.OPENAI_BASE_URL
```

For Vercel AI Gateway, check that the key is set before constructing the client. An undefined key lets the SDK fall back to Netlify's injected provider key:

```typescript
import OpenAI from 'openai';

const apiKey = process.env.AI_GATEWAY_API_KEY;
if (!apiKey) {
  throw new Error('Set AI_GATEWAY_API_KEY before creating this client.');
}

const client = new OpenAI({
  apiKey,
  baseURL: 'https://ai-gateway.vercel.sh/v1',
});

const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-5",
  messages: [{ "role": "user", "content": "Why is the sky blue?" }],
});

console.log(response.choices[0]?.message.content);
```

The client now uses these two arguments in place of `OPENAI_API_KEY` and `OPENAI_BASE_URL`, and Vercel's provider keys or your own keys from step 8 authenticate to the provider. Replace the example slug with the one you resolved in step 3. The API format doesn't decide which provider serves a request, so an OpenAI SDK client can also call models from other creators. The same client configuration serves `client.responses.create()`, which Netlify's quickstart uses.

On a Vercel deployment, the OpenAI and Anthropic SDKs don't find the OIDC token themselves. To pass it to them, install `@vercel/oidc`:

**pnpm**

```bash
pnpm add @vercel/oidc
```

**yarn**

```bash
yarn add @vercel/oidc
```

**npm**

```bash
npm install @vercel/oidc
```

**bun**

```bash
bun add @vercel/oidc
```

Await `getVercelOidcToken()` in each request handler and pass the token as `apiKey`. Vercel rotates function tokens within an hour.

#### Anthropic SDK

On Netlify, `new Anthropic()` reads `ANTHROPIC_API_KEY` and `ANTHROPIC_BASE_URL`. If your app doesn't have the `@anthropic-ai/sdk` package yet, install it:

**pnpm**

```bash
pnpm add @anthropic-ai/sdk
```

**yarn**

```bash
yarn add @anthropic-ai/sdk
```

**npm**

```bash
npm install @anthropic-ai/sdk
```

**bun**

```bash
bun add @anthropic-ai/sdk
```

On Vercel AI Gateway, the Anthropic base URL has no `/v1` suffix:

```typescript
import Anthropic from '@anthropic-ai/sdk';

const apiKey = process.env.AI_GATEWAY_API_KEY;
if (!apiKey) {
  throw new Error('Set AI_GATEWAY_API_KEY before creating this client.');
}

const client = new Anthropic({
  apiKey,
  baseURL: 'https://ai-gateway.vercel.sh',
});

const response = await client.messages.create({
  model: "anthropic/claude-sonnet-5",
  messages: [{ "role": "user", "content": "Why is the sky blue?" }],
  max_tokens: 1024,
});

for (const block of response.content) {
  if (block.type === 'text') console.log(block.text);
}
```

Messages accepts the gateway credential in `x-api-key` or `Authorization: Bearer`, so the Anthropic SDK can keep its usual header.

#### `fetch` and other HTTP clients

Netlify's REST examples build each URL from an injected base-URL variable and send the injected key in the provider's own header. An OpenAI request goes to `${OPENAI_BASE_URL}/v1/chat/completions` with `Authorization: Bearer`, and an Anthropic request goes to `${ANTHROPIC_BASE_URL}/v1/messages` with `x-api-key`.

Send Chat Completions to `https://ai-gateway.vercel.sh/v1/chat/completions` with the gateway credential in `Authorization: Bearer` and the resolved model slug. Use `/v1/responses` for Responses and `/v1/messages` for Messages.

Point OpenRouter REST calls from `${OPENROUTER_BASE_URL}/chat/completions` to the same Chat Completions URL. Check the [supported parameters](https://vercel.com/docs/ai-gateway/sdks-and-apis/openai-chat-completions) against your request fields before migrating.

#### Google Gen AI, OpenRouter, and TypeSafe SDKs

Migrate Google Gen AI's `generateContent` calls and Gemini-format REST requests to the AI SDK in step 5 or the OpenAI SDK client above. Adapt both the request body and response handling, then test each call with the model slug from step 3.

OpenRouter SDK chat calls use Chat Completions and accept a custom `serverURL`. Vercel's documented client paths are the OpenAI SDK and AI SDK. If you retain `@openrouter/sdk`, check its request options and response validation against the calls your application uses. Endpoint compatibility alone doesn't establish support for every SDK method.

TypeSafe SDK clients keep their SDK. Vercel AI Gateway serves a [TypeSafe-compatible API](https://vercel.com/docs/ai-gateway/sdks-and-apis/typesafe), so pass `AI_GATEWAY_API_KEY` as the client's `apiKey` and `https://ai-gateway.vercel.sh/typesafe` as its `baseURL`.

After you change a client, run one of its calls. One completed response confirms the base URL, the credential, and the slug together.

### 5\. Move AI SDK calls to Vercel AI Gateway

Move calls individually with an explicit `gateway()` model. Each call you change selects Vercel AI Gateway by name, and calls that still use another provider keep their current path. Google Gen AI SDK and OpenRouter SDK calls that you rewrite with the AI SDK use the same pattern.

The examples use AI SDK 7. Check the installed AI SDK version first:

```bash
pnpm list ai
```

Vercel AI Gateway supports AI SDK 6 and 7, with some [differences in option names](https://vercel.com/docs/ai-gateway/sdks-and-apis/ai-sdk#version-compatibility). AI SDK 7 requires Node.js 22 or later and ESM.

AI SDK 5 is deprecated, and teams new to Vercel AI Gateway can't use it. Support ends for existing teams on January 8, 2027. If your app uses version 5, follow the [AI SDK migration guides](https://ai-sdk.dev/docs/migration-guides) before changing these calls.

For the AI SDK 7 examples, install the AI SDK and Gateway provider:

**pnpm**

```bash
pnpm add ai@7 @ai-sdk/gateway
```

**yarn**

```bash
yarn add ai@7 @ai-sdk/gateway
```

**npm**

```bash
npm install ai@7 @ai-sdk/gateway
```

**bun**

```bash
bun add ai@7 @ai-sdk/gateway
```

In AI SDK code that runs on Netlify, look for provider packages such as `@ai-sdk/openai` and check how each provider instance gets its key and base URL. For a library that doesn't read the injected variables, Netlify's guidance is to pass the key and base URL as arguments, so you may find `NETLIFY_AI_GATEWAY_KEY` or a provider variable in the provider's settings.

Keep the prompt, and select the model through `gateway()` with the slug you resolved in step 3:

```typescript
import { gateway } from '@ai-sdk/gateway';
import { generateText } from 'ai';

const { text } = await generateText({
  model: gateway('openai/gpt-6-luna'),
  prompt: 'Why is the sky blue?',
});

console.log(text);
```

This call uses Vercel AI Gateway while unmigrated calls keep their Netlify provider. Keep `gateway()` explicit throughout the migration, including calls configured through middleware or provider registries.

The AI SDK reads `AI_GATEWAY_API_KEY` from the environment. On a Vercel deployment, it uses the OIDC token when no API key is set. Without an API key or OIDC token, requests fail with `GatewayAuthenticationError`.

Keep provider imports until no remaining call uses them. Preserve provider-specific options and put gateway settings under `providerOptions.gateway`. Check each result metadata field and test provider-error handling before moving the next call.

### 6\. Set retention, usage tracking, and caching

Set `providerOptions.gateway` on each AI SDK call. With Chat Completions, Messages, and Responses, include the same options in the JSON request body.

#### Preserve zero data retention

Netlify routes models served through OpenRouter only to providers with a zero data retention (ZDR) policy. By default, Vercel AI Gateway doesn't route on a provider's retention policy, so set the requirement on each call that relied on it.

If a request requires provider zero data retention, set `zeroDataRetention: true`. Vercel AI Gateway restricts the request and its fallbacks to eligible providers and fails if none can serve the model. This requirement is separate from the gateway's own payload logging policy.

Per-request ZDR requires a Pro or Enterprise plan, purchased AI Gateway Credits, or an active Token Pass. BYOK keys must be marked ZDR-compliant under your provider agreement. Check the [requirements and exclusions](https://vercel.com/docs/ai-gateway/security-and-compliance/zdr#per-request-zero-data-retention) before migration.

In the AI SDK, set the option on the call:

```typescript
import { gateway } from '@ai-sdk/gateway';
import { generateText } from 'ai';

const { text } = await generateText({
  model: gateway('anthropic/claude-sonnet-5'),
  prompt: 'Analyze this example business data: revenue grew by 5%.',
  providerOptions: {
    gateway: {
      zeroDataRetention: true,
    },
  },
});

console.log(text);
```

#### Track usage by user and tag

The OpenAI SDK's TypeScript types don't declare gateway options, so spread them into the request. This call attributes usage to a user and two tags:

```typescript
import OpenAI from 'openai';

const apiKey = process.env.AI_GATEWAY_API_KEY;
if (!apiKey) {
  throw new Error('Set AI_GATEWAY_API_KEY before creating this client.');
}

const client = new OpenAI({
  apiKey,
  baseURL: 'https://ai-gateway.vercel.sh/v1',
});

const response = await client.chat.completions.create({
  model: 'anthropic/claude-sonnet-5',
  messages: [
    {
      role: 'user',
      content: 'Tell me about San Francisco.',
    },
  ],
  // AI Gateway extension fields are not included in the upstream SDK types.
  ...{
    providerOptions: {
      gateway: {
        user: 'user-123',
        tags: ['feature:chat', 'env:development'],
      },
    },
  },
});

console.log(response.choices[0]?.message.content);
```

If ZDR is required, add `zeroDataRetention: true` to the same `gateway` object. Check for `enabledZeroDataRetention: true` in successful responses' gateway metadata to confirm ZDR was used.

Netlify reports AI Gateway usage at team level. Vercel accepts one `user` string up to 256 characters and up to 10 tags of 1–64 characters each for customer or feature reporting. [Custom Reporting](https://vercel.com/docs/ai-gateway/observability-and-spend/custom-reporting) charges $0.075 per 1,000 writes, counting each unique tag or user ID in a request as one write.

#### Preserve prompt caching

Netlify supports prompt caching within limits: only the default five-minute cache duration for Claude, and no explicit context caching for Gemini. With `caching: 'auto'`, Vercel AI Gateway adds cache markers for providers that need them, and the provider can reuse a cached prompt prefix at its reduced input-token rate. The model still generates a response for every request. When `caching` isn't set, Vercel AI Gateway passes the request through unchanged, so cache markers your code already adds reach the provider.

### 7\. Add model fallbacks and provider routing

Check the fallback logic and routing options each call currently uses before migrating it. Model fallbacks and provider routing are optional additions to the migration. Fallback attempts that share a request body can use a `models` array in `providerOptions.gateway`, alongside the primary model.

Vercel AI Gateway receives the fallback list with the request:

```typescript
import { gateway } from '@ai-sdk/gateway';
import { generateText } from 'ai';

const result = await generateText({
  model: gateway('anthropic/claude-opus-5.5'),
  prompt: 'Write a haiku about TypeScript.',
  providerOptions: {
    gateway: {
      models: ['openai/gpt-5.5'],
    },
  },
});

console.log(result.text);
console.log(result.providerMetadata?.gateway);
```

Vercel AI Gateway tries the primary model first. If its eligible providers fail, it tries the next model in `models` until one succeeds. Check every fallback slug against the catalog. Fallbacks work across supported text-generation APIs.

To see which model answered, read `result.providerMetadata?.gateway` in the AI SDK. Its `routing.finalProvider` field names the provider that served the request, and `routing.modelAttempts` lists each model and provider that Vercel AI Gateway tried. For every client, the request's details in Logs show the same routing attempts.

If fallbacks need different prompts, tools, credentials, retries, or timeouts, preserve those differences in an application fallback loop.

Vercel AI Gateway also tries other providers for the same model. It uses recent uptime and latency to choose a provider unless you set [routing options](https://vercel.com/docs/ai-gateway/models-and-providers/provider-filtering-and-ordering):

- `order` lists provider slugs in the order to try them. It sets a preference, so other providers can still serve the request.
  
- `only` restricts routing to the providers you list. If those providers are down, rate limited, or out of capacity, the request fails.
  
- `sort` ranks providers by cost, time to first token, or tokens per second. Use `'cost'`, `'ttft'`, or `'tps'` respectively.
  

When a request sets both `only` and `order`, `only` defines the allowed set and `order` sets the priority within it.

### 8\. Set up provider keys and billing

Netlify AI Gateway calls providers on your behalf and bills your plan's credits. Setting your own provider key opts that provider out of its gateway. Vercel AI Gateway supports both managed provider keys and BYOK, with a gateway credential required for either path.

| On Netlify                                       | On Vercel AI Gateway                            | Setup                                                                                                                                                                                                                   |
| ------------------------------------------------ | ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Netlify credits                                  | AI Gateway Credits, with Vercel's provider keys | Purchase credits                                                                                                                                                                                                        |
| Your own provider key                            | Team BYOK                                       | On the [Bring Your Own Key (BYOK) page](https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai-gateway%2Fbyok&title=AI+Gateway+BYOK), find the provider, click **Add Key**, enter the credentials, and click **Test API Key** |
| Your own provider key that only one project uses | Request-scoped BYOK                             | Send the key in `providerOptions.gateway.byok`                                                                                                                                                                          |

Request-scoped BYOK puts the provider key in the request's options. On Netlify, `ANTHROPIC_API_KEY` holds a Netlify-issued key unless you set it yourself, and setting it stops Netlify from injecting the Anthropic pair for calls that haven't moved. Store your provider key under a separate name that Netlify doesn't inject, such as `ANTHROPIC_BYOK_API_KEY`, before running this example:

```typescript
import { gateway } from '@ai-sdk/gateway';
import { generateText } from 'ai';

const providerKey = process.env.ANTHROPIC_BYOK_API_KEY;
if (!providerKey) {
  throw new Error('Set ANTHROPIC_BYOK_API_KEY before making requests.');
}

const { text } = await generateText({
  model: gateway('anthropic/claude-sonnet-5'),
  prompt: 'Explain quantum computing in two sentences.',
  providerOptions: {
    gateway: {
      byok: {
        anthropic: [
          {
            apiKey: providerKey,
          },
        ],
      },
    },
  },
});

console.log(text);
```

When a request carries its own credentials, Vercel AI Gateway doesn't consider the keys stored in the dashboard for that request. In both cases, the request's details in Logs show whether your key or Vercel's provider keys served it.

Vercel stores dashboard provider keys for the team, so they can serve every project. Netlify lets you set a provider key for one project or the team. Both stored and request-scoped BYOK require purchased AI Gateway Credits and a positive balance; otherwise the gateway returns `402`.

When a request fails on your key, Vercel AI Gateway retries it on Vercel's provider keys by default and bills that usage to your credits. To keep requests on your own keys, as they are on Netlify once you set a provider key, open the AI Gateway **Settings** tab and turn off **Fallback to Vercel Keys**. The setting applies to the whole team, and while it's off, Vercel AI Gateway charges $0.20 per 1,000 BYOK requests.

Vercel AI Gateway stores up to 10 keys per provider and uses the oldest enabled key by default. ZDR requests can use another enabled key marked ZDR-compliant.

Netlify [converts model usage to credits](https://docs.netlify.com/manage/accounts-and-billing/billing/billing-for-credit-based-plans/pricing-for-ai-features/) at 180 credits per $1 and draws them from the same pool as the rest of your plan. Vercel AI Gateway has no markup or platform fee on tokens. Calls using Vercel's provider keys draw from [AI Gateway Credits](https://vercel.com/docs/ai-gateway/pricing); BYOK token charges are paid to your provider. The per-request BYOK fee described above is separate.

Purchased AI Gateway Credits expire after one year, and payment processing fees may apply. The free tier includes a monthly credit for a subset of models. Buying credits moves the team to the paid tier and ends its monthly free credit.

### 9\. Cut over and verify

Move one call site at a time, keeping unverified paths on Netlify.

1. Check the call's request limits, retention requirements, and routing.
   
2. Deploy to preview or staging with the intended API key or OIDC credential.
   
3. Test streaming, tool calls, structured output, fallbacks, and rejections.
   
4. Review the repository search results for references still used by migrated paths. Keep references needed by calls that remain on Netlify.
   
5. Confirm the model, provider, credential source, and routing attempts in Vercel AI Gateway Logs. Set a budget for that credential or project.
   
6. Shift production traffic gradually and compare application errors and model output. Preserve Netlify's variables and AI features settings for rollback.
   

In the Vercel dashboard, open AI Gateway, then [**Logs**](https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai-gateway%2Flogs&title=AI+Gateway+Logs). Each row records the request's time, status, model, provider, usage, cost, duration, and authentication. New rows can take about 90 seconds to appear.

Open a row to inspect its routing attempts and credential source. Confirm that the request used the intended model, provider, and key; a successful response alone doesn't establish that the migration preserved those choices.

To list the same requests from your terminal, run:

```bash
vercel ai-gateway requests list --since 24h
```

Vercel AI Gateway checks budgets before each request and returns `402` once a limit is exceeded, including for BYOK requests covered by that budget. BYOK token charges paid to the provider don't count toward the budget, but the fee charged when **Fallback to Vercel Keys** is off does.

> **Warning:**
>
> Disabling AI features for your Netlify team, or setting your own value for a provider's key or base URL variable, stops Netlify from injecting the credentials that unmigrated calls depend on. Before changing either, confirm that no active workload needs them and the rollback period is over.

After the final call site has moved, watch the AI inference chart in Netlify's [account usage insights](https://docs.netlify.com/manage/accounts-and-billing/billing/billing-for-credit-based-plans/monitor-usage-for-credit-based-plans/) over a period that includes scheduled and infrequent jobs. Once the migration is stable and you no longer need the rollback path, remove unused packages and the code that reads Netlify's variables. Leave Netlify's AI features on if other workloads still use them.

## What doesn't map from Netlify AI Gateway

### Rate limiting

Netlify limits AI Gateway usage for the whole team, per minute, in credits: 90 on Free, 450 on Personal, 1,800 on Pro, and 9,000 on Enterprise. Vercel AI Gateway applies per-model rate limits on the free tier. The paid tier removes those gateway limits, but upstream provider limits still apply.

For a custom limit on Vercel, protect your model endpoint with [WAF rate limiting](https://vercel.com/docs/vercel-firewall/vercel-waf/rate-limiting). To allow 100 requests per minute:

1. Select your project in the Vercel dashboard, open **Firewall**, then select **Configure** and **\+ New Rule**.
   
2. Name the rule and match **Request Path** with **Equals**. Enter `/api/chat`, or the path of your model endpoint.
   
3. Set the action to **Rate Limit** with **Fixed Window**. If this is your first rate limit rule, review the **Rate Limiting Pricing** dialog and select **Continue**. Use a **Time Window** of 60 seconds and a **Request Limit** of 100, grouped by source IP.
   
4. Choose **Log** to monitor the rule first. Save it, select **Review Changes**, and inspect the change before choosing **Publish**, which applies it to production. Log mode doesn't block requests.
   
5. Check the rule's traffic in **Firewall**. Once the matches are correct, change the action to **Too Many Requests (429)** and publish the change to enforce the limit.
   

Each source has a separate counter in each region, so this doesn't enforce a gateway-wide limit of 100 requests. It covers traffic through the protected Vercel route. If your endpoint stays on Netlify, enforce its limit there, for example with the rate limiting rules Netlify recommends for functions that call the gateway, or in application code. Use a budget to cap spending separately.

### Input size and function time limits

Netlify AI Gateway limits input prompts to 200k tokens. Check your destination model's context window in the [model catalog](https://vercel.com/docs/ai-gateway/models-and-providers) before changing input truncation.

Netlify's runtime limits still apply after changing gateways. Its [Functions API](https://docs.netlify.com/build/functions/api/#streaming-responses) allows synchronous and streaming functions to run for up to 60 seconds. Streaming delivers incremental output but doesn't extend that limit.

For longer work, [background functions](https://docs.netlify.com/build/functions/api/#background-mode) can run for up to 15 minutes and return an immediate `202` response. Keep your existing result-delivery path for those jobs, and check the separate limits if you use Netlify's Lambda-compatible API.

## Troubleshooting

| What you observe                                         | What to check                                                                                                                                                                                       |
| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `401`                                                    | The credential is missing, invalid, or revoked. Check that `AI_GATEWAY_API_KEY` is set in the runtime that makes the call, and that `apiKey` doesn't hold a Netlify-injected key or a provider key. |
| `401` in local development after earlier requests worked | The local OIDC token has expired. Run `vercel env pull` again.                                                                                                                                      |
| `402`                                                    | The team has no positive credit balance, which every request needs, including BYOK requests. When the error's `type` is `quota_for_entity_exceeded`, a budget has reached its limit.                |
| `403` with a message that names the free tier            | The model isn't in the free-tier subset. Choose a free-tier model or purchase credits.                                                                                                              |
| `429`                                                    | An AI Gateway or upstream provider rate limit was exceeded. Retry after a short wait.                                                                                                               |
| OIDC isn't used on a Vercel deployment                   | For the AI SDK, remove both the explicit `createGateway()` API key and `AI_GATEWAY_API_KEY`. OpenAI and Anthropic clients need the current OIDC token passed explicitly, as described in step 4.    |
| Requests don't appear in Vercel AI Gateway Logs          | Allow about 90 seconds, then check the team, project scope, time range, and filters. Confirm the client uses the Vercel base URL and a populated gateway credential.                                |
| Calls that haven't moved stop using Netlify AI Gateway   | Someone set a provider key or base URL variable in Netlify, so Netlify no longer injects that provider's pair. Remove the variable, or migrate those calls.                                         |
| BYOK requests show Vercel's provider keys in Logs        | Open the row and inspect the routing attempts and credential source. Check whether your key failed, was excluded by ZDR, or was replaced by request-scoped BYOK credentials.                        |

## Next steps

- [Set spend limits for a team, project, API key, or team member](https://vercel.com/docs/ai-gateway/observability-and-spend/budgets)
  
- [Add prompt caching and an application response cache](https://vercel.com/docs/ai-gateway/models-and-providers/automatic-caching)
  
- [Group usage by user or tag with the Custom Reporting API](https://vercel.com/docs/ai-gateway/observability-and-spend/custom-reporting)
  
- Follow the [Netlify migration steps](https://vercel.com/kb/guide/migrate-to-vercel-from-netlify) to move the rest of your application.
  

## Frequently asked questions

### Can I use Vercel AI Gateway from a Netlify Function?

Yes. Vercel AI Gateway is a hosted API, and an AI Gateway API key authenticates requests from any server or cloud. Your function needs a Vercel account for the key and for billing, and no Vercel project or deployment.

### Does Vercel AI Gateway inject environment variables on Netlify?

No. Set `AI_GATEWAY_API_KEY` in the Netlify runtime environment, then pass the key and Vercel base URL to the client. On Vercel deployments, the AI SDK uses the project's OIDC token if no API key is set.

### Can I use the Google Gen AI SDK with Vercel AI Gateway?

Use the AI SDK or an OpenAI-compatible client for supported Gemini models through Vercel AI Gateway. Replace `generateContent` with the chosen API format and model's `google/` slug, then test request options and response handling.

### Can I keep using my own provider keys with Vercel AI Gateway?

Yes, with BYOK. Add each provider key for your team in the dashboard, or send a key with a single request in `providerOptions.gateway.byok`. BYOK needs purchased AI Gateway Credits, and requests fall back to Vercel's provider keys by default when your key fails.

### How is Vercel AI Gateway billed compared with Netlify AI Gateway?

Netlify turns each request's token cost into Netlify credits, 180 for every $1 of model usage, and takes them from your plan's credit pool. Vercel AI Gateway deducts the provider's list price from AI Gateway Credits bought in advance, with no markup or platform fee on tokens. Payment processing fees can apply, and purchased credits expire one year after purchase.

## More AI Gateway guides

- [Migrate from Cloudflare AI Gateway to Vercel AI Gateway](/kb/guide/cloudflare-aig-to-vercel-aig): Swap Cloudflare's base URL and cf-aig-\* headers for Vercel's, map each model to a creator/model slug, and move caching, rate limits, and guardrails into your app.
- [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.
- [Durable agent approval workflows on Vercel](/kb/guide/agent-approval-workflow-stack-guide): How enterprise architects choose a stack and decide where to run durable, human-in-the-loop agent approval workflows on Vercel.

## 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>
```
