Real-Time Communication in JavaScript: SSE vs WebSockets Explained

Posted by

Learn how Server-Sent Events and WebSockets work, their key differences, and how to pick the right one for your real-time web app.

Learn how Server-Sent Events and WebSockets work, their key differences, and how to pick the right one for your real-time web app.

Introduction

Modern users expect real-time experiences, think live chats, notifications, stock tickers, or collaborative editors.

As JavaScript developers, we have two main tools to make that happen:

  • Server-Sent Events (SSE)
  • WebSockets

Both let you send data from the server to the client without reloading or polling, but they work very differently.

In this article, youโ€™ll learn:

  • What real-time communication means in the browser
  • How SSE and WebSockets actually work
  • When to use each
  • Practical code examples for both

By the end, youโ€™ll know how to build a real-time feature using pure JavaScript, no heavy frameworks or plugins needed.


1. Why Real-Time Communication Matters

Traditional HTTP is request-response-based.
 The client sends a request, the server responds once, and thatโ€™s it.

But what if you want:

  • A chat app that updates instantly?
  • A dashboard that reflects changes in real time?
  • A notification system that alerts users immediately?

You need a way for the server to push data to the browser the moment something changes, not when the client asks.

Thatโ€™s where Server-Sent Events and WebSockets come in.


2. Server-Sent Events (SSE): One-Way, Simple, Reliable

How It Works

Server-Sent Events (SSE) let the server push updates to the browser over a single, long-lived HTTP connection.
 The browser opens a connection, and the server continuously sends updates whenever thereโ€™s new data.

Itโ€™s unidirectional data that only flows from the server to โ†’ client.

Client-Side Example

// Client
const eventSource = new EventSource('/events');

eventSource.onmessage = (event) => {
console.log('New message:', event.data);
};

Server-Side Example (Node.js + Express)

// Server
import express from 'express';
const app = express();

app.get('/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
setInterval(() => {
res.write(`data: ${new Date().toISOString()}\n\n`);
}, 2000);
});

app.listen(3000, () => console.log('SSE running on port 3000'));

โœ… The connection stays open.
โœ… The server sends messages in plain text.
โœ… The browser automatically reconnects if the connection drops.

Itโ€™s perfect for dashboards, notifications, or feeds that donโ€™t need two-way interaction.


Under the Hood

  • Uses standard HTTP (port 80 or 443)
  • Content-Type: text/event-stream
  • Messages are text-only and formatted as data: <message>\n\n
  • Built-in reconnect in case of disconnects
  • Lightweight and browser-native (EventSource API)

3. WebSockets: Two-Way, Fast, Interactive

How It Works

WebSockets create a full-duplex (two-way) communication channel over a single TCP connection.
Once established, both the server and client can send and receive messages anytime.

Think of it as a direct pipe between the two no request-response pattern at all.

Client-Side Example

const socket = new WebSocket('ws://localhost:3000');

socket.onopen = () => console.log('Connected');
socket.onmessage = (event) => console.log('Server says:', event.data);

// Send data to server
socket.send('Hello Server!');

Server-Side Example (Node.js + ws)

import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 3000 });

wss.on('connection', (socket) => {
console.log('Client connected');
socket.on('message', (msg) => console.log('Received:', msg));

setInterval(() => {
socket.send(`Server time: ${new Date().toLocaleTimeString()}`);
}, 2000);
});

โœ… Both sides can send data freely.
โœ… Works great for chat apps, collaboration tools, and live games.
โœ… Can send binary data, not just text.


4. SSE vs WebSocketsโ€Šโ€”โ€ŠHead-to-Head Comparison

Summary:

  • Use SSE when you only need server โ†’ client streaming.
  • Use WebSockets when both sides need to talk to each other.

5. When to Use Server-Sent Events

Best For

  • News or activity feeds
  • System monitoring dashboards
  • Real-time logs or build progress
  • Live scores, updates, notifications

Why

  • Simple HTTP connection
  • Built-in auto-reconnect
  • Works with CDNs and load balancers
  • Uses minimal server resources

Example: Live Stock Ticker

const source = new EventSource('/stocks');
source.onmessage = (e) => {
updateStockList(JSON.parse(e.data));
};

Perfect for sending frequent updates from the server without needing a two-way connection.


6. When to Use WebSockets

Best For

  • Chat applications
  • Multiplayer games
  • Real-time collaboration (e.g., document editing)
  • Live trading systems
  • IoT devices sending telemetry data

Why

  • Full-duplex: both sides communicate freely
  • Ultra-low latency
  • Can handle thousands of simultaneous connections

Example: Live Chat

const ws = new WebSocket('wss://example.com/chat');
ws.onmessage = (e) => addMessage(e.data);
document.querySelector('form').onsubmit = (e) => {
e.preventDefault();
ws.send(messageInput.value);
};

Messages are sent instantly in both directions, no reloading, no lag.


7. Handling Reconnection and Errors

In SSE: Easy

The browser automatically reconnects after a few seconds if the connection drops.

eventSource.onerror = () => console.log('Connection lost, reconnecting...');

In WebSockets: Manual

You need to handle reconnection logic yourself.

socket.onclose = () => {
setTimeout(() => {
socket = new WebSocket('ws://localhost:3000');
}, 3000);
};

Libraries like Socket.IO simplify this by adding auto-reconnect and event handling on top of WebSockets.


8. Scalability and Performance

For large-scale systems (like multiplayer games), WebSockets win.
For lightweight, broadcast-style updates, SSE is simpler and more scalable.


9. Browser and Server Support

Both are well-supported in modern browsers, but SSE doesnโ€™t work in old Internet Explorer versions.


10. Choosing Between SSE and WebSockets

If youโ€™re unsure which to pick, use this quick guide:

In short:

  • Start with SSE for simplicity.
  • Switch to WebSockets when you need full-duplex power.

Conclusion

Both Server-Sent Events and WebSockets bring real-time magic to JavaScript apps.
They solve the same problem, keeping your users updated live, but they take different approaches.

  • SSE is simple, reliable, and HTTP-friendly, ideal for feeds and dashboards.
  • WebSockets are powerful, flexible, and built for full-duplex interactivity.

If your web app needs a lightweight stream of updates, use SSE.
If itโ€™s more interactive and chat-like, go for WebSockets.

Pro Tip: You can even combine both SSE for broadcasting events and WebSockets for direct messaging.


Call to Action

Which approach are you using for real-time communication: SSE, WebSockets, or both?
Share your experience in the comments and bookmark this guide for your next real-time JavaScript project.

Leave a Reply

Your email address will not be published. Required fields are marked *