Running Websockets/Subscriptions with Fetch / Edge Runtimes Adapter
Hi, has anyone been able to use trpc websockets/subscriptions? I am having challenges setting up the ws server using Fetch / Edge Runtimes Adapter and running it either in dev or production mode. Tried to follow the docs but it does not highlight this bit.
I am using Node 20> and pnpm.
Here is my route handler
Here is my sample router module
And finally here is my base module
14 Replies
The fetch adapter doesn’t support web sockets
If that's the case, then it seems you can only use tRPC subscriptions in Next.js projects that use the pages router.
Using Next.js v.14 with the app router, I found that I could only get tRPC to work using the
fetchRequestHandler
function from the fetch adapter. All code snippets from the docs that explain using Next with tRPC seem to be based on the pages router. Except there's another way - which I can't find in the docs - of setting up tRPC in a Next.js project that uses the app router, it seems I'd have to use the pages router if I want to use tRPC subscriptions.The fetch adapter doesn't support subscriptions either as far as I know? What link are you using for your client?
I'm using the client from the
@trpc/react-query
libraryI understand, but when you use trpc.createClient what link do you use to your server? Because I am pretty sure I could not get subscriptions working that way.
Here's what I'm doing.
The
websocketClient
is defined and exported from another file.The websocker server is set up this way, but I don't get any of the logs in my server terminal
Oh you just have a separate server running for your subscriptions, you made it sound like you were doing subscriptions with the fetchHandler
Oh yeah, I have a separate server for websockets set up. I basically followed the same setup in the example here: https://github.com/trpc/examples-next-prisma-websockets-starter/blob/daf54ca6576f3e290aa4f36dc7d0ff1eb718b716/src/server/wssDevServer.ts.
I don't get any of the logs on the server, but I get these errors on the browser console
Though, that example uses Next.js' pages router, so I had to change the code in the
/trpc/[trpc]
api route to look like the screenshot in my earlier message - that only seemed to work with Next.js app router.@Emmytobs you an now do subscriptions over http with SSE using the httpSubscriptionLink
HTTP Subscription Link | tRPC
httpSubscriptionLink is a terminating link that's uses Server-sent Events (SSE) for subscriptions.