Fix CORS for WebSocket connections
All checks were successful
Build Frontend / Build Frontend (push) Successful in 23s

- 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
This commit is contained in:
2026-01-11 02:33:22 +00:00
parent 9bfed45c0f
commit 4e6fef197e

View File

@@ -68,6 +68,7 @@ const registerPlugins = async (fastify) => {
"http://localhost:5173", "http://localhost:5173",
"http://127.0.0.1:5173", "http://127.0.0.1:5173",
"https://turbotrades.dev", "https://turbotrades.dev",
"https://www.turbotrades.dev",
config.cors.origin, config.cors.origin,
]; ];
@@ -90,6 +91,7 @@ const registerPlugins = async (fastify) => {
callback(new Error("Not allowed by CORS"), false); callback(new Error("Not allowed by CORS"), false);
} }
}, },
preflightContinue: true,
credentials: true, credentials: true,
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"], methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"],
allowedHeaders: [ allowedHeaders: [
@@ -106,6 +108,18 @@ const registerPlugins = async (fastify) => {
maxAge: 86400, // Cache preflight requests for 24 hours 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 // Security headers
await fastify.register(fastifyHelmet, { await fastify.register(fastifyHelmet, {
contentSecurityPolicy: config.isProduction, contentSecurityPolicy: config.isProduction,