Building a Real-Time Chat Application with TypeScript and WebSocket

Learn how to build a simple real-time chat application using TypeScript and WebSocket. This beginner-friendly tutorial guides you step-by-step through setting up a server and client for interactive messaging.

Real-time communication is an essential feature of modern web applications, powering chat apps, live notifications, and collaborative tools. In this tutorial, we will build a basic real-time chat application using TypeScript and WebSocket, which allows for two-way communication between the client and the server.

We will start by creating a WebSocket server that can manage multiple clients. Then, we will create a browser-based client to send and receive chat messages. TypeScript will help us write safer and more maintainable code.

### Step 1: Setting Up the WebSocket Server First, let's create a simple WebSocket server using Node.js and the `ws` library. If you don't have the `ws` package installed, you can add it by running `npm install ws`.

typescript
import WebSocket, { WebSocketServer } from 'ws';

const port = 8080;
const wss = new WebSocketServer({ port });

wss.on('connection', (ws: WebSocket) => {
  console.log('New client connected');

  ws.on('message', (data: WebSocket.Data) => {
    // Broadcast the incoming message to all connected clients
    wss.clients.forEach(client => {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(data.toString());
      }
    });
  });

  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

console.log(`WebSocket server is running on ws://localhost:${port}`);

This server listens on port 8080 for WebSocket connections. When a new client connects, it logs the connection. Every incoming message from a client is broadcast to all other connected clients, enabling the chat functionality.

### Step 2: Creating the Client Side Now, let's create a simple client using an HTML page with embedded TypeScript. For ease, we will write the logic in TypeScript and compile it to JavaScript.

typescript
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>TypeScript WebSocket Chat Client</title>
  <style>
    #messages { height: 300px; overflow-y: scroll; border: 1px solid #ccc; padding: 10px; }
    #messageInput { width: 80%; }
  </style>
</head>
<body>
  <div id="messages"></div>
  <input id="messageInput" type="text" placeholder="Type a message..." />
  <button id="sendBtn">Send</button>

  <script src="client.js"></script>
</body>
</html>

Next, here is the TypeScript code for the client (`client.ts`). This script connects to the WebSocket server and handles sending and receiving messages:

typescript
const ws = new WebSocket('ws://localhost:8080');

const messagesDiv = document.getElementById('messages') as HTMLDivElement;
const input = document.getElementById('messageInput') as HTMLInputElement;
const sendBtn = document.getElementById('sendBtn') as HTMLButtonElement;

function appendMessage(message: string, isOwnMessage = false) {
  const msgElm = document.createElement('div');
  msgElm.textContent = message;
  msgElm.style.padding = '5px';
  msgElm.style.marginBottom = '5px';
  msgElm.style.backgroundColor = isOwnMessage ? '#DCF8C6' : '#FFFFFF';
  msgElm.style.textAlign = isOwnMessage ? 'right' : 'left';
  messagesDiv.appendChild(msgElm);
  messagesDiv.scrollTop = messagesDiv.scrollHeight;
}

ws.onopen = () => {
  appendMessage('Connected to the chat server.');
};

ws.onmessage = event => {
  appendMessage(event.data);
};

sendBtn.addEventListener('click', () => {
  if (input.value.trim() !== '') {
    ws.send(input.value.trim());
    appendMessage(input.value.trim(), true);
    input.value = '';
  }
});

input.addEventListener('keypress', event => {
  if (event.key === 'Enter') {
    sendBtn.click();
  }
});

Compile the TypeScript file to JavaScript using `tsc client.ts` and include the generated `client.js` in your HTML file. Then open the HTML file in multiple browser windows to test real-time messaging.

### Summary In this tutorial, we built a simple real-time chat application leveraging TypeScript and WebSocket. The server established a WebSocket connection and broadcasted incoming messages to all clients. The client connected to this server, sending and displaying chat messages dynamically. This foundation can be expanded with features like user names, message timestamps, and persistent storage.

Real-time WebSocket communication allows you to create interactive and engaging apps. With TypeScript's type safety, coding becomes more manageable and less error-prone. Keep experimenting and building more complex real-time apps!