Skip to content
Prev Previous commit
Next Next commit
add cors handdling and options
  • Loading branch information
sid597 committed Mar 31, 2025
commit ed6c5b235550a3ea7bcce4eb783ce705ec9309d2
15 changes: 14 additions & 1 deletion apps/website/app/api/llm-endpoints/chat-openai/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { NextRequest } from "next/server";
import { NextRequest, NextResponse } from "next/server";

type Message = {
role: string;
Expand All @@ -19,6 +19,7 @@ type RequestBody = {

const CONTENT_TYPE_JSON = "application/json";
const CONTENT_TYPE_TEXT = "text/plain";
const allowedOrigins = ["https://roamresearch.com", "http://localhost:3000"];

export const runtime = "nodejs";
export const preferredRegion = "auto";
Expand Down Expand Up @@ -95,6 +96,18 @@ export async function POST(request: NextRequest): Promise<Response> {
}
}

export async function OPTIONS(request: Request) {
const origin = request.headers.get("origin");
const isAllowedOrigin = origin && allowedOrigins.includes(origin);
const response = new NextResponse(null, { status: 204 });
if (isAllowedOrigin) {
response.headers.set("Access-Control-Allow-Origin", origin);
response.headers.set("Access-Control-Allow-Methods", "POST, OPTIONS");
response.headers.set("Access-Control-Allow-Headers", "Content-Type");
}
return response;
}

function createErrorResponse(message: string, status: number): Response {
return new Response(JSON.stringify({ error: message }), {
status,
Expand Down