Building a Simple Chat Server with Node.js and WebSocket

Want to build a real-time chat app from scratch without relying on third-party services? With Node.js and WebSocket, you can create a lightweight chat server that delivers messages instantly between users.

In this post, you’ll learn how to build a simple chat server using Node.js and the ws WebSocket package โ€” step by step.

๐Ÿš€ Why Use WebSocket for Chat?

HTTP is request/response-based โ€” not ideal for real-time messaging. WebSockets create a persistent, two-way connection between client and server, perfect for:

  • Chat apps
  • Live notifications
  • Real-time dashboards
  • Multiplayer games

๐Ÿ”ง Step 1: Initialize a Node.js Project

Create a new directory and initialize a Node.js app:

mkdir websocket-chat
cd websocket-chat
npm init -y

Install the ws package:

npm install ws

The ws package is a simple and efficient WebSocket library for Node.js. See more on the official npm page.

๐Ÿ“ Step 2: Create the Chat Server

Create a file named server.js:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });
console.log('WebSocket server started on ws://localhost:8080');

wss.on('connection', (ws) => {
  console.log('New client connected.');

  ws.on('message', (message) => {
    console.log(`Received: ${message}`);

    // Broadcast to all connected clients
    wss.clients.forEach((client) => {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });

  ws.on('close', () => {
    console.log('Client disconnected.');
  });
});

This server listens on port 8080, accepts connections, and broadcasts any received message to all other connected clients.

๐Ÿงช Step 3: Create a Simple HTML Client

Create a file named client.html:

<!DOCTYPE html>
<html>
<head><title>WebSocket Chat</title></head>
<body>
  <h2>WebSocket Chat</h2>
  <input id="msg" placeholder="Type a message..." />
  <button onclick="sendMessage()">Send</button>
  <ul id="messages"></ul>

  <script>
    const socket = new WebSocket('ws://localhost:8080');
    const messages = document.getElementById('messages');

    socket.onmessage = (event) => {
      const li = document.createElement('li');
      li.textContent = event.data;
      messages.appendChild(li);
    };

    function sendMessage() {
      const input = document.getElementById('msg');
      socket.send(input.value);
      input.value = '';
    }
  </script>
</body>
</html>

Open this file in two tabs or different browsers to simulate multiple users.

You can learn more about the WebSocket API in the official MDN documentation.

โœ… Final Thoughts

You’ve now built a fully functional real-time chat server using Node.js and WebSocket โ€” no external services, just code and sockets.

This is the foundation for more advanced features like:

  • User authentication
  • Message persistence (MongoDB, PostgreSQL, etc.)
  • Private rooms or channels
  • WebSocket with frontend frameworks (React, Vue, etc.)

WebSocket is a powerful tool for building real-time apps โ€” and Node.js makes it fast and easy to get started.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top