How to monitor and debug JavaScript WebSocket connections in real-time?

Content verified by Anycode AI
July 21, 2024
Whereas WebSocket connections provide real-time, bidirectional communication between clients and servers, they can be pretty hard to debug because, unlike traditional HTTP requests, which don't persist, a WebSocket connection may stay open, and their different issues need to be diagnosed and fixed. This requires a systematic way of monitoring and debugging. The following guide should help demystify WebSocket debugging by providing a fully workable strategy for client-side logging and identifying server-side logging at the network level, with performance profiling also covered. Armed with these techniques, developers will be very well-placed to get into the guts of WebSocket connections, locate problems in them much more rapidly, and guarantee both robustness and efficiency within the real-time communication that applications support.

Keeping tabs on and troubleshooting JavaScript WebSocket connections on-the-fly is super crucial when you're building interactive web applications that chat back in real time. Let's walk through how to do this step-by-step with some practical tricks and examples to guide you along.

Checking Out WebSocket Connections in the Browser Console

Chrome and Firefox both come equipped with handy tools for peeking into WebSocket connections.

Chrome

Pop Open the Developer Tools:

  • Right-click anywhere on your webpage and select "Inspect" or hit Ctrl+Shift+I (Windows/Linux) or Cmd+Option+I (Mac).

Finding the WebSocket Interface:

  • Head over to the "Network" tab.
  • Filter by "WS" to narrow it down to just WebSocket connections.
  • Click on a WebSocket connection to check out the frames.

Looking at WebSocket Frames:

  • Under the "Frames" sub-tab, you'll see data flying back and forth.
  • Stuff your client sends is labeled as "send" and stuff from the server shows up as "receive".

Digging into Individual Messages:

  • Click any frame to see the nitty-gritty details.
  • WebSocket data can be JSON, plain text, or binary.

Firefox

Open Developer Tools:

  • Right-click your webpage and choose "Inspect Element" or press Ctrl+Shift+I (Windows/Linux) or Cmd+Option+I (Mac).

Navigating WebSocket Interface:

  • Jump to the "Network" tab.
  • Filter by "WS" to list the WebSocket connections.
  • Click a WebSocket connection to get more detailed views.

Analyzing Frames:

  • The "Messages" sub-tab is where frames are detailed.
  • Frames are color-coded, making them easier to distinguish.

Logging Manually in Your JavaScript Code

Add a bit of logging to your WebSocket code to track connection status, outgoing messages, and incoming messages.

const socket = new WebSocket('wss://example.com/socket');

// Log when connection opens or closes
socket.addEventListener('open', function (event) {
    console.log('WebSocket connection opened:', event);
});

socket.addEventListener('close', function (event) {
    console.log('WebSocket connection closed:', event);
});

// Log incoming messages
socket.addEventListener('message', function (event) {
    console.log('Message received from server:', event.data);
});

// Log sent messages
function sendMessage(message) {
    console.log('Sending message to server:', message);
    socket.send(message);
}

// Example: send a message
sendMessage(JSON.stringify({ type: 'ping', content: 'Hello, server!' }));

Using Middleware for Advanced Logging

When you need more advanced logging, consider a middleware-esque approach to intercept and log messages.

Create a WebSocket wrapper function:

function createWebSocket(url) {
    const ws = new WebSocket(url);

    ws.addEventListener('message', function(event) {
        logMessage('received', event.data);
    });

    const originalSend = ws.send;
    ws.send = function(data) {
        logMessage('sent', data);
        originalSend.apply(ws, arguments);
    };

    function logMessage(type, message) {
        console.log(`WebSocket ${type}:`, message);

        // Add more logic here if you want
    }

    return ws;
}

// Use your new wrapper function
const socket = createWebSocket('wss://example.com/socket');

// Example: send a message
socket.send(JSON.stringify({ type: 'ping', content: 'Hello, server!' }));

Using External Libraries and Tools

WebSocket Debugger Tool

Try out some external tools like Proxy WebSocket Debugger, which can serve as an intermediary between your WebSocket server and client, letting you inspect and monitor messages easily.

Third-Party Libraries

Libraries like socket.io can simplify and enrich your debugging experience.

const socket = io('https://example.com', {
    transports: ['websocket']
});

socket.on('connect', () => {
    console.log('Socket.io connection established');
});

socket.on('message', (data) => {
    console.log('Received:', data);
});

function sendMessage(message) {
    console.log('Sending message:', message);
    socket.send(message);
}

// Example: send a message
sendMessage('Hello Server!');

And to enable more detailed logging:

localStorage.debug = 'socket.io-client:socket';
const socket = io('https://example.com', {
    transports: ['websocket']
});

Network Sniffing and Protocol Analysis

For more in-depth analysis, tools like Wireshark let you capture and sniff WebSocket traffic, providing a deep dive into the communication.

Capture traffic:

  • On the needed interface.

Filter WebSocket frames:

  • Use the websocket display filter in Wireshark.

Analyze frames:

  • Inspect the payload and decode following the WebSocket protocol.

Happy debugging!

Have any questions?
Our CEO and CTO are happy to
answer them personally.
Get Beta Access
Anubis Watal
CTO at Anycode
Alex Hudym
CEO at Anycode