What is WebSocket, and How to Implement WebSocket in NodeJS (Part 3 of 3)

What is WebSocket, and How to Implement WebSocket in NodeJS (Part 3 of 3)

What is WebSocket, and How to Implement WebSocket in NodeJS (Part 3 of 3)
6 min read

Introduction: Bringing WebSocket to the Next Level

In the previous parts, we learned the basics of WebSocket and how to build a two-way communication system. In Part 3, we’ll explore advanced topics, including:

  1. Adding user authentication.

  2. Integrating WebSocket with ExpressJS.

  3. Optimizing performance and security.

This final part will help you build a WebSocket system that’s ready for production.


1. Integrating WebSocket with ExpressJS

In real-world applications, we often use ExpressJS for handling regular HTTP routes. Thankfully, WebSocket can be integrated easily into Express.

Code Example:

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

app.get("/", (req, res) => {
  res.send("WebSocket App with Express");
});

wss.on("connection", (ws) => {
  console.log("Client connected via WebSocket");
  ws.on("message", (message) => {
    console.log("Received:", message);
    ws.send("Message received by Express WebSocket server");
  });
});

server.listen(3000, () => {
  console.log("Server running at http://localhost:3000");
});

Now your WebSocket can run alongside Express, serving both HTTP APIs and real-time communication.


2. Adding Authentication

For security, only authorized users should be able to connect to your WebSocket server. You can use JWT (JSON Web Token) for that.

Example:

const jwt = require("jsonwebtoken");

wss.on("connection", (ws, req) => {
  const token = req.url.split("token=")[1];
  try {
    const user = jwt.verify(token, "secret");
    ws.user = user;
    console.log("Authenticated user:", user.username);
  } catch (err) {
    ws.close();
    console.log("Authentication failed");
  }
});

This ensures only users with valid tokens remain connected.


3. Performance and Security Optimization

To handle more connections efficiently, follow these best practices:

a. Enable Message Compression

const wss = new WebSocket.Server({ server, perMessageDeflate: true });

b. Implement Heartbeat (Ping-Pong)

This keeps your connections alive and removes dead ones:

setInterval(() => {
  wss.clients.forEach((ws) => {
    if (ws.isAlive === false) return ws.terminate();
    ws.isAlive = false;
    ws.ping();
  });
}, 30000);

c. Use HTTPS and WSS

Always use secure connections with SSL to protect data from being intercepted.


4. Scaling with Redis Pub/Sub

For large-scale systems, multiple WebSocket servers can communicate using Redis Pub/Sub.

const redis = require("redis");
const publisher = redis.createClient();
const subscriber = redis.createClient();

subscriber.on("message", (channel, message) => {
  wss.clients.forEach((ws) => {
    if (ws.readyState === WebSocket.OPEN) ws.send(message);
  });
});

subscriber.subscribe("chat");

Now all servers stay in sync through Redis channels.


Final Conclusion

Across these three parts, you’ve learned:

  1. The core concept of WebSocket.

  2. Building two-way and multi-client communication.

  3. Adding security, Express integration, and optimization.

You’re now equipped to create real-time web applications such as chat platforms, live dashboards, or notification systems — powered by NodeJS and WebSocket.

Recommended for you