Next.js 15 streaming chat route
Edge runtime API route that proxies a streaming chat completion through ScopeVeil.
import OpenAI from 'openai';
export const runtime = 'edge';
const ai = new OpenAI({
baseURL: 'https://gateway.scopeveil.com/v1',
apiKey: process.env.SCOPEVEIL_KEY!,
});
export async function POST(req: Request) {
const { prompt } = await req.json();
const upstream = await ai.chat.completions.create({
model: 'openai/gpt-4o-mini',
stream: true,
messages: [{ role: 'user', content: prompt }],
});
const encoder = new TextEncoder();
const body = new ReadableStream({
async start(controller) {
for await (const chunk of upstream) {
const token = chunk.choices[0]?.delta?.content ?? '';
if (token) controller.enqueue(encoder.encode(token));
}
controller.close();
},
});
return new Response(body, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});
}