How can I access the session in fastify when using `useWSS: true`?
I've got a fastify/trpc application that looks something like this:
I would expect that the
req
in the createContext
function would have access to the session (and it does if useWSS
is false). However, when using TRPC with websockets, it currently consistently logs undefined
.
I assume this is because I'm misconfiguring something somewhere, but I'm not sure what, and I'm not sure how to solve this. Has anyone experienced this, or does anyone have any suggestions about how to resolve this? Thanks in advance!Solution:Jump to solution
Hi @Mr. Joker, I ended up writing my solution up on my blog, you can read that here: https://jonathan-frere.com/posts/trpc-fastify-websockets/
Specifically, the solution I found was this:
```typescript...
Accessing Fastify Sessions via tRPC Websockets | Jonathan's Blog
This is a quick post to point out a potential issue that might catch you out with using Fastify’s sessions mechanism alongside tRPC’s websockets transport, and how I’ve fixed it in my projects.
The problem happens with an application that looks something like this:
const app = Fastify(); app.register(ws); app.register(fastifyCookie); app.r...
4 Replies
Hey, have you found solution for this? I have same problem with session undefined in created context in websocket subscriptions
I did. Basically, the type of
req
is wrong: for websockets, it's FastifyRequest | IncomingMessage
where IncomingMessage
is the raw node request object. To get hold of the FastifyRequest
object, you can use a Fastify to listen to all incoming requests, and then save those requests in a WeakMap. Then in the context you can use the WeakMap to fetch the original requests out again.
I'll write it up properly tomorrow.Solution
Hi @Mr. Joker, I ended up writing my solution up on my blog, you can read that here: https://jonathan-frere.com/posts/trpc-fastify-websockets/
Specifically, the solution I found was this:
Accessing Fastify Sessions via tRPC Websockets | Jonathan's Blog
This is a quick post to point out a potential issue that might catch you out with using Fastify’s sessions mechanism alongside tRPC’s websockets transport, and how I’ve fixed it in my projects.
The problem happens with an application that looks something like this:
const app = Fastify(); app.register(ws); app.register(fastifyCookie); app.r...
Thank you very much for the information