Learn how to build a real-time chat app using WebSockets. Step-by-step guide for web developers with code examples and best practices.
Table of content
Real-time web applications have become essential in modern web development. Chat applications are at the forefront of this demand for instant communication. This guide will walk you through building a real-time chat app using WebSockets, a protocol that allows for full-duplex, persistent communication between the client and server without refreshing the page.
WebSockets offer a way for your application to send and receive messages instantly. Unlike HTTP, which requires new connections for every request and response, WebSockets establish a single connection that stays open for real-time data transfer.
mkdir realtime-chat-app
cd realtime-chat-app
npm init -y
npm install express ws
We’ll use express
for serving static files and ws
as the WebSocket server.
// server.js
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', ws => {
ws.on('message', message => {
// Broadcast received message
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
ws.send('Welcome to the chat!');
});
app.use(express.static('public'));
server.listen(3000, () => {
console.log('Server started on http://localhost:3000');
});
Create a public
folder and add an index.html
file:
<!DOCTYPE html>
<html>
<head>
<title>Real-Time Chat App</title>
</head>
<body>
<h1>Chat Room</h1>
<ul id="messages"></ul>
<input id="message-input" autocomplete="off" />
<button id="send-btn">Send</button>
<script>
const ws = new WebSocket('ws://' + location.host);
const messages = document.getElementById('messages');
const input = document.getElementById('message-input');
const button = document.getElementById('send-btn');
ws.onmessage = event => {
const li = document.createElement('li');
li.textContent = event.data;
messages.appendChild(li);
};
button.onclick = () => {
if (input.value) {
ws.send(input.value);
input.value = '';
}
};
input.addEventListener('keyup', e => {
if (e.key === 'Enter') button.click();
});
</script>
</body>
</html>
Building a real-time chat app with WebSockets is a fantastic way to understand modern web development techniques. With this foundation, you can expand your app with more complex features as you grow your skills.