WebSockets are a way for a browser and server to keep a connection open and send messages back and forth in real time. Unlike regular HTTP where the browser asks and the server answers, WebSockets let the server push data to the browser whenever it wants.
HTTP vs. WebSockets
HTTP (request-response):
Browser: "Any new messages?" β Server: "No."
Browser: "Any new messages?" β Server: "No."
Browser: "Any new messages?" β Server: "Yes, here's one."
Browser: "Any new messages?" β Server: "No."
The browser has to keep asking (polling). Wasteful and slow.
WebSockets (persistent connection):
Browser: "Let's open a connection."
Server: "OK, connected."
... (connection stays open) ...
Server: "New message: Hello!" β Server pushes instantly
Server: "New message: How are you?" β No need to ask
Browser: "I'm typing..." β Browser can send too
One connection, instant two-way communication.
When to use WebSockets
- Chat apps β messages appear instantly
- Live notifications β new email, new follower
- Collaborative editing β Google Docs, Figma
- Live dashboards β stock prices, server metrics
- Multiplayer games β real-time player positions
- Live sports scores β updates as they happen
When NOT to use WebSockets
- Regular web pages β just use HTTP
- REST APIs β request-response is fine
- Infrequent updates β polling every 30 seconds is simpler
- Static content β no real-time needed
Simple example
Server (Node.js):
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (data) => {
console.log('Received:', data.toString());
// Broadcast to all connected clients
wss.clients.forEach((client) => {
if (client.readyState === 1) {
client.send(data.toString());
}
});
});
ws.send('Welcome!');
});
Client (browser):
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
console.log('Connected');
ws.send('Hello from browser!');
};
ws.onmessage = (event) => {
console.log('Received:', event.data);
};
ws.onclose = () => {
console.log('Disconnected');
};
Thatβs a working chat server in ~30 lines.
WebSockets vs. alternatives
| Technology | How it works | Best for |
|---|---|---|
| WebSockets | Persistent two-way connection | Chat, games, collaboration |
| Server-Sent Events (SSE) | Server pushes, client listens (one-way) | Notifications, live feeds |
| Long polling | Client asks, server holds response until data is ready | Simple real-time, fallback |
| HTTP polling | Client asks repeatedly on a timer | Infrequent updates |
SSE is simpler than WebSockets if you only need server β client communication (no messages from the client). It works over regular HTTP and reconnects automatically.
In production
For production apps, most people use a library instead of raw WebSockets:
- Socket.IO β most popular, handles reconnection and fallbacks
- Pusher / Ably β managed WebSocket services (no server to maintain)
- Supabase Realtime β real-time database subscriptions
// Socket.IO example (much simpler)
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000');
socket.on('message', (data) => console.log(data));
socket.emit('message', 'Hello!');