Fix CORS for WebSocket connections
All checks were successful
Build Frontend / Build Frontend (push) Successful in 23s
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:
14
index.js
14
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,
|
||||
|
||||
Reference in New Issue
Block a user