How do I add a Websocket server to a normal tRPC HTTP server for realtime events?
I have a project that contains the following:
- Express API using TRPC
- CapacitorJS mobile app using SolidJS
- PWA app using SolidJS
The PWA has a QR code that displays on a TV in a physical building. The mobile app can scan this QR code and log the user into the system. I wanted to use a websocket implementation so that the PWA knows when the user is authenticated after the QR code scan. If it's possible, I would like the websocket connection to live inside the API project, but I'm not sure if that is doable. My infrastructure is already set up for one API server, it would be great to somehow handle all the requests with one server.
Is this possible? And can you point me to any documentation about how to set that up?
Thanks!
4 Replies
I'm using Hono + tRPC + SocketIO on the same server. Here's how I did it (abbreviated):
The setup with Express should be similar
If you just need to subscribe to events we would generally recommend you go for an SSE implementation over the web sockets one. It’s simpler to get working with tRPC and more fault tolerant by default
There should be no issue getting it working with express though I haven’t done that myself, I believe it wouldn’t require any changes to express whereas web sockets might need you to handle the upgrade event
There are example projects you can refer to though in either case