Building a Real-Time Chat Application with WebSockets: A Step-by-Step Guide
Real-time chat apps require instant, bidirectional communication between clients and a server. Unlike traditional HTTP polling, WebSockets maintain a persistent connection, enabling low-latency messaging. This tutorial walks you through creating a simple, functional chat app using Node.js and the native WebSocket API.
We’ll build a two-part system: a server that handles connections and message broadcasting, and a client that connects and displays messages. You’ll need Node.js installed and a basic understanding of JavaScript and HTML.
1. Setting Up the WebSocket Server
Initialize a Node.js project and install the ws library:
npm init -ynpm install ws
Create a file server.js. Use the WebSocket server to listen for connections. On each connection, listen for messages and broadcast them to all connected clients:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
ws.on('message', (data) => {
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(data.toString());
}
});
});
});
2. Building the Chat Client
Create index.html with a simple UI: an input field and a messages list. Include a <script> that connects to ws://localhost:8080. On form submit, send the message; when receiving messages, append them to the list:
const ws = new WebSocket('ws://localhost:8080');
ws.onmessage = (event) => {
const msg = document.createElement('li');
msg.textContent = event.data;
document.getElementById('messages').appendChild(msg);
};
document.getElementById('chat-form').addEventListener('submit', (e) => {
e.preventDefault();
const input = document.getElementById('msg');
ws.send(input.value);
input.value = '';
});
3. Running and Testing
Start the server with node server.js and open index.html in multiple browser tabs. Send a message from one tab—it should appear in all others instantly. This basic app demonstrates the core WebSocket flow.
For production, add user name tracking, persistence, and error handling. The same pattern scales to group chats, notifications, or live collaboration tools.
Conclusion
You’ve built a real-time chat app using WebSockets. The persistent connection eliminates polling overhead, making message delivery near-instantaneous. Experiment with broadcasting to specific users or adding rooms to extend functionality. WebSockets are the backbone of modern interactive web applications.