web socket keeps on disconnecting and connecting

Hi! Its my first time using web sockets. The first code snippet is my socket code. The second code snippet is where I create context to use in the applyWSSHandler. My issue is that in my createContext function. When I try to use the getUser function, the socket keeps on connecting and disconnecting rapidly (like every few milliseconds). But the moment I remove that function, everything works fine. Any idea what could be issue? The create context has no issue without running the socket.
Thank you!

import { createContext } from "./context";
import { appRouter } from "./router";
import { applyWSSHandler } from "@trpc/server/adapters/ws";
import ws from "ws";
const wss = new ws.Server({
  port: 3002,
const handler = applyWSSHandler({ wss, router: appRouter, createContext });

wss.on("connection", (ws) => {
  console.log(`➕➕ Connection (${wss.clients.size})`);
  ws.once("close", () => {
    console.log(`➖➖ Connection (${wss.clients.size})`);

wss.on("error", (err) => {
  console.error("WebSocket error", err);
console.log("✅ WebSocket Server listening on ws://localhost:3002");

process.on("SIGTERM", () => {

import { auth } from "@clerk/nextjs/app-beta";
type IUserProps = {
  user: User | null;

const ee = new EventEmitter();
export const createContextInner = async ({ user }: IUserProps) => {
  return {

async function getUser() {
  // get userId from request
  const { userId } = auth();
  // get full user object
  const user = userId ? await clerkClient.users.getUser(userId) : null;
  return user;

export const createContext = async () => {
  const user = await getUser();
  return await createContextInner({ user });

export type Context = inferAsyncReturnType<typeof createContext>;
A/Kalex / KATT4/13/2023
my thinking is that your create context fails and throws an error
A/Kalex / KATT4/13/2023
maybe the auth doesn't work with WSS
I see! In that case, I'll just try using Pusher instead. Thank you!
hey mate, can you give me some code or link to show me how to integrate Pusher or Ably with tRPC?Thanks in advance
You can checkout this youtube video: https://www.youtube.com/watch?v=Dw4vF2nftAE
Jump to the 10min mark