DEV Community

Samuel Karani
Samuel Karani

Posted on

How to setup Vercel AI Function Streaming with CORS support

Vercel seems to have abandoned or deprioritized their serverless functions offering (outside Next.js) because I couldn’t find any official documentation for setting up function streaming with CORS enabled.

Eventually this ended up being quite a hassle to figure out, so I decided to make this snippet for anyone who needs it.

import { openai } from "@ai-sdk/openai"; import { streamText } from "ai"; export function OPTIONS() { return new Response("OK", { status: 200, headers: { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET,OPTIONS,PATCH,DELETE,POST,PUT", "Access-Control-Allow-Headers": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version", }, }); } export async function GET() { const response = streamText({ model: openai("gpt-4o-mini"), messages: [{ role: "user", content: "Write a short poem" }], }); return response.toTextStreamResponse({ headers: { "Content-Type": "text/event-stream", "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET,OPTIONS,PATCH,DELETE,POST,PUT", "Access-Control-Allow-Headers": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version", }, }); } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)