0Pricing
tRPC End-to-End Type Safe APIs · Ders

Abonelikler için WebSockets Kurulumu

Gerçek zamanlı iletişimi etkinleştirmek için bir WebSocket sunucusu yapılandırın ve bunu tRPC arka ucunuzla entegre edin.

Abonelikler için WebSockets Kurulumu, CoddyKit'te ücretsiz bir tRPC End-to-End Type Safe APIs dersidir. Bu, 4 dersinin 2. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, tRPC End-to-End Type Safe APIs öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. tRPC End-to-End Type Safe APIs kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Real-time with WebSockets

When building modern web applications, real-time updates are often essential. Think of live chat, stock tickers, or notification systems.

Traditional HTTP requests are stateless and short-lived. WebSockets provide a persistent, bidirectional communication channel between a client and a server.

  • Persistent: The connection stays open, unlike HTTP.
  • Bidirectional: Both client and server can send messages at any time.
  • Efficient: Less overhead than constantly polling via HTTP.

Basic WebSocket Server Setup

Before integrating tRPC, let's understand how a standalone WebSocket server works. We'll use the popular ws library for Node.js.

First, install the necessary packages: npm install ws typescript ts-node

This basic server listens for connections and logs when clients connect or send messages.

import ws from 'ws';

const wss = new ws.Server({ port: 3001 });

wss.on('connection', (socket) => {
  console.log('Client connected to raw WS!');

  socket.on('message', (message) => {
    console.log(`Received: ${message}`);
    socket.send(`Echo: ${message}`);
  });

  socket.on('close', () => {
    console.log('Client disconnected from raw WS!');
  });

  socket.send('Welcome to the raw WS server!');
});

console.log('Raw WS server listening on ws://localhost:3001');

tRPC's WebSocket Adapter

tRPC needs a way to communicate over the WebSocket protocol. That's where @trpc/server/adapters/ws comes in.

This adapter allows your tRPC procedures to be exposed and handled by an existing WebSocket server (like the ws server we just saw).

Install it: npm install @trpc/server @trpc/server/adapters/ws

Preparing Your tRPC Router

For tRPC to handle subscriptions over WebSockets, you need a tRPC router and a context factory. This is similar to setting up an HTTP API, but for real-time communication.

Let's define a minimal tRPC setup. We'll add a simple subscription procedure next.

import { initTRPC } from '@trpc/server';

// Create a tRPC instance
const t = initTRPC.create();

// Define your application router
export const appRouter = t.router({
  // This will hold our subscription procedures
  healthcheck: t.procedure.query(() => 'ok'),
});

// Export the router's type for client-side usage
export type AppRouter = typeof appRouter;

// Context factory (can be empty for now)
export const createContext = () => ({});

Integrating tRPC with the WS Server

Now, let's combine our ws server with the tRPC router using the applyWSSHandler function from the adapter.

This function bridges your tRPC procedures to the WebSocket connection, making them available for real-time interaction.

  • wss: Your WebSocket server instance.
  • router: Your tRPC appRouter.
  • createContext: A function to create the tRPC context for each request.
import { applyWSSHandler } from '@trpc/server/adapters/ws';
import ws from 'ws';
import { appRouter, createContext } from './trpc'; // Assuming trpc.ts from previous scene

const wss = new ws.Server({ port: 3001 });

const handler = applyWSSHandler({
  wss,
  router: appRouter,
  createContext,
});

wss.on('connection', (socket) => {
  console.log(`tRPC WS client connected! Total: ${wss.clients.size}`);
  socket.once('close', () => {
    console.log(`tRPC WS client disconnected! Total: ${wss.clients.size}`);
  });
});

console.log('tRPC WS server listening on ws://localhost:3001');

// Optional: Handle graceful shutdown
process.on('SIGTERM', () => {
  console.log('SIGTERM received, closing WS server');
  handler.broadcastReconnectNotification(); // Notify clients to reconnect
  wss.close();
});

Creating a Simple Subscription

tRPC subscriptions use the observable pattern. An observable is a stream of data that a client can subscribe to, receiving updates over time.

Here, we create a basic onHello subscription that immediately sends a greeting and then cleans up.

// Inside your trpc.ts (update appRouter definition)
import { observable } from '@trpc/server/observable';

export const appRouter = t.router({
  healthcheck: t.procedure.query(() => 'ok'),
  onHello: t.procedure.subscription(() => {
    return observable<string>((emit) => {
      // Send a message immediately when subscribed
      emit.next('Hello from tRPC WebSocket!');

      // This function runs when the client unsubscribes
      return () => {
        console.log('Client unsubscribed from onHello');
      };
    });
  }),
});

Full tRPC WebSocket Server Code

Here's the complete server-side setup. You can save this as server.ts and run it with ts-node server.ts.

It combines the tRPC router with a subscription, the ws server, and the integration via applyWSSHandler.

import { initTRPC } from '@trpc/server';
import { applyWSSHandler } from '@trpc/server/adapters/ws';
import ws from 'ws';
import { observable } from '@trpc/server/observable';

