구독을 위한 WebSockets 설정
WebSocket 서버를 구성하고 tRPC 백엔드와 연동하여 실시간 통신을 활성화합니다.
구독을 위한 WebSockets 설정은(는) CoddyKit의 무료 tRPC End-to-End Type Safe APIs 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 tRPC End-to-End Type Safe APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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 tRPCappRouter.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
wslibrary. - Then, we integrated our tRPC router with this server using
@trpc/server/adapters/wsandapplyWSSHandler. - We added a simple subscription procedure to our router using the
observablepattern. - Finally, we configured the client with
wsLinkand saw how to consume subscriptions usinguseSubscription.
This robust setup allows your tRPC backend to push real-time updates directly to your frontend clients, leveraging type safety end-to-end.
자주 묻는 질문
“구독을 위한 WebSockets 설정” 강의는 무료인가요?
네 — “구독을 위한 WebSockets 설정” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 tRPC End-to-End Type Safe APIs 강의 전체를 잠금 해제할 수 있습니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
“구독을 위한 WebSockets 설정”에서 뭘 배우나요?
WebSocket 서버를 구성하고 tRPC 백엔드와 연동하여 실시간 통신을 활성화합니다. 브라우저에서 직접 실행하는 실습 코드로 tRPC End-to-End Type Safe APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
tRPC End-to-End Type Safe APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 tRPC End-to-End Type Safe APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“구독을 위한 WebSockets 설정” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 tRPC End-to-End Type Safe APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 tRPC End-to-End Type Safe APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- tRPC 실시간 기능 소개
- 구독을 위한 WebSockets 설정
- 실시간 데이터 구독 구현
- 재연결과 구독 정리 처리