WebSocket, SSE, and Real-Time Messaging

Build one-way streams and bidirectional connections and release resources on disconnect

🎯 Introduction

By the end of this article, you will be able to build one-way streams and bidirectional connections and release resources on disconnect.

⚖️ Choose by communication direction

Ordinary HTTP suits one result per request. SSE continuously sends text events in one HTTP response, making it suitable for progress or notifications. WebSocket lets either side send messages proactively, making it suitable for chat or collaboration.

Real-time connections can still disconnect when networks change, proxies time out, or services restart. The application must define reconnection and recovery of missed messages.


📡 End each SSE message with a blank line

Create sse.mjs and define event sending:

sse.mjs
function sendEvent(res, event, data) {
    return res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
}

event is the name and data is text; here, the object is serialized as JSON. The final blank line completes the event. Without it, the client may keep waiting.


⏱ Stream updates and clean up connections

Add the complete handler to send the current time every second:

sse.mjs
export function events(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' });
    res.flushHeaders();
    const timer = setInterval(() => {
        if (!sendEvent(res, 'clock', { time: new Date().toISOString() })) res.destroy();
    }, 1000);
    res.once('close', () => clearInterval(timer));
}

Stop the timer when the client disconnects. A false return from write indicates buffered backpressure. This example disconnects slow clients to prevent unlimited accumulation; real applications may pause or drop replaceable updates according to their needs.

Create the startup file:

sse-server.mjs
import express from 'express';
import { events } from './sse.mjs';

const app = express();
app.get('/events', events);
app.listen(3002, '127.0.0.1');

After starting it, inspect output with unbuffered curl:

curl -N http://127.0.0.1:3002/events

A clock event arrives every second. Disconnecting with Ctrl+C clears its server-side timer.


🖥 Receive events with EventSource in the browser

If the events handler is registered at a same-origin /events route, the page can use:

const source = new EventSource('/events');
source.addEventListener('clock', event => {
    console.log(JSON.parse(event.data).time);
});
window.addEventListener('pagehide', () => source.close());

This is browser code, not page code you can run directly in Node.js. Different origins need the earlier CORS configuration. EventSource normally reconnects automatically but cannot recover missed messages by itself. Recovery requires event IDs, server-side storage, and resumption rules.

Native EventSource cannot set a custom Authorization header directly. Authenticated streams need an appropriate cookie approach or another streaming mechanism that supports authentication headers. Do not put long-lived tokens in URLs.


🔄 WebSocket also lets clients send continuously

Install the WebSocket server library:

npm install ws@8.22.0

Create ws-server.mjs with a local server and a per-message size limit:

ws-server.mjs
import { WebSocketServer } from 'ws';

const server = new WebSocketServer({ host: '127.0.0.1', port: 3001, maxPayload: 16 * 1024 });

Add a connection handler:

ws-server.mjs
server.on('connection', socket => {
    socket.on('error', console.error);
    socket.on('message', data => {
        socket.send(`Received: ${data.toString()}`);
    });
});

The message event fires for each incoming message. This local protocol demo only echoes text; it has no authentication or room permissions. Production connections must verify identity and allowed origins before establishment and validate structure and permissions for each message type.


🧪 Complete a bidirectional exchange with a client

After starting the server, create ws-client.mjs using the built-in WebSocket client:

ws-client.mjs
const socket = new WebSocket('ws://127.0.0.1:3001');
socket.addEventListener('open', () => socket.send('hello'));
socket.addEventListener('message', event => {
    console.log(event.data);
    socket.close();
});
socket.addEventListener('error', () => console.error('Connection failed'));

Running it prints “Received: hello” and closes the connection. Production HTTPS pages use encrypted wss://, and reverse proxies must support connection upgrades. WebSocket does not rely on CORS headers for authorization; configuring HTTP CORS does not protect it.


🧹 Handle disconnects and service shutdown too

Limit message size, queued sends, and connections per user. Use protocol heartbeats to detect lost peers and clean them up after a deadline rather than waiting for business messages.

SSE behind a proxy usually needs response buffering disabled; WebSocket needs upgrade requests forwarded correctly. End these connections explicitly on shutdown, or logic waiting for ordinary HTTP requests may never finish.


❓ Questions and Answers

Q1: Is real-time push always better than polling?

No. Periodic queries may suffice for infrequent updates and simple requirements. Persistent connections add management and recovery work.

Q2: Are all messages trusted after WebSocket authentication?

No. Validate message types, sizes, fields, and permissions on target resources too.

Q3: Does reconnection guarantee no message loss?

No. Recovery needs server-side message storage, client position markers, and a catch-up strategy.


🧪 Practice

Run the SSE and WebSocket examples. Observe the server's continuous push in the former and its response to a client message in the latter. Check that disconnecting leaves no timer tasks behind.

// Write your code or record your verification results here