CORS error with socket-io connections on Chrome v88+ and Nestjs server
Asked Answered
T

4

18

I have an application connecting to a Nestjs server to establish a WS connection (server is on a different URL, so it is a CORS request).

The WebsocketGateway is defined as such.

@WebSocketGateway(port, {
  handlePreflightRequest: (req, res) => {
    const headers = {
      'Access-Control-Allow-Headers': 'Authorization',
      'Access-Control-Allow-Origin': 'the page origin',
      'Access-Control-Allow-Credentials': true,
    };
    res.writeHead(200, headers);
    res.end();
  }
})

Works like a charm on Chrome v87 and down and on Firefox. Since upgrading my browser to Chrome 88, the front-end socket-io connection goes on a connect-reconnect loop, as:

  1. The preflight request passes and gets a 200 response, with the headers set above;
  2. The actual connection fails with CORS error as the only message in the browser console
Tbar answered 29/1, 2021 at 15:35 Comment(0)
O
78

Just incase someone else needs this, in your decorator there is a cors property

@WebSocketGateway({ cors: true })
Omor answered 3/8, 2021 at 13:22 Comment(6)
Thanks! Works for me. Should be accepted as the right answer.Avlona
This did the trick! Just one small note to remember to align the versions of socket.io between server and client (I was stuck in this issue, even after adding cors: true when using different versions).Kiernan
Thank you thank you thank you! I was diving down a nasty rabbit hole of code trying to get this to work. This really needs to be in the core documentation!Olivann
If I set it to only true, does it restrict connections? How do I restrict the connections?Convene
It worked as expected, but I am still getting the message in the console: WebSocket connection to 'ws://localhost:3000/ws' failed:Idiolect
Thanks! That works for me! (it very helps for deploying on Heroku)Albatross
T
18

This is how i fixed

import { IoAdapter } from '@nestjs/platform-socket.io';
import { ServerOptions } from 'socket.io';

export class SocketAdapter extends IoAdapter {
  createIOServer(
    port: number,
    options?: ServerOptions & {
      namespace?: string;
      server?: any;
    },
  ) {
    const server = super.createIOServer(port, { ...options, cors: true });
    return server;
  }
}

main.ts

const app = await NestFactory.create(AppModule, { cors: true });
app.useWebSocketAdapter(new SocketAdapter(app));
Tradesfolk answered 9/7, 2021 at 13:20 Comment(3)
It works thank you. But I don't know if it's normal to do that . I think it must be implemented directly in Nest or should be in the documentationChacha
That was really great! It finished many hours of total desolation. : )Charmine
You saved my life after hours of fixing the issue. Legend.Preciado
A
1

I had a problem connecting to a WebSocket which always gives me CORS Error in network tab. fixed that issue by adding transports object to socket instance as follows.

   const socket = io(SOCKET_URL, {
      transports: ['websocket'],
    });

ref: https://github.com/socketio/socket.io-client/issues/641

Affiance answered 26/10, 2023 at 10:6 Comment(1)
thanks, this works. i have same problem, which is cors error in chrome devtools network tabPropose
H
0

If you are using cookie authentication ensure you set the credential cors property to true. For example:

@WebSocketGateway({
  cors: {
    origin: [IPs],
    credentials: true,
  },
  transports: ['websocket', 'polling'],
})
Haslett answered 18/5, 2023 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.