Building a Real-Time Chat App With WebSockets and Node.js
Real-time communication is a key feature in modern web apps. In this guide, we’ll walk through building a simple real-time chat application using WebSockets with Node.js and the ws
library — no frameworks or front-end libraries required.
Step 1: Initialize the Project
Start by setting up a basic Node.js project:
mkdir websocket-chat
cd websocket-chat
npm init -y
npm install ws express
Step 2: Create a WebSocket Server
Create a file server.js
and set up a basic Express and WebSocket server:
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 });
app.use(express.static("public"));
wss.on("connection", (ws) => {
ws.on("message", (message) => {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
Step 3: Add the Client Interface
Create a public/index.html
file with this content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>WebSocket Chat</title>
<style>
body { font-family: sans-serif; padding: 20px; }
#chat { height: 300px; overflow-y: scroll; border: 1px solid #ccc; margin-bottom: 10px; }
</style>
</head>
<body>
<h1>Real-Time Chat</h1>
<div id="chat"></div>
<input id="message" placeholder="Type a message..." />
<button onclick="sendMessage()">Send</button>
<script>
const chat = document.getElementById("chat");
const input = document.getElementById("message");
const ws = new WebSocket("ws://" + location.host);
ws.onmessage = (event) => {
const msg = document.createElement("div");
msg.textContent = event.data;
chat.appendChild(msg);
chat.scrollTop = chat.scrollHeight;
};
function sendMessage() {
ws.send(input.value);
input.value = "";
}
</script>
</body>
</html>
Step 4: Test It Out
Run the server with:
node server.js
Visit http://localhost:3000
in two browser tabs. Messages sent in one will appear instantly in the other.
Conclusion
WebSockets allow for efficient, low-latency, bidirectional communication between clients and servers. This is a great entry point into building more complex real-time applications like multiplayer games, collaborative tools, or live dashboards.
If this post helped you, consider supporting me: buymeacoffee.com/hexshift
Top comments (0)