From 632e7979a226927016db412ad4908609bfb29a14 Mon Sep 17 00:00:00 2001 From: Jeff Emmett <46964190+Jeff-Emmett@users.noreply.github.com> Date: Sat, 7 Dec 2024 14:39:57 -0500 Subject: [PATCH] fix CORS --- worker/TldrawDurableObject.ts | 16 +++++++++++++++- worker/worker.ts | 36 +++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/worker/TldrawDurableObject.ts b/worker/TldrawDurableObject.ts index a101989..e958bb6 100644 --- a/worker/TldrawDurableObject.ts +++ b/worker/TldrawDurableObject.ts @@ -97,7 +97,21 @@ export class TldrawDurableObject { // `fetch` is the entry point for all requests to the Durable Object fetch(request: Request): Response | Promise { - return this.router.fetch(request) + try { + return this.router.fetch(request) + } catch (err) { + console.error('Error in DO fetch:', err); + return new Response(JSON.stringify({ + error: 'Internal Server Error', + message: (err as Error).message + }), { + status: 500, + headers: { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*' + } + }); + } } // what happens when someone tries to connect to this room? diff --git a/worker/worker.ts b/worker/worker.ts index 473d4ae..c81ad19 100644 --- a/worker/worker.ts +++ b/worker/worker.ts @@ -133,3 +133,39 @@ const router = AutoRouter({ // export our router for cloudflare export default router + +const corsHeaders = { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type, Authorization', + 'Access-Control-Max-Age': '86400', +}; + +// Add CORS headers to all responses +function handleCors(request: Request) { + // Handle preflight requests + if (request.method === 'OPTIONS') { + return new Response(null, { + headers: corsHeaders + }); + } + + return null; +} + +// Modify the fetch handler +async function handleRequest(request: Request) { + // Handle CORS preflight + const corsResult = handleCors(request); + if (corsResult) return corsResult; + + // Handle the actual request + const response = await router.handle(request); + + // Add CORS headers to the response + Object.entries(corsHeaders).forEach(([key, value]) => { + response.headers.set(key, value); + }); + + return response; +}