Next.js AI Streaming Route Handler
Stream OpenAI responses from a Next.js App Router route handler using the Vercel AI SDK.
// app/api/chat/route.ts
import { openai } from "@ai-sdk/openai";
import { streamText } from "ai";
export const runtime = "edge";
export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: openai("gpt-4o"),
system: "You are a helpful coding assistant.",
messages,
});
return result.toDataStreamResponse();
}Sponsored
Deploy AI apps instantly with Vercel
Use Cases
- AI chatbot backend
- streaming API endpoint
- LLM integration
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
OpenAI Chat Completion with Streaming
Stream GPT responses token-by-token using the OpenAI SDK with async iteration.
DALLΒ·E 3 Image Generation
Generate images from a text prompt using the OpenAI DALLΒ·E 3 API and return a URL.
Content Moderation with OpenAI
Check user input for harmful content using the OpenAI Moderation API before processing.
Generate Text Embeddings with OpenAI
Create vector embeddings for semantic search and similarity matching using text-embedding-3-small.