Build a Real-Time Chat App with WebSockets

Learn how to build a real-time chat app using WebSockets. Step-by-step guide for web developers with code examples and best practices.


Back to Home

Table of content

Introduction

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.

What Are WebSockets?

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.

  • Low latency two-way communication
  • Less overhead compared to polling
  • Ideal for chat apps, games, and live notifications

Setting Up the Project

Prerequisites

  • Node.js and npm installed
  • Basic JavaScript and HTML knowledge

Initialize your project

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

Creating the WebSocket Server

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

Building the Frontend

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>

How It Works

  • When a user connects, the server sends a welcome message.
  • Each message sent by a client is broadcast to all connected clients.
  • The frontend listens for messages and displays them in real time.

Additional Features & Best Practices

Suggestions for Enhancement:

  • Add usernames for users
  • Show when someone is typing
  • Persist messages with a database
  • Implement authentication and authorization
  • Secure WebSocket connections with WSS (for production)

Conclusion

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.

Explore Further

chat app
JavaScript
Node.js
real-time
Tutorial
Web Development
WebSockets