Context with trpc ws client
Hello! I've implemented trpc to my nextjs 14 app router project, along with trpc socket subscriptions. I recently started making use of trpc context and implemented an asyncrhinous check to my session handler in order to append session information to my trpc context. This all works fine for the majority of my trpc functionality (non websocket stuff), however my clients are unable to establish a websocket connection to the server as every time the initial upgrade request is sent, the server 500 errors due to the added context initialisation.
The error seems to be caused because some server component functionality ( cookies() ) is called during the call to fetch session information during context initialisation for the socket. Why does this cause an error when initliasing the trpc websocket client and not when making a standard trpc request?
I should note that I followed this example to initialise my seperate websocket server. ( ws server is hosted on port 3001, main next app is on port 3000, could this possible be a cors issue?) https://github.com/trpc/examples-next-prisma-websockets-starter/blob/main/src/server/wssDevServer.ts
I've attached most of my core trpc initialisation code.
any help would be greatly appreciated, I've been toying with this issue for days now and it is really hindering my project's development. Thanks.
9 Replies
console when app is running (sockets connect then instantly disconnect. Notice 'creating TRPC context' is logged, but 'created trpc context!' is not, meaning error occurs in 'getServerSession' call.)
Also attached is 'getServerSession' function.
error also occurs if I only make a call 'headers()' (another server side only function) in my context creation function. I receive a very similar error as a result of doing so. See attached. I also tried to use 'redirect' another server function. This also caused an error. For this reason I think the error is definitely being caused because somehow we are calling the createTRPCContext function from within a client component?
I am also stuck with the same problem with no lead.
WebSocket connections do not go through NextJS, you cannot use next/headers within that context
How would one go about identify who a socket belongs to then? If not headers, as typically one would check for an auth cookie header or something along those lines.
Still the request headers, but now from the websocket connection request object
You could take a look at my repo https://github.com/BeBoRE/ei-noah-bot it uses an outdated version of lucia auth tho and ws connetions are proxied
GitHub
GitHub - BeBoRE/ei-noah-bot: De officiële Discord Bot voor de Sweat...
De officiële Discord Bot voor de Sweaty GG Chat. Contribute to BeBoRE/ei-noah-bot development by creating an account on GitHub.
thanks bud đź‘Ś