# Multiple WebSocket servers in a single Express instance

Published: 28 August 2021
Category: Technology

I use [Postgraphile](https://www.graphile.org/postgraphile/) for a lot of things.  It gives me an extremely powerful GraphQL interface to my PostgreSQL databases.  It also supports [pub/sub subscriptions](https://www.graphile.org/postgraphile/subscriptions/) for realtime data updates.

As part of an application I was building I needed another WebSocket server for other client interactions that didn’t touch the database, so the WebSocket implementation in Postgraphile couldn’t do what I wanted.

A lot of articles describing [how to setup a WebSocket server with Express](https://masteringjs.io/tutorials/express/websockets) tell you to hook into the `upgrade` event of the Express server.

Since I didn’t want to interfere with the subscription functionality of Postgraphile this wouldn’t cut it.

Thankfully, Postgraphile only listens to `upgrade` events that are sent to `/graphql` (by default, this route is configurable).

Using the same approach I could configure my WebSocket server to listen on my own route.

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

const app = express();

const server = app.listen(3000);

server.on("upgrade", (request, socket, head) => {
  if (request.url === "/custom") {
    wsServer.handleUpgrade(request, socket, head, (client) => {
      wsServer.emit("connection", client, request);
    });
  }
});
~~~
