Setting Up WebSockets for Subscriptions
Configure a WebSocket server and integrate it with your tRPC backend to enable real-time communication.
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');All lessons in this course
- Introduction to Real-time with tRPC
- Setting Up WebSockets for Subscriptions
- Implementing Live Data Subscriptions
- Handling Reconnection and Subscription Cleanup