WebSockets in TypeScript: Building Real-Time Applications from Scratch

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Why WebSockets Are the Magic of Real-Time?

\n

Imagine 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.

\n

WebSockets 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.

\n

In 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\n

What Are WebSockets and Why Do You Need Them?

\n

WebSocket 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.

\n

Where 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
\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\n

Project Setup: Node.js + TypeScript + WebSocket

\n

Let's start with initialization. Make sure you have Node.js (version 18+) and npm installed.

\n
mkdir websocket-ts-chat\ncd websocket-ts-chat\nnpm init -y\nnpm install ws @types/ws typescript ts-node @types/node\nnpx tsc --init
\n

In tsconfig.json, enable strict mode and specify outDir: "./dist". This is the foundation for any TypeScript project.

\n\n

Writing a WebSocket Server in TypeScript

\n

Create a file server.ts. Here we will start a WebSocket server on port 8080.

\n
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');
\n

Let'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
\n

Run the server with the command npx ts-node server.ts. It will listen on port 8080.

\n\n

Client Side: Connecting to WebSocket

\n

Now let's create client.ts. This will be a simple script that connects to the server and sends messages.

Blogs

Book Recommendations