Can I use Express and WebSocket on same service [Node]?

I am trying to deploy an API that uses the express library, but this api will also contains a WebSocket (ws library)service used for a connection between API and an app. I tried using different ports for express server and websocket, and it did not work. I now tried using the same port but it throws an EADDRINUSE error.

When I try to use different ports, my external app won’t connect to the websocket, it just throws an ETIMEDOUT error.

Hey there

If you’re using both express and websockets, then the standard way is to “upgrade” the http server to handle websockets. Not running both websocket server and a http server. Websocket server shares the http server with Express.

Before I go into the code it’s worth noting that usually you don’t need express server when you’re running a websockets server. The idea behind websockets is to create a pipe between the client and server by emitting events and listening to them. This is very handy in real time application, for example chat.

Express uses routes and the client sends a http request to those routes and recieves a response. So just be sure not to mix them too much together.

Now on to the code.

const express = require('express')
const ws = require('ws')

const app = express()
const httpServer = app.listen(process.env.PORT)

const wsServer = new ws.Server({ noServer: true })

httpServer.on('upgrade', (req, socket, head) => {
  wsServer.handleUpgrade(req, socket, head, (ws) => {
    wsServer.emit('connection', ws, req)
  })
})

Note that this is not tested code. Just a napkin code strung together from the docs:
websockets/ws: Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js (github.com)

So I am actually a bit new using Express. I wrote an API that uses express to handle the requests from the frontend, and then the API sends a new request to an external app through websockets. I’ve tested it on my local computer and it works fine, but when I deploy it on Render (Both the API and the external APP), the app cannot connect to the API via the websocket address.

Do the solution that you proposed works for what I need?

Hey Eduardo,

If you’re still having an issue with your service, please contact us via the “Contact Support” form via the dashboard.

Jérémy, Render Support

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.