WebSocket Gateway is not working properly when Nest application is created by using ExpressAdapter.
It seems that the gateway is not linked properly to the http service - client gets 404 upon connection, gateway itself seems to be initiated (OnGatewayInit is executed with meaningful result).
I've created minimal code to reproduce.
In the main.ts there are two bootstrap method implementations - one works, second one doesn't.
There is client.js file to simulate the client. Simply run it with node client.js - it should produce console logs in both server (when socket is properly connected) and in client (upon connection error).
https://github.com/adrianpiesiak/NestJs-socket-bug
The WebSocketGateway should work in both bootstrapping methods
Node: 10.15.2
@nestjs/[email protected]
@nestjs/[email protected]
@nestjs/platform-socket.[email protected]
@nestjs/[email protected]
Try to
const httpServer = await https.createServer(httpsOptions, server).listen(port);
app.useWebSocketAdapter(new IoAdapter(httpServer));
await app.init();
If you replace this line:
http.createServer(server).listen(3000);
with this line
await app.listen(3000);
it's gonna work fine. Why are you trying to spin up http
server manually? You can access HTTP server created by Nest easily:
const httpServer = app.getHttpServer();
Also, you don't have to use ExpressAdapter
to have full control over express
instance - you can simply call this instead:
const express = app.getHttpAdapter().getInstance();
EDIT:
@kamilmysliwiec - The example wasn't showing the intention - which is, instantiate the app, so that you can get a some applications services instances injected into the main.ts file, so that you can read e.g. http / https / certificates / etc and apply them to the http server, without breaking the socket gateway ;)
Thanks for quick answer, but sadly your answer with just replacing the initialization to
await app.init()
isn't going to work for me, as it doesn't allow to specify https options.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
If you replace this line:
with this line
it's gonna work fine. Why are you trying to spin up
http
server manually? You can access HTTP server created by Nest easily:Also, you don't have to use
ExpressAdapter
to have full control overexpress
instance - you can simply call this instead:see https://docs.nestjs.com/faq/http-adapter