Reputation: 5
I am not getting any errors when the frontend is already running and then i start the server. The socket connection is formed without any issues. However, If I disconnect the frontend and start again, it gives me CORS error: The error looks like this:
Access to XMLHttpRequest at 'http://localhost:3001/socket.io/?EIO=4&transport=polling&t=pypdmqlh' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
This is the socket cors:
export const registerSocketServer = (server: HttpServer) => {
const io = new Server<
ClientToServerEvents,
ServerToClientEvents,
InterServerEvents,
SocketData
>(server, {
cors: {
// origin: true,
origin: [`${process.env.FRONTEND_URL}`, "*"],
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
credentials: true,
// allowedHeaders: "*",
allowedHeaders: [
"Content-Type",
"AccessKey",
"st-auth-mode",
"rid",
"x-file-name",
"x-start-byte",
"x-end-byte",
"x-total-size",
"content-type",
"Access-Control-Max-Age",
"Access-Control-Allow-Origin",
"Access-Control-Allow-Methods",
"Access-Control-Allow-Headers",
...getAllCORSHeaders(),
],
},
// allow max 10mb file
maxHttpBufferSize: 1e7,
});
This is the cors setup in server.js:
app.use(
cors({
origin: [`${process.env.FRONTEND_URL}`, "*"],
// // origin: "*", //allow all
// // allowedHeaders: ["content-type", ...getAllCORSHeaders()],
allowedHeaders: [
"Content-Type",
"AccessKey",
"st-auth-mode",
"rid",
"x-file-name",
"x-start-byte",
"x-end-byte",
"x-total-size",
"content-type",
"Access-Control-Max-Age",
"Access-Control-Allow-Origin",
"Access-Control-Allow-Methods",
"Access-Control-Allow-Headers",
...getAllCORSHeaders(),
],
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true, // Ensure credentials are allowed
}),
);
headers of the preflight request
Upvotes: 0
Views: 30
Reputation: 29
It sounds like your issue happens when the frontend reconnects, which could be due to stale CORS settings or how preflight requests are handled. A few things you might want to try:
1️⃣ Instead of ["${process.env.FRONTEND_URL}", ""], try just process.env.FRONTEND_URL. Using "" alongside credentials can cause conflicts. 2️⃣ Make sure OPTIONS is included in the allowed methods, so preflight requests go through correctly. 3️⃣ Try manually disconnecting the socket before reconnecting—it could be holding onto an old session.
If it still acts up, logging the request headers when the issue happens might give you more clues. Hope this helps!
Upvotes: 0