Introduction to WebSocket and TypeScript for Real-Time Applications
Modern web applications increasingly require instant data exchange between client and server. The traditional HTTP protocol, operating on a "request-response" principle, is not suitable for tasks where information delivery speed is critical: online chats, stock quotes, multiplayer games, or monitoring systems. This is where WebSocket comes to the rescue — a protocol that provides a persistent two-way connection.
In combination with TypeScript — a strictly typed superset of JavaScript — developing WebSocket applications becomes not only efficient but also safe. TypeScript allows you to catch errors at the compilation stage, improves code readability, and simplifies refactoring. In this article, we will cover the complete cycle of creating a real-time application on WebSocket with TypeScript: from theory to practical examples.
WebSocket Basics: How the Protocol Works
What is WebSocket?
WebSocket (RFC 6455) is a protocol that establishes a persistent connection between a client (browser) and a server. After the handshake, data can be transmitted in both directions without repeated HTTP requests. This reduces latency and network load.
Difference from HTTP
- HTTP: client initiates a request → server responds → connection closes (or remains open for subsequent requests, but is still initiated by the client).
- WebSocket: after the connection is established, the server can send data to the client at any time (push notifications).
WebSocket Connection Lifecycle
- Handshake: the client sends an HTTP request with the header
Upgrade: websocket. The server responds with status code 101 Switching Protocols. - Data Exchange: after a successful handshake, the connection switches to the WebSocket protocol. Data is transmitted in the form of frames.
- Closure: either side can initiate the closure of the connection by sending a special control frame.
Creating a WebSocket Server in TypeScript
Choosing a Library
For the server side, we will use the popular ws library — a lightweight and fast WebSocket implementation for Node.js. Let's install it along with the types for TypeScript:
npm install wsnpm install -D @types/wsBasic Server
Let's create a file server.ts:
import { WebSocketServer, WebSocket } from 'ws';
const PORT = 8080;const wss = new WebSocketServer({ port: PORT });
console.log(`WebSocket server started on ws://localhost:${PORT}`);
wss.on('connection', (ws: WebSocket) => { console.log('New connection');
// Send a welcome message ws.send('Welcome to the server!');
// Handle incoming messages ws.on('message', (message: Buffer) => { const text = message.toString(); console.log(`Received: ${text}`);
// Echo response ws.send(`Echo: ${text}`); });
// Handle connection close ws.on('close', () => { console.log('Client disconnected'); });
// Handle errors ws.on('error', (error: Error) => { console.error('WebSocket error:', error); });});Handling Different Message Types
In real applications, messages are often structured in JSON format. Let's create a typed handler:
interface ChatMessage { type: 'message' | 'join' | 'leave'; username: string; content?: string; timestamp: number;}
wss.on('connection', (ws: WebSocket) => { ws.on('message', (data: Buffer) => { try { const msg: ChatMessage = JSON.parse(data.toString()); switch (msg.type) { case 'join': console.log(`${msg.username} joined`);