Real-Time Communication with WebSockets in Node.js: Testing with Postman

Ayowande Oluwatosin - Feb 24 - - Dev Community

Introduction

WebSockets enable real-time, bidirectional communication between a client and a server. Unlike traditional HTTP requests, WebSockets maintain an open connection, allowing instant data exchange. In this article, we'll explore how to set up WebSockets in a Node.js application, integrate them with a blogging system, and test using Postman.

Setting Up WebSockets in Node.js

To integrate WebSockets, we will use Socket.io, a popular WebSocket library for Node.js. Our implementation includes a centralized socket.js file for managing WebSocket connections.

Install Dependencies

Ensure you have Socket.io installed:

npm install socket.io

WebSocket Initialization (socket.js)

We'll create a socket.js file to manage WebSocket connections:

let io;

module.exports = {
    init: httpServer => {
        io = require('socket.io')(httpServer);
        return io;
    },
    getIo: () => {
        if (!io) {
            throw new Error("Socket.io not initialized");
        }
        return io;
    }
};
Enter fullscreen mode Exit fullscreen mode

This module exports two functions:

  1. init: Initializes WebSocket on the HTTP server.
  2. getIo: Retrieves the active WebSocket instance.

Integrating WebSockets in app.js

Modify your app.js to initialize WebSockets:

const express = require('express');
const http = require('http');
const { init } = require('./socket');

const app = express();
const server = http.createServer(app);
const io = init(server);

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

    socket.on('message', (data) => {
        console.log('Received message:', data);
        socket.emit('response', { message: `Message received: ${data}` });
    });

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

server.listen(4000, () => {
    console.log('Server running on port 4000');
});
Enter fullscreen mode Exit fullscreen mode

Implementing WebSockets in a Blog Post System

Let's create a blog post system where new posts trigger real-time notifications via WebSockets.

Blog Post Controller (controllers/postController.js)

const { getIo } = require('../socket');
const { User } = require('../models');

exports.createPost = async (req, res) => {
    try {
        const user = await User.findByPk(req.userId);
        const { title, content } = req.body;
        const image = req.file;

        if (!image) {
            throw new Error('Image file is required!');
        }

        const imageUrl = image.path;
        const post = await user.createPost({ title, content, imageUrl });

        getIo().emit('posts', { action: 'createdPost', post });

        return res.status(201).json({ message: 'Post created successfully!', post });
    } catch (error) {
        return res.status(500).json({ message: error.message || 'Something went wrong.' });
    }
};
Enter fullscreen mode Exit fullscreen mode

Testing WebSockets with Postman

Postman now supports WebSocket testing. Follow these steps:

Step 1: Open a WebSocket Connection

  1. Open Postman.
  2. Click "New" → "WebSocket Request".
  3. Enter WebSocket URL: ws://localhost:4000.
  4. Click Connect.

Step 2: Send a Message

  1. Go to the Messages tab.
  2. Send a test JSON message:
{
   "type": "chat",
   "message": "Hello WebSocket!"
}
Enter fullscreen mode Exit fullscreen mode
  1. Click Send.

Step 3: Listen for Incoming Messages

If the WebSocket server is set up correctly, you should receive a response:

{
   "message": "Message received: Hello WebSocket!"
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Testing Blog Post Notifications

Create a blog post via a REST API request (e.g., POST /api/posts).

If successful, Postman (connected to WebSockets) should receive an event:

{
   "action": "createdPost",
   "post": { "title": "New Post", "content": "This is a new post" }
}
Enter fullscreen mode Exit fullscreen mode

This confirms that real-time notifications work correctly.

Conclusion

By integrating WebSockets into a Node.js blog system, we enable real-time updates when new posts are created. Testing WebSockets with Postman ensures everything works as expected.

. . . . . . . . . . . . . .