Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nestjs server does not serve socket.io client

Tags:

nestjs

I have a split app using nestjs on the server and an Angular app as the client. Setting up websockets with socket.io seemed pretty easy using the @nestjs/websockets module and on the client I used ngx-socket-io. I used this repo as basis. Now when I update the project's @nestjs/websockets dependency to the latest version I get

  • CORS errors and
  • an error that the client couldn't load the socket.io client js file http://localhost:3000/socket.io/?EIO=3&transport=polling&t=Mg48H4P

I expected CORS problems and after the update, I could fix them by adding

  app.enableCors({
    origin: 'http://localhost:4200',
    credentials: true,
  });

to my main.ts file, but I don't know why the client file is not served. With the version of the repo (5.7.x) there are neither CORS errors nor problems with serving the file.

I tried a couple of settings of @WebSocketGateway(), moving to a different port, setting serveClient (even though it should be true by default), but nothing seemed to work. Any advice?

thanks

like image 882
KenavR Avatar asked Mar 05 '26 13:03

KenavR


2 Answers

In my case I replaced

app.useWebSocketAdapter(new WsAdapter(app));

from

import { WsAdapter } from '@nestjs/platform-ws';

with

app.useWebSocketAdapter(new IoAdapter(app));

in main .ts from

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

Worked like a charm!

like image 124
Divek John Avatar answered Mar 08 '26 21:03

Divek John


The problem was that nestjs did separate the lower level platform (socket.io, express, fastify, ...) from the nestjs modules. The websocket module requires to install an underlying platform, for socket.io

npm install --save @nestjs/platform-socket.io

To serve the socket.io client file it seems like there also needs to be an HTTP platform installed, for express

npm install --save @nestjs/platform-express

More info in the migration guide for v6.

like image 25
KenavR Avatar answered Mar 08 '26 20:03

KenavR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!