Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 387
CedricLaberge Avatar asked Jan 29 '21 15:01

CedricLaberge


2 Answers

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

@WebSocketGateway({ cors: true })
like image 112
Chad Faurie Avatar answered Oct 17 '22 17:10

Chad Faurie


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));
like image 22
Lilian Tonofa Avatar answered Oct 17 '22 16:10

Lilian Tonofa