// 1. tRPC Setup
const t = initTRPC.create();

const appRouter = t.router({
  healthcheck: t.procedure.query(() => 'ok'),
  onHello: t.procedure.subscription(() => {
    return observable<string>((emit) => {
      emit.next('Hello from tRPC WebSocket!');
      return () => { /* optional cleanup */ };
    });
  }),
});

export type AppRouter = typeof appRouter;
const createContext = () => ({});

// 2. WebSocket Server Setup
const wss = new ws.Server({ port: 3001 });

// 3. Integrate tRPC with WS Server
const handler = applyWSSHandler({
  wss,
  router: appRouter,
  createContext,
});

wss.on('connection', (socket) => {
  console.log(`Client connected! Total: ${wss.clients.size}`);
  socket.once('close', () => {
    console.log(`Client disconnected! Total: ${wss.clients.size}`);
  });
});

console.log('tRPC WebSocket Server listening on ws://localhost:3001');

// 4. Graceful shutdown
process.on('SIGTERM', () => {
  console.log('SIGTERM received, closing WS server');
  handler.broadcastReconnectNotification();
  wss.close();
});

Client-Side WebSocket Link

On the client-side, you need to configure your tRPC client to use the WebSocket connection. This is done with wsLink from @trpc/client/links/wsLink.

The wsLink tells your tRPC client where to connect for real-time data, distinct from your HTTP endpoint.

Install: npm install @trpc/client @trpc/react-query @tanstack/react-query

import { createWSClient, wsLink, httpBatchLink, createTRPCReact } from '@trpc/react-query';
import type { AppRouter } from '../server/server'; // Adjust path to your server's AppRouter

// Create a tRPC React client instance
export const trpc = createTRPCReact<AppRouter>();

// Create a WebSocket client instance
const wsClient = createWSClient({
  url: `ws://localhost:3001`,
});

export const trpcClient = trpc.createClient({
  links: [
    // Use the WebSocket link for subscriptions
    wsLink({
      client: wsClient,
    }),
    // Optionally, use HTTP for queries/mutations
    httpBatchLink({
      url: `http://localhost:3000/api/trpc`,
    }),
  ],
});

Consuming Subscriptions in Frontend

With the client configured, you can now use tRPC's useSubscription hook (if using React Query) to listen for real-time updates.

It works similarly to queries and mutations, but for continuous data streams, providing callbacks for new data and errors.

import React from 'react';
import { trpc } from './trpcClient'; // Assuming trpcClient.ts from previous scene

function MyComponent() {
  const [message, setMessage] = React.useState('Waiting for greeting...');

  // Subscribe to the 'onHello' procedure
  trpc.onHello.useSubscription(undefined, {
    onData(data) {
      // This callback fires whenever the server sends new data
      setMessage(data);
      console.log('Received subscription data:', data);
    },
    onError(err) {
      console.error('Subscription error:', err);
      setMessage(`Error: ${err.message}`);
    },
  });

  return (
    <div>
      <h1>Live Greeting:</h1>
      <p>{message}</p>
    </div>
  );
}

export default MyComponent;

Quick Check: WS Integration

You've learned how to set up a WebSocket server and integrate it with tRPC for real-time subscriptions. Which of the following are essential components or steps for this integration?

Recap: Setting Up WebSockets

You've successfully set up the foundation for real-time communication with tRPC!

  • We started with a basic WebSocket server using the ws library.
  • Then, we integrated our tRPC router with this server using @trpc/server/adapters/ws and applyWSSHandler.
  • We added a simple subscription procedure to our router using the observable pattern.
  • Finally, we configured the client with wsLink and saw how to consume subscriptions using useSubscription.

This robust setup allows your tRPC backend to push real-time updates directly to your frontend clients, leveraging type safety end-to-end.

Sıkça Sorulan Sorular

“Abonelikler için WebSockets Kurulumu” dersi ücretsiz mi?

Evet — “Abonelikler için WebSockets Kurulumu” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve tRPC End-to-End Type Safe APIs kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. tRPC End-to-End Type Safe APIs kursu toplamda 4 dersten oluşur.

“Abonelikler için WebSockets Kurulumu” dersinde ne öğreneceğim?

Gerçek zamanlı iletişimi etkinleştirmek için bir WebSocket sunucusu yapılandırın ve bunu tRPC arka ucunuzla entegre edin. tRPC End-to-End Type Safe APIs ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

tRPC End-to-End Type Safe APIs öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te tRPC End-to-End Type Safe APIs, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 2. dersidir.

“Abonelikler için WebSockets Kurulumu” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu tRPC End-to-End Type Safe APIs dersinde kod yazıp çalıştırabilir miyim?

Evet. Her tRPC End-to-End Type Safe APIs dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. tRPC ile Gerçek Zamanlı İletişime Giriş
  2. Abonelikler için WebSockets Kurulumu
  3. Canlı Veri Aboneliklerini Uygulama
  4. Yeniden Bağlanmayı ve Abonelik Temizliğini Yönetme
← tRPC End-to-End Type Safe APIs Sayfasına Dön