Building a Real-Time Chat Application with WebSocket and Node.js

Learn how to create a simple real-time chat application using WebSocket and Node.js, perfect for beginners getting started with real-time web development.

Real-time communication is an essential feature in many modern applications, especially chat apps. This tutorial will guide you through building a basic real-time chat application using WebSocket and Node.js. WebSockets allow for a full-duplex communication channel between the client and server, making it perfect for chat applications.

To get started, ensure you have Node.js installed on your computer. We'll use the popular WebSocket library called `ws` for handling WebSockets in our Node.js server.

First, create a new folder for your project and open a terminal in that directory. Initialize a new Node.js project by running:

javascript
npm init -y

Next, install the WebSocket package:

javascript
npm install ws

Now, create a file named `server.js`. This will be the WebSocket server that handles client connections and broadcasts messages.

javascript
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  console.log('A new client connected!');

  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
    // Broadcast the message to all clients
    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });

  ws.send('Welcome to the chat!');
});

console.log('WebSocket server is running on ws://localhost:8080');

This server listens for new connections and then broadcasts any incoming messages to all connected clients except the sender.

Next, let’s create a simple HTML client to connect to this WebSocket server. Create an `index.html` file with the following content:

javascript
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>WebSocket Chat</title>
  <style>
    #messages { list-style-type: none; margin: 0; padding: 0; }
    #messages li { padding: 8px; background: #f4f4f4; margin-bottom: 5px; border-radius: 4px; }
  </style>
</head>
<body>
  <ul id="messages"></ul>
  <input id="messageInput" autocomplete="off" placeholder="Type a message..." />
  <button id="sendBtn">Send</button>

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

    ws.onopen = () => {
      console.log('Connected to server');
    };

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

    sendBtn.onclick = () => {
      if(input.value) {
        ws.send(input.value);
        input.value = '';
      }
    };

    input.addEventListener('keypress', function (e) {
      if (e.key === 'Enter') {
        sendBtn.click();
      }
    });
  </script>
</body>
</html>

This client connects to the server, listens for messages, and displays them in a list. Users can type a message and send it by clicking the send button or pressing Enter.

To run your chat application, first start the WebSocket server by running:

javascript
node server.js

Then, open the `index.html` file in a browser (you can simply open it by double-clicking, or ideally serve it using a local web server for better cross-browser compatibility). Open multiple tabs or browsers to test real-time messaging between clients.

You now have a basic real-time chat application! This project can be extended by adding user names, styling, and persistent storage for messages. WebSockets with Node.js provide a powerful way to build live interactive web apps.