renardeinsR
tRPC17mo ago
renardeins

Correct types and payload for the applyWSSHandler with createContext

Hey everyone,

I'm using t3 stack and trying to add websocket handler for my setup. I'm following this example - https://github.com/trpc/examples-next-prisma-websockets-starter.

My create context func looks like this:
import type { CreateNextContextOptions } from "@trpc/server/adapters/next";
import type { CreateWSSContextFnOptions } from "@trpc/server/adapters/ws";
import { getSession } from "next-auth/react";

/**
 * Creates context for an incoming request
 * @link https://trpc.io/docs/v11/context
 */
export const createContext = async (
  opts: CreateNextContextOptions | CreateWSSContextFnOptions,
) => {
  const session = await getSession(opts);

  console.log("createContext for", session?.user?.name ?? "unknown user");

  return {
    session,
  };
};

export type Context = Awaited<ReturnType<typeof createContext>>;


and I'm using it like this:
const wss = new WebSocketServer({
  port: 3001,
});
const handler = applyWSSHandler({ wss, router: appRouter, createContext });

unfortunately I see the following typing error in VSCode:
Type '(opts: CreateNextContextOptions | CreateWSSContextFnOptions) => Promise<{ session: Session | null; }>' is not assignable to type 'CreateWSSContextFn<Router<{ ctx: { session: Session | null; db: PrismaClient<{ log: ("error" | "query" | "warn")[]; }, never, DefaultArgs>; }; meta: object; errorShape: { data: { ...; }; message: string; code: TRPC_ERROR_CODE_NUMBER; }; transformer: true; }, {}>>'.


What needs to be fixed to make this work correctly?
Was this page helpful?