From 4690fcfa75f2a693bb8b0cc5cc12dbee7b5bb85d Mon Sep 17 00:00:00 2001 From: Daniel O'Connell Date: Thu, 24 Aug 2023 17:34:41 +0200 Subject: [PATCH] Allow localhost for CORS --- app/server-utils/responses.ts | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/app/server-utils/responses.ts b/app/server-utils/responses.ts index 0b5f0f06..cdbab674 100644 --- a/app/server-utils/responses.ts +++ b/app/server-utils/responses.ts @@ -8,16 +8,28 @@ export const jsonCORS = (data: T) => }, }) -export const CORSOptions = (request: Request) => { +const allowedOrigins = (request: Request) => { const origin = request.headers.get('origin') || '' - const isOriginAllowed = ALLOW_ORIGINS == '*' || ALLOW_ORIGINS.split(',').includes(origin) - const allowed = isOriginAllowed ? origin : '' + const allowedOrigins = ALLOW_ORIGINS.split(',') + + // always allow localhost + try { + if (['localhost', '127.0.0.1'].includes(new URL(origin).hostname)) { + return origin + } + } catch (e) { + // ignore errors + } + return ALLOW_ORIGINS == '*' || allowedOrigins.includes(origin) ? origin : '' +} + +export const CORSOptions = (request: Request) => { return json( {}, { headers: { - 'Access-Control-Allow-Origin': allowed, + 'Access-Control-Allow-Origin': allowedOrigins(request), 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE', 'Access-Control-Allow-Headers': 'Content-Type, Authorization, allow-control-allow-origin', },