MrJohz
MrJohz
Explore posts from servers
TtRPC
Created by MrJohz on 4/8/2025 in #❓-help
How can I access the session in fastify when using `useWSS: true`?
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:
// create a new scope so that the hook we add later will only
// affect tRPC-specific requests
app.register((app) => {
// use a WeakMap to avoid leaking memory by holding on to
// requests longer than necessary
const REQS = new WeakMap<
FastifyRequest | IncomingMessage,
FastifyRequest
>();

app.addHook("onRequest", async (req) => {
// associate each raw `IncomingMessage` (`req.raw`) with
// the original `IncomingMessage`
REQS.set(req.raw, req);
});

app.register(fastifyTRPCPlugin, {
prefix: "/trpc",
useWSS: true,
trpcOptions: {
router,
onError,
createContext: ({ req }) => {
// given either a `FastifyRequest` or an
// `IncomingMessage`, fetch the related
// `FastifyRequest` that we saved earlier
const realReq = REQS.get(req.raw ?? req);
if (!realReq)
throw new Error("This should never happen");

console.log(realReq.session); // logs the session object
return {};
},
},
});
});
// create a new scope so that the hook we add later will only
// affect tRPC-specific requests
app.register((app) => {
// use a WeakMap to avoid leaking memory by holding on to
// requests longer than necessary
const REQS = new WeakMap<
FastifyRequest | IncomingMessage,
FastifyRequest
>();

app.addHook("onRequest", async (req) => {
// associate each raw `IncomingMessage` (`req.raw`) with
// the original `IncomingMessage`
REQS.set(req.raw, req);
});

app.register(fastifyTRPCPlugin, {
prefix: "/trpc",
useWSS: true,
trpcOptions: {
router,
onError,
createContext: ({ req }) => {
// given either a `FastifyRequest` or an
// `IncomingMessage`, fetch the related
// `FastifyRequest` that we saved earlier
const realReq = REQS.get(req.raw ?? req);
if (!realReq)
throw new Error("This should never happen");

console.log(realReq.session); // logs the session object
return {};
},
},
});
});
7 replies
TtRPC
Created by MrJohz on 4/8/2025 in #❓-help
How can I access the session in fastify when using `useWSS: true`?
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.
7 replies
SSolidJS
Created by MrJohz on 1/23/2025 in #support
How can I test that all computations were created in a root?
Thanks, that's helpful!
5 replies