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", () => {
console.log("SIGTERM");
handler.broadcastReconnectNotification();
wss.close();
});
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", () => {
console.log("SIGTERM");
handler.broadcastReconnectNotification();
wss.close();
});
import { auth } from "@clerk/nextjs/app-beta";
type IUserProps = {
user: User | null;
};

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

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>;
import { auth } from "@clerk/nextjs/app-beta";
type IUserProps = {
user: User | null;
};

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

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>;
AK
Alex / KATT 🐱382d ago
my thinking is that your create context fails and throws an error maybe the auth doesn't work with WSS
Z
zeph1665382d ago
I see! In that case, I'll just try using Pusher instead. Thank you!
M
ManuRodgers378d ago
hey mate, can you give me some code or link to show me how to integrate Pusher or Ably with tRPC?Thanks in advance
Z
zeph1665357d ago
You can checkout this youtube video: https://www.youtube.com/watch?v=Dw4vF2nftAE Jump to the 10min mark
Scalable Scripts
YouTube
Build a Realtime Chat App with React
👉 Check our website: https://scalablescripts.com Learn how to create a Realtime Chat App with React and Pusher. Source Code: https://github.com/scalablescripts/react-chat This video can be combined with other videos: React and NodeJS Chat App: https://www.youtube.com/playlist?list=PLlameCF3cMEvB8N2bhctdqCMfj1q5aiZh React and NestJS Chat App:...
More Posts
Pagination QueryHi, I'm new for web dev and I'm moved to tRPC not so long I'm looking for example of pagination quEnrich the response object for TRPC endpointCurrently when I hit a trpc endpoint I get something like: ```typescript { result: { data:Can i fetch tRPC in different project@coco- : I Make a tRPC in my project. Can I use the enpoint api in different project ?Importing AppRouter types from an external repoI've got a production T3 app already in production. I've created a fresh expo app to start building TypeScript type for request object for route handlersSo far I've been writing my routes like: ```typescript export const router = t.router({ helloWorlTyped wrappers for proceduresI have a TRPC client with working queries and mutations. I wanted to create wrapper functions for alAre TRPC server procedures actual endpoints? Meaning can you directly do a `post` request to them?Lets say you have a public procedure called `getHelloWorld`, can you hit it by doing `localhost:3000TRPCClientError - No "query"-procedure on path "user.all"Im using react native expo, prisma, trpc and the postgres database is on railway I have run the follAm I the only one struggling with pnpm + TypeScript monorepo + trpc?Hello all, When using pnpm in a TypeScript monorepo without `node-linker`, I hit those errors: ```tRPC standalone server in monorepoHi, I'm using t3-stack monorepo as my base and I've swapped out NextJS backend for standalone HTTP Codemod to v10 is not modifying any fileHello 👋, I must be super dumb but running `pnpm dlx trpc-v10-migrate-codemod ` in my project isn't No overload matches this call when outputting unionsHello there 👋, I have this simple procedure (we're not fully migrated on v10 yet, using interop):