Fouad Raheb
Fouad Raheb14mo ago

How to have 2 separate trpc clients for http and websockets?

I'm trying to have a setup where I can use trpc with 2 separate clients, one for normal HTTP requests and one for websockets since most of our site pages do not need a websocket connection. I have tried to create 2 files with 2 different createTRPCNext clients, it works fine in pages that don't use useSubscription but when using it, it looks like only the first trpc client that was initialized will be used, because even if I'm using the websocket client for useSubscription, I'm getting this error TRPCClientError: Subscriptions should use wsLink
8 Replies
Nick
Nick14mo ago
Have a look at our SOA example One client, many backend
Fouad Raheb
Fouad RahebOP14mo ago
Can you please share the SOA example link? I couldn't find it on the site and github, sorry Found it! https://github.com/trpc/trpc/tree/main/examples/soa It didn't help in my case with websockets I'm trying to have this example use 2 separate trpc clients, so that only some queries/mutations/subscriptions use the websocket client and the rest with the default http client https://github.com/trpc/examples-next-prisma-websockets-starter
Nick
Nick14mo ago
Not 100% sure but isn't the splitLink exactly what you want for that? SOA uses it already I believe
Fouad Raheb
Fouad RahebOP14mo ago
I tried using splitLink and requests started going through http but a websocket connection is still starting as showing in dev tools with an empty array message []
No description
Nick
Nick14mo ago
Hm, I think @julius might be our resident websockets and soa pro then
Fouad Raheb
Fouad RahebOP14mo ago
Seems like the only way to not have an empty websocket connection created is by creating wsLink on run time, but this would create multiple connections for each useSubscription. We just need to have a way to not start a connection if no messages are sent yet and no active useSubscription
(runtime) => {
return (ctx) => {
if (ctx.op.type === "subscription") {
return getWSLink()(runtime)(ctx);
} else {
return getBatchLink()(runtime)(ctx);
}
};
},
(runtime) => {
return (ctx) => {
if (ctx.op.type === "subscription") {
return getWSLink()(runtime)(ctx);
} else {
return getBatchLink()(runtime)(ctx);
}
};
},
julius
julius14mo ago
i don't think I've ever touched those the websocket parts - just been fighting our example to work with newer next versions haha
Fouad Raheb
Fouad RahebOP14mo ago
Haha good luck

Did you find this page helpful?