acronie
acronie17mo ago

Not able to implement websockets with trpc

import { applyWSSHandler } from "@trpc/server/adapters/ws";
import ws from "ws";
import { createTRPCContext } from "./api/trpc";
import { appRouter } from "./api/root";

const wss = new ws.Server({
port: 3001,
});
const handler = applyWSSHandler({
wss,
router: appRouter,

createContext: createTRPCContext,
});

wss.on("connection", (ws) => {
console.log(`➕➕ Connection (${wss.clients.size})`);
ws.once("close", () => {
console.log(`➖➖ Connection (${wss.clients.size})`);
});
});
console.log("✅ WebSocket Server listening on ws://localhost:3001");

process.on("SIGTERM", () => {
console.log("SIGTERM");
handler.broadcastReconnectNotification();
wss.close();
});
import { applyWSSHandler } from "@trpc/server/adapters/ws";
import ws from "ws";
import { createTRPCContext } from "./api/trpc";
import { appRouter } from "./api/root";

const wss = new ws.Server({
port: 3001,
});
const handler = applyWSSHandler({
wss,
router: appRouter,

createContext: createTRPCContext,
});

wss.on("connection", (ws) => {
console.log(`➕➕ Connection (${wss.clients.size})`);
ws.once("close", () => {
console.log(`➖➖ Connection (${wss.clients.size})`);
});
});
console.log("✅ WebSocket Server listening on ws://localhost:3001");

process.on("SIGTERM", () => {
console.log("SIGTERM");
handler.broadcastReconnectNotification();
wss.close();
});
I have something like this atp in very early stage of trying websocket this is how my server looks rn. The connection isn't started for some reason on the server 🤔
2 Replies
acronie
acronieOP17mo ago
links: [
loggerLink({
enabled: (opts) =>
process.env.NODE_ENV === "development" ||
(opts.direction === "down" && opts.result instanceof Error),
}),
httpBatchLink({
url: `${getBaseUrl()}/api/trpc`,
}),
wsLink({
client: wsClient,
}),
],
links: [
loggerLink({
enabled: (opts) =>
process.env.NODE_ENV === "development" ||
(opts.direction === "down" && opts.result instanceof Error),
}),
httpBatchLink({
url: `${getBaseUrl()}/api/trpc`,
}),
wsLink({
client: wsClient,
}),
],
this is how it's lookijng the next client Anyone 😅 Subscription error: TRPCClientError: Subscriptions should use wsLink getting this error
pjnicolas
pjnicolas16mo ago
I'm a little late, but try using this links:
links: [
splitLink({
condition: (op) => op.type === 'subscription',
true: wsLink({ client: wsClient }),
false: httpBatchLink({ url: `${getBaseUrl()}/api/trpc` }),
}),
],
links: [
splitLink({
condition: (op) => op.type === 'subscription',
true: wsLink({ client: wsClient }),
false: httpBatchLink({ url: `${getBaseUrl()}/api/trpc` }),
}),
],