blog bg

August 18, 2025

How to Build a Real-Time Chat Application with WebSockets

Share what you learn in this blog to prepare for your interview, create your forever-free profile now, and explore how to monetize your valuable knowledge.

How to Build a Real-Time Chat Application with WebSockets

 

Today, real-time communication is an important part of all web apps, from messaging apps to live dashboards to tools for working together. With WebSockets, which let a client and server communicate two-way over time, this is one of the best ways to do it. This guide will teach you how to use WebSockets, Node.js, and normal JavaScript to make a simple real-time chat app.

 

Tools and Technologies Used

To keep things simple and minimal, we'll use:

  • Node.js: for the backend runtime
  • Express.js: to serve static files
  • ws: a WebSocket library for Node.js
  • HTML + JavaScript: for the frontend

 

Step 1: Setting Up the Project

Create a project directory and initialize a Node.js project to begin:

mkdir websocket-chat-app
cd websocket-chat-app
npm init -y
npm install express ws

 

Now set up your project structure like this:

/websocket-chat-app
  |-- server.js
  |-- public/
       |-- index.html
       |-- script.js

 

This structure keeps your backend (server.js) files separate from the frontend files in the public folder.

 

Step 2: Creating the WebSocket Server

In server.js, we will use Express to make a simple server and the ws library to add WebSocket support:

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 });

// Serve static files from "public"
app.use(express.static('public'));

// Handle WebSocket connections
wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    // Broadcast message to all clients
   wss.clients.forEach(client => {
      if (client.readyState === WebSocket.OPEN) {
       client.send(message);
      }
    });
  });
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

 

This set-up makes it possible for all connected clients to see every message that broadcasted from a client, which is great for a group chat. 

 

Step 3: Building the Frontend 

Let's use HTML and JavaScript to make a simple chat system.

index.html
<!DOCTYPE html>
<html>
<head>
 <title>WebSocket Chat</title>
  <style>
    body { font-family: Arial; }
    #messages { border: 1px solid #ccc; height: 200px; overflow-y: scroll; margin-bottom: 10px; padding: 5px; }
  </style>
</head>
<body>
  <h2>Real-Time Chat</h2>
  <div id="messages"></div>
  <input type="text" id="input" placeholder="Type your message..." />
  <button onclick="sendMessage()">Send</button>

  <script src="script.js"></script>
</body>
</html>

script.js

const socket = new WebSocket('ws://localhost:3000');

socket.onmessage = function(event) {
  const messages = document.getElementById('messages');
  const msg = document.createElement('div');
  msg.textContent = event.data;
 messages.appendChild(msg);
};

function sendMessage() {
  const input = document.getElementById('input');
  if (input.value.trim() !== '') {
   socket.send(input.value);
    input.value = '';
  }
}

 

This script makes a connection to the WebSocket server, waits for messages to receive, and shows them on the screen. It also communicates to the server when you press the "Send" button.

 

Step 4: Run and Test

  1. Initialize your server: node server.js
  2. Open your browser and go to: http://localhost:3000
  3. Use different browsers or tabs to open the same URL and test the chat in real time. Messages sent from one window will show up instantly in other windows.

 

What You Can Add Next

This is a simple chat, but here are some ways to make it scalable:

  • Usernames: This is how people can identify themselves.
  • Message timestamps: Shows the time when messages were sent.
  • Chat rooms: Users can join various groups.
  • Database support: Use MongoDB or Firebase to save your message history.
  • UI Enhancement (UI): You can further add avatars, colours, notifications, or typing indicators.

 

Conclusion

Using WebSockets, you just made a simple real-time chat app that's functional. This app is a great place to start for more advanced real-time features like online games with multi-player features, collaborative editors, and customer support system.

WebSockets offer a continuous connection with low latency, making them ideal for situations where speed and engagement are important. Once you feel more comfortable, you could add frameworks like React, use Socket.IO to add extra features, or put your app online with Heroku or Vercel.

111 views

Please Login to create a Question