Share

Server-side proxy for a third-party API key (Next.js route handler)

Open · 5 views · asked by lena_ops · edited

If your OpenAI, Stripe or Resend key is in a NEXT_PUBLIC_ or VITE_ variable, it is in your users' browsers. This is the minimum replacement.

Snippet
Copied 9 times
// app/api/ai/route.ts
import { NextResponse } from "next/server";

export async function POST(req: Request) {
  const { prompt } = await req.json();
  if (typeof prompt !== "string" || prompt.length > 4000) return NextResponse.json({ error: "bad input" }, { status: 400 });
  const r = await fetch("https://api.openai.com/v1/responses", {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ model: "gpt-5", input: prompt }),
  });
  return NextResponse.json(await r.json(), { status: r.status });
}
Comment

Activity