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:




  
  WebSocket Chat
  


  

Real-Time Chat

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