Next.js and Vercel AI SDK
Protect Next.js /api/chat route handlers and Vercel AI SDK streamText and generateText endpoints before token streaming starts.
Securing Next.js app/api/chat/route.ts
When using the Vercel AI SDK (streamText or generateText), place the Gated check at the top of your POST handler before starting the model stream.
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";
export async function POST(req: Request) {
const { messages, userId } = await req.json();
const latestInput = String(messages.at(-1)?.content || "");
// 1. Pre-screen with Gated (<1ms edge check)
try {
const gateRes = await fetch("https://getgated.ai/v1/check", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.M6L_GATE_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
user: userId || "anon",
input: latestInput,
messages: messages.length,
feature: "nextjs_chat",
}),
signal: AbortSignal.timeout(400),
});
if (gateRes.ok) {
const gate = await gateRes.json();
if (!gate.allow) {
return Response.json({ role: "assistant", content: gate.message }, { status: 200 });
}
}
} catch {
// Fail open on timeout
}
// 2. Safe to call OpenAI or Anthropic
const result = streamText({
model: openai("gpt-4o"),
messages,
});
return result.toDataStreamResponse();
}