Deploying an AI SDK Agent to Vercel Edge Functions
Streaming chat feels fast when the function starts near the user and begins flushing tokens immediately.
Search across all documentation pages
Streaming chat feels fast when the function starts near the user and begins flushing tokens immediately.
This page deploys a Next.js App Router AI SDK agent route on Vercel's Edge runtime with duration, env, and compatibility checks that keep streams healthy in production.
Mark the chat route with export const runtime = 'edge', stream with streamText + UI message response helpers, set maxDuration within platform limits, keep dependencies edge-safe, and verify secrets via Vercel env vars. Prefer Node runtime when the agent needs heavy native modules or long multi-tool work.
fs, optional native addons).export const runtime = 'edge' (and region config if you pin locales).export const maxDuration = ... appropriate to plan and workload.AI_GATEWAY_API_KEY, OPENAI_API_KEY, etc.).stopWhen) so tools cannot run until platform kill.vercel / git integration; smoke-test streaming from multiple regions.nodejs runtime if edge bundles fail or libraries require Node.app/api/chat/route.ts:
import {
convertToModelMessages,
isStepCount,
streamText,
tool,
type UIMessage,
} from "ai";
import { z } from "zod";
export const runtime = "edge";
export const maxDuration = 30;
export async function POST(req: Request) {
const { messages }: { messages: UIMessage[] } = await req.json();
const result = streamText({
model: "openai/gpt-4o-mini", // gateway string or edge-safe provider - verify at build
messages: await convertToModelMessages(messages),
instructions: "Be concise. Prefer tools only when needed.",
stopWhen: isStepCount(5),
tools: {
timeNow: tool({
description: "Return the current server time ISO string",
inputSchema: z.object({}),
execute: async () => ({ now: new Date().toISOString() }),
}),
},
});
return result.toUIMessageStreamResponse();
}Client stays standard useChat + DefaultChatTransport({ api: '/api/chat' }).
vercel.json is optional; runtime export on the route is enough for many apps.
Env in Vercel dashboard (Production + Preview):
AI_GATEWAY_API_KEY=...
# TOOL_APPROVAL_SECRET=... # if you sign approvalsDeploy:
pnpm i
pnpm build
vercel --prodEdge runtimes (V8 isolates) optimize cold start and geographic placement.
For chat, time-to-first-token often matters more than raw multi-second tool throughput.
Streaming remains supported: start sending the response promptly, then continue streaming within platform caps (edge streaming commonly up to ~300s class limits; confirm current Vercel docs).
Edge functions should begin the response within about 25 seconds to keep streaming beyond that window.
Design implications:
| Concern | Edge | Node (nodejs runtime) |
|---|---|---|
| Cold start / TTFB | Often better | Heavier |
| Library support | Web-standard only | Full Node ecosystem |
| Max duration | Platform edge limits | Often higher configurable caps on Pro+ |
| Native modules | Usually no | Yes |
| Long agent graphs | Risky | Safer |
| Simple streamText chat | Excellent | Fine |
If @something imports Node crypto legacy APIs or PDF native bindings, use Node.
AI SDK Core streaming itself is edge-friendly when providers use fetch.
Pinning functions near your DB can beat "closest to user" if every tool call cross-ocean hops.
For pure LLM proxy chat with external model APIs, multi-region edge is often ideal.
For tools hitting a single regional Postgres, consider Node in that region or edge with a nearby data plane.
Log:
Wire OpenTelemetry or Vercel log drains; avoid logging full prompts if policy forbids it.
/api/chat.maxDuration and tool steps.Each PR preview needs env vars copied or shared.
Point useChat at same-origin /api/chat so previews do not call production APIs accidentally.
| Approach | Pros | Cons |
|---|---|---|
| Vercel Edge route | Low latency streaming | API surface limits |
| Vercel Node route | Full compatibility | Heavier isolates |
| Separate Node agent service | Scale agent independently | More ops, CORS/proxy |
| Serverless other clouds | Flexibility | You rebuild streaming glue |
| Long-running worker + poll | Hard jobs | Worse chat UX |
No. The SDK runs on Node and other runtimes. Edge is an optimization choice.
Prefer AI SDK providers that use fetch. Some official SDKs need Node. Verify your provider package.
Start with 30s for simple chat; raise for multi-step tools within your plan's maximum. Measure p95.
export const runtime = 'nodejs' (or omit where Node is default for your Next version - verify).
Yes if you return the UI message stream correctly; tool parts flow like on Node.
Vercel continues to evolve function execution (including Fluid compute). Treat runtime choice as "edge vs node" and re-read current Vercel limits at deploy time.
Not as the AI SDK TypeScript edge route. Host Python (Pydantic AI / LangGraph) on a Python-friendly service and proxy streams from Next.
next dev does not perfect production edge. Use vercel dev or deploy previews for integration tests.
Check model provider regional latency, cold starts, and whether tools call a far database.
Auth middleware often is edge; keep it thin. Do not run the full agent in middleware.
Stack versions: Pins from the category manifest (verify at build): OpenRouter (~315+ models, July 2026 pricing/fees); LangGraph 1.0+; CrewAI 1.14+; Microsoft Agent Framework 1.0; Vercel AI SDK 6; Pydantic AI (latest); LlamaIndex (latest); OpenAI Agents SDK (latest + MCP); MCP (Linux Foundation governance); A2A (HTTP+SSE+JSON-RPC 2.0); Solana
@solana/web3.js+@solana/spl-token.
Reviewed by Chris St. John·Last updated Jul 16, 2026