Why WebSockets Are the Magic of Real-Time?
\nImagine you open a support chat, send a message, and... wait. One second, two, five. Sound familiar? This is the classic HTTP request: you ask, the server answers. But what if the server itself wants to say something? For example, a new order in a CRM or a voice in an online game? Here HTTP falls short — it requires constant ping-pong.
\nWebSockets solve this problem radically. They create a persistent two-way channel between the client and server. One "handshake" — and data flows in both directions instantly. No extra traffic, no delays. Just pure real-time magic.
\nIn this article, we will build a full-fledged real-time application in TypeScript. We'll learn to work with a WebSocket server on Node.js, set up the client, and even add error handling. By the end, you'll be able to write your own chat, notification system, or multiplayer game.
\n\nWhat Are WebSockets and Why Do You Need Them?
\nWebSocket is a protocol over TCP that provides a persistent connection between the browser and the server. Unlike HTTP, where each request opens and closes a connection, WebSocket keeps it open.
\nWhere is this critical?
\n- \n
- Chats and messengers — messages arrive without delay. \n
- Online games — player positions update in real time. \n
- Stock quotes — prices change every millisecond. \n
- Collaborative editing — like Google Docs. \n
TypeScript adds strict typing to this. You won't accidentally send a string instead of a number — the compiler will catch the error at the development stage. This saves you from bugs in production.
\n\nProject Setup: Node.js + TypeScript + WebSocket
\nLet's start with initialization. Make sure you have Node.js (version 18+) and npm installed.
\nmkdir websocket-ts-chat\ncd websocket-ts-chat\nnpm init -y\nnpm install ws @types/ws typescript ts-node @types/node\nnpx tsc --init\nIn tsconfig.json, enable strict mode and specify outDir: "./dist". This is the foundation for any TypeScript project.
Writing a WebSocket Server in TypeScript
\nCreate a file server.ts. Here we will start a WebSocket server on port 8080.
import { WebSocketServer, WebSocket } from 'ws';\n\nconst wss = new WebSocketServer({ port: 8080 });\n\ninterface CustomWebSocket extends WebSocket {\n id: string;\n username?: string;\n}\n\nwss.on('connection', (ws: CustomWebSocket) => {\n ws.id = generateId();\n console.log(`Client connected: ${ws.id}`);\n\n ws.on('message', (data: Buffer) => {\n const message = data.toString();\n console.log(`Received: ${message}`);\n\n // Broadcast to everyone except the sender\n wss.clients.forEach((client) => {\n if (client !== ws && client.readyState === WebSocket.OPEN) {\n client.send(`[${ws.id}]: ${message}`);\n }\n });\n });\n\n ws.on('close', () => {\n console.log(`Client disconnected: ${ws.id}`);\n });\n\n ws.send('Welcome to the chat!');\n});\n\nfunction generateId(): string {\n return Math.random().toString(36).substring(2, 9);\n}\n\nconsole.log('Server started on ws://localhost:8080');\nLet's break down the key points:
\n- \n
- WebSocketServer — creates the server. \n
- connection — event when a new client connects. \n
- message — receive data from the client. \n
- send — send data back. \n
Run the server with the command npx ts-node server.ts. It will listen on port 8080.
Client Side: Connecting to WebSocket
\nNow let's create client.ts. This will be a simple script that connects to the server and sends messages.