WebSocket with Node.js: Syntax, Examples, and Real-Life Applications

Introduction

Modern web applications often need to exchange data between the client and server in real time. For example, a chat application must display new messages immediately, while a live dashboard needs to update information without requiring users to refresh the page.

Traditional HTTP requests are useful for normal communication, but they are not always the best choice for applications that require continuous updates. WebSocket provides a solution by allowing the client and server to maintain a persistent, two-way communication connection.

Node.js supports WebSocket-based applications through libraries such as ws. Developers can use this library to build chat applications, live notifications, multiplayer games, and real-time monitoring systems.

In this tutorial, you will learn what WebSocket is, how to use it with Node.js, its syntax, practical examples, common mistakes, and important interview questions.

What is WebSocket with Node.js?

WebSocket is a communication protocol that allows a client and server to exchange data in both directions over a single, long-lived connection.

Unlike traditional HTTP communication, where the client usually sends a request before receiving a response, WebSocket allows either side to send messages whenever necessary after the connection is established.

Node.js can create WebSocket servers using libraries such as ws. A browser can connect to the server using its built-in WebSocket API.

Key Features of WebSocket

  • Full-duplex communication: The client and server can send messages independently.
  • Persistent connection: The connection remains open until one side closes it or a network problem interrupts it.
  • Low communication overhead: After the initial handshake, messages do not require a new HTTP request each time.
  • Real-time updates: Data can be delivered immediately when an event occurs.
  • Wide range of applications: WebSocket is useful for chat systems, notifications, live dashboards, and online games.

WebSocket vs HTTP

Feature HTTP WebSocket
Communication Request-response Two-way communication
process.version Returns the Node.js version. Persistent connection
Server updates Often requires polling or another mechanism Server can push updates
Best suited for APIs and normal web requests Real-time applications

Syntax

To use WebSocket in Node.js, you can install the ws package from npm.

Step 1: Install the WebSocket Package

Create a new Node.js project and install the package:


mkdir websocket-demo
cd websocket-demo
npm init -y
npm install ws

The ws package provides the tools required to create a WebSocket server and connect Node.js clients.

Step 2: Create a WebSocket Server

The basic syntax for creating a WebSocket server is:


const WebSocket = require('ws');

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

server.on('connection', (socket) => {
    console.log('Client connected');

    socket.on('message', (message) => {
        console.log(message.toString());
    });

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

Explanation:

  • require(‘ws’) imports the WebSocket library.
  • new WebSocket.Server() creates a server listening on port 8080.
  • The connection event runs when a client connects.
  • The message event handles incoming messages.
  • The close event runs when the connection closes.

The socket.send() method sends data to a connected client. You can also use server.clients to access connected clients when broadcasting messages.

Example: Create a WebSocket Server in Node.js

Let’s create a simple WebSocket server that receives a message from a client and sends a response.

Create a file named server.js:


const WebSocket = require('ws');
const server = new WebSocket.Server({
    port: 8080
});
server.on('connection', (socket) => {
    console.log('Client connected');

    socket.send('Welcome to the WebSocket server!');
    socket.on('message', (message) => {
        const text = message.toString();
        console.log('Received:', text);
        socket.send(`Server received: ${text}`);
    });
    socket.on('close', () => {
        console.log('Client disconnected');
    });
    socket.on('error', (error) => {
        console.error('WebSocket error:', error.message);
    });
});
console.log('WebSocket server running on port 8080');

Run the Server

Execute the following command in your terminal:


node server.js

The server will start listening on port 8080.

Connect Using a Browser

Create an index.html file:


<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Demo</title>
</head>
<body>
    <h2>WebSocket with Node.js</h2>

    <input id="message" placeholder="Enter a message">
    <button onclick="sendMessage()">Send</button>

    <p id="output"></p>

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

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

        socket.onmessage = (event) => {
            document.getElementById('output').textContent =
                event.data;
        };

        function sendMessage() {
            if (socket.readyState === WebSocket.OPEN) {
                socket.send(
                    document.getElementById('message').value
                );
            }
        }
    </script>
</body>
</html>

Open the HTML file in a browser while the Node.js server is running.

When the connection opens, the server sends a welcome message. Enter text and click Send to receive a response from the server.

For production applications, serve the page over HTTP or HTTPS and use the appropriate WebSocket URL.

Real-Life Example: Broadcasting Chat Messages

Consider a team chat application where multiple users need to receive new messages immediately. When one user sends a message, the server can broadcast it to all connected clients.

Add the following message-handling logic to a WebSocket server:


const WebSocket = require('ws');

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

server.on('connection', (socket) => {
    socket.on('message', (message) => {
        const text = message.toString();

        server.clients.forEach((client) => {
            if (client.readyState === WebSocket.OPEN) {
                client.send(text);
            }
        });
    });
});
console.log('Chat server running on port 8080');

How it works:

  1. A user connects to the WebSocket server.
  2. The user sends a chat message.
  3. The server receives the message through the message event.
  4. The server checks which connected clients are ready.
  5. The message is sent to every connected client.

This example demonstrates message broadcasting, but it is not a complete production-ready chat application. A real system should identify users, validate messages, enforce message-size limits, and apply authentication and authorization.

WebSocket broadcasting is also useful for live stock prices, delivery tracking, collaborative editing, and real-time analytics dashboards.

Common Mistakes When Using WebSocket with Node.js

Developers may encounter several problems when building WebSocket applications.

1. Forgetting to install the package

Using require(‘ws’) without installing the library causes a module-not-found error. Install it with npm install ws.

2. Sending messages before the connection opens

Calling socket.send() before the connection is ready can cause an error. Check socket.readyState === WebSocket.OPEN before sending.

3. Ignoring connection errors

Network failures and unexpected disconnections can interrupt communication. Add error handlers and implement reconnection logic when the application requires it.

4. Broadcasting to closed connections

A client may disconnect while the server is broadcasting a message. Check that client.readyState is WebSocket.OPEN before sending.

5. Ignoring security

Never trust messages received from clients. Validate input, authenticate users, authorize access, and limit message sizes. Use wss:// with TLS in production.

6. Creating a new connection for every message

Repeatedly opening and closing connections defeats the purpose of WebSocket. Reuse an established connection for ongoing communication.

Conclusion

WebSocket is an effective solution for building real-time applications with Node.js. It allows clients and servers to exchange messages over a persistent, two-way connection without repeatedly creating new HTTP requests.

Using the ws package, developers can create WebSocket servers, handle incoming messages, send responses, and broadcast updates to multiple clients. These capabilities make WebSocket suitable for chat applications, live notifications, online games, and monitoring dashboards.

When implementing WebSocket in production, remember to handle errors, validate incoming data, secure connections, and manage disconnected clients properly. Understanding these concepts will help you develop responsive and reliable real-time applications with Node.js.

WebSocket with Node.js – Interview Questions

Q 1: What is WebSocket?
Ans: WebSocket is a protocol that enables two-way communication between a client and server over a persistent connection.
Q 2: How is WebSocket different from HTTP?
Ans: HTTP commonly follows a request-response pattern, while WebSocket allows both the client and server to send messages independently over an established connection.
Q 3: Which Node.js package can be used to create a WebSocket server?
Ans: The ws package is a popular option for implementing WebSocket communication in Node.js.
Q 4: What is the purpose of the connection event?
Ans: The connection event runs when a client successfully establishes a WebSocket connection with the server.
Q 5: What is the difference between send() and the message event?
Ans: The send() method transmits data through a WebSocket connection. The message event handles data received from the other side.

Related Node.js Tutorials