Search code examples
expressherokusocket.ionestjsfastify

Issue with NestJS and Socket.IO app deployment on Heroku (PORT)


I have created an app using NestJS and Socket.IO. I used a gateway to make it listen on a port other than the app's default port. When I run the project on my localhost, it works fine. However, when I deploy it to Heroku, it doesn't respond on the port I specified. I also tried making it listen on the same port as the app, but it logged a 404 error.

Can you help me resolve these issue?


Solution

  • If someone has a similar issue:

    You need to know one thing - only one port is available for your application from Heroku, and Heroku defines it (you only need to use process.env.PORT). Therefore, we put sockets and rest API on the same port.

    To do this, we need to specify the port only for the HTTP server.

    In general, each gateway is listening on the same port as the HTTP server, unless your app is not a web application, or you have changed the port manually. This default behavior can be modified by passing an argument to the @WebSocketGateway(80) decorator where 80 is a chosen port number.

    HTTP:

    app.listen(process.env.PORT)
    

    WSS:

    @WebSocketGateway({ cors: true, })