Building a Real-Time Chat Application with WebSockets in JavaScript

Learn how to create a simple real-time chat app using WebSockets in JavaScript, perfect for beginners interested in live communication features.

Real-time chat applications have become a staple in modern web development. In this tutorial, we will build a basic chat app using WebSockets in JavaScript. WebSockets provide a full-duplex communication channel over a single TCP connection, allowing the server and client to send messages instantly. This makes them perfect for real-time apps like chat.

To keep things simple, we will create a Node.js server to handle WebSocket connections and a basic HTML/JavaScript frontend. By the end, you'll understand how to set up WebSocket servers and clients for live message exchange.

Step 1: Set up Node.js and Install Dependencies

First, ensure you have Node.js installed on your computer. If not, download and install it from https://nodejs.org. Next, create a new folder for your project and initialize it with npm by running `npm init -y` in the terminal.

We will use the popular `ws` package for WebSocket support on the server side. Install it with:

javascript
npm install ws

Step 2: Create the WebSocket Server

Create a file called `server.js` and add the following code. This sets up a WebSocket server that listens on port 8080 and broadcasts messages to all connected clients.

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

Step 3: Create the Frontend

Next, create an `index.html` file. This simple webpage connects to the WebSocket server and allows users to send and receive messages.

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>
    body { font-family: Arial, sans-serif; margin: 20px; }
    #messages { height: 300px; border: 1px solid #ccc; padding: 10px; overflow-y: scroll; }
    #input { width: 80%; }
    #send { width: 18%; }
  </style>
</head>
<body>
  <h1>Real-Time Chat</h1>
  <div id="messages"></div>
  <input id="input" type="text" placeholder="Type a message..." />
  <button id="send">Send</button>

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

    // Display incoming messages
    ws.onmessage = (event) => {
      const messageElem = document.createElement('div');
      messageElem.textContent = event.data;
      messages.appendChild(messageElem);
      messages.scrollTop = messages.scrollHeight;
    };

    // Send message when button is clicked
    sendBtn.addEventListener('click', () => {
      if(input.value) {
        ws.send(input.value);
        input.value = '';
      }
    });

    // Also send message on Enter key
    input.addEventListener('keyup', (event) => {
      if(event.key === 'Enter' && input.value) {
        ws.send(input.value);
        input.value = '';
      }
    });
  </script>
</body>
</html>

Step 4: Run the Application

Start your WebSocket server by running the command below in your project folder:

javascript
node server.js

Then, open the `index.html` file in your browser. You should see a simple chat interface. Open the file in multiple browser windows or tabs and try sending messages — they will appear in real-time across all open clients.

Congratulations! You have successfully built a basic real-time chat application using WebSockets in JavaScript. From here, you can expand this by adding user authentication, storing chat history, or improving the UI.