From 4e6fef197e25aa973bb2b538f1f84a7bb342d5a3 Mon Sep 17 00:00:00 2001 From: iDefineHD Date: Sun, 11 Jan 2026 02:33:22 +0000 Subject: [PATCH] Fix CORS for WebSocket connections - Added www.turbotrades.dev to allowed origins - Skip CORS validation for WebSocket upgrade requests - Allow WebSocket connections from any origin with credentials - Fixes 500 CORS error on /ws endpoint --- index.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/index.js b/index.js index b7a7cb2..7201b7a 100644 --- a/index.js +++ b/index.js @@ -68,6 +68,7 @@ const registerPlugins = async (fastify) => { "http://localhost:5173", "http://127.0.0.1:5173", "https://turbotrades.dev", + "https://www.turbotrades.dev", config.cors.origin, ]; @@ -90,6 +91,7 @@ const registerPlugins = async (fastify) => { callback(new Error("Not allowed by CORS"), false); } }, + preflightContinue: true, credentials: true, methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"], allowedHeaders: [ @@ -106,6 +108,18 @@ const registerPlugins = async (fastify) => { maxAge: 86400, // Cache preflight requests for 24 hours }); + // Skip CORS for WebSocket connections + fastify.addHook("preHandler", async (request, reply) => { + // Allow WebSocket upgrade requests from any origin + if (request.raw.headers.upgrade === "websocket") { + reply.header( + "Access-Control-Allow-Origin", + request.headers.origin || "*" + ); + reply.header("Access-Control-Allow-Credentials", "true"); + } + }); + // Security headers await fastify.register(fastifyHelmet, { contentSecurityPolicy: config.isProduction,