From 610649b08f2561378b3aec4cb7e2cc7515c936e8 Mon Sep 17 00:00:00 2001 From: Kenneth Date: Tue, 3 Jun 2025 13:33:25 +0000 Subject: [PATCH] fix cors not handling multi origins --- packages/server/src/http-handler.ts | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/packages/server/src/http-handler.ts b/packages/server/src/http-handler.ts index 0f675bb..baf9147 100644 --- a/packages/server/src/http-handler.ts +++ b/packages/server/src/http-handler.ts @@ -2,7 +2,7 @@ import { HttpError } from "./error.ts" type HttpMethod = "GET" | "POST" | "DELETE" | "PUT" | "OPTIONS" | "PATCH" -const ALLOWED_ORIGINS = ["http://localhost:5173"] +const ALLOWED_ORIGINS = ["http://localhost:5173", "http://127.0.0.1:5173"] function httpHandler( handler: (request: Bun.BunRequest) => Promise, @@ -23,7 +23,8 @@ function httpHandler( response = new Response(undefined, { status: 500 }) } } - for (const origin of ALLOWED_ORIGINS) { + const origin = request.headers.get("Origin") + if (origin && ALLOWED_ORIGINS.includes(origin)) { response.headers.set("Access-Control-Allow-Origin", origin) } response.headers.set("Access-Control-Allow-Credentials", "true") @@ -35,16 +36,21 @@ function preflightHandler({ allowedMethods, allowedHeaders, }: { allowedMethods: HttpMethod[]; allowedHeaders: string[] }) { - return async (request: Bun.BunRequest) => - new Response(undefined, { + return async (request: Bun.BunRequest) => { + const origin = request.headers.get("Origin") + const headers: Record = { + "Access-Control-Allow-Methods": allowedMethods.join(", "), + "Access-Control-Allow-Credentials": "true", + "Access-Control-Allow-Headers": allowedHeaders.join(", "), + } + if (origin && ALLOWED_ORIGINS.includes(origin)) { + headers["Access-Control-Allow-Origin"] = origin + } + return new Response(undefined, { status: 200, - headers: { - "Access-Control-Allow-Origin": ALLOWED_ORIGINS.join(", "), - "Access-Control-Allow-Methods": allowedMethods.join(", "), - "Access-Control-Allow-Credentials": "true", - "Access-Control-Allow-Headers": allowedHeaders.join(", "), - }, + headers, }) + } } export { httpHandler, preflightHandler }