⚙
4w ago

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
FluX
FluX4w ago
I'm using Hono + tRPC + SocketIO on the same server. Here's how I did it (abbreviated): The setup with Express should be similar
// API index.ts
import { serve } from "@hono/node-server"

const app = new Hono()
app.use("/api/*", trpcServer({ endpoint: "/api", router: appRouter, createContext }))

const server = serve({ ...app, port: 3100 })
startWsServer(server as Server)
// API index.ts
import { serve } from "@hono/node-server"

const app = new Hono()
app.use("/api/*", trpcServer({ endpoint: "/api", router: appRouter, createContext }))

const server = serve({ ...app, port: 3100 })
startWsServer(server as Server)
// In another file
import { Server } from "socket.io"
import type { Server as HTTPServer } from "node:http"

export const io = new Server({
path: "/ws",
transports: ["websocket", "polling"],
})

export function startWsServer(httpServer: HTTPServer) {
io.attach(httpServer, {
cors: {
credentials: true,
},
})

io.on("connection", (socket) => {
/* ... */
})
}
// In another file
import { Server } from "socket.io"
import type { Server as HTTPServer } from "node:http"

export const io = new Server({
path: "/ws",
transports: ["websocket", "polling"],
})

export function startWsServer(httpServer: HTTPServer) {
io.attach(httpServer, {
cors: {
credentials: true,
},
})

io.on("connection", (socket) => {
/* ... */
})
}
Nick
Nick4w ago
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
Nick
Nick4w ago
There are example projects you can refer to though in either case

Did you find this page helpful?