Developing a Chat Application with TypeScript


Introduction

Chat applications are a common use case for real-time web development. In this guide, we'll walk you through the process of developing a simple chat application using TypeScript and the WebSocket protocol. This will allow you to create a basic real-time chat experience between clients in a web browser.


Prerequisites

Before you begin, make sure you have the following prerequisites:

  • Node.js: You can download it from https://nodejs.org/
  • TypeScript: Install it globally with npm install -g typescript

Getting Started

Let's start by setting up the project and creating a basic chat server and client using TypeScript.


Step 1: Set Up Your Project

Create a new directory for your project and navigate to it in your terminal:

mkdir chat-app
cd chat-app

Step 2: Initialize a Node.js Project

Initialize a Node.js project and answer the prompts. You can use the default settings for most prompts:

npm init

Step 3: Install Dependencies

Install the required dependencies, including TypeScript, WebSocket, and Express:

npm install typescript express express-ws --save

Step 4: Create TypeScript Configuration

Create a TypeScript configuration file (tsconfig.json) in your project directory:

{
"compilerOptions": {
"target": "ES6",
"outDir": "./dist",
"rootDir": "./src"
}
}

Step 5: Create the Chat Server

Create a TypeScript file (server.ts) for your chat server:

// src/server.ts
import express from 'express';
import expressWs from 'express-ws';
import { Server } from 'ws';
const app = express();
expressWs(app);
const wss = new Server({ noServer: true });
wss.on('connection', (ws) => {
ws.on('message', (message) => {
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === Server.OPEN) {
client.send(message);
}
});
});
});
app.ws('/chat', (ws, req) => {
ws.on('message', (message) => {
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === Server.OPEN) {
client.send(message);
}
});
});
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

Step 6: Create the Chat Client

Create an HTML file (index.html) for your chat client:

<!-- public/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Chat Application</title>
</head>
<body>
<h1>Chat</h1>
<input type="text" id="message" placeholder="Type a message..." />
<button onclick="sendMessage()">Send</button>
<ul id="chat"></ul>
<script>
const chatSocket = new WebSocket('ws://localhost:3000/chat');
chatSocket.onmessage = (event) => {
const messageList = document.getElementById('chat');
const messageItem = document.createElement('li');
messageItem.innerText = event.data;
messageList.appendChild(messageItem);
};
function sendMessage() {
const messageInput = document.getElementById('message');
chatSocket.send(messageInput.value);
messageInput.value = '';
}
</script>
</body>
</html>

Step 7: Compile and Run Your TypeScript Code

Compile your TypeScript code using the TypeScript compiler:

tsc

Step 8: Start the Server

Start the server by running:

node ./dist/server.js

Step 9: Open the Chat Application

Open a web browser and navigate to http://localhost:3000 to access the chat application. You can open multiple tabs or browsers to test real-time chat functionality.


Conclusion

Developing a chat application with TypeScript and WebSocket is a great way to learn about real-time communication and enhance your web development skills. This simple chat application serves as a foundation for building more complex and feature-rich chat systems. You can further improve the application by adding user authentication, message persistence, and other features.