Normal HTTP is request → response: the server cannot send data unless the client asks. WebSockets keep a connection open, so the server can push data instantly — for chat, live scores, notifications and dashboards.
Socket.IO
Socket.IO makes WebSockets easy and adds automatic reconnection, rooms and fallbacks. Install npm install socket.io on the server and use the client library in the browser.
Key methods
io.on('connection', socket => ...)— a client connectedsocket.on('event', handler)— receivesocket.emit('event', data)— send to this clientio.emit('event', data)— send to everyonesocket.broadcast.emit(...)— everyone except the sendersocket.join('room1')andio.to('room1').emit(...)— rooms (group chats, per-order updates)socket.on('disconnect', ...)
Validate data from clients just like HTTP input, and check login (for example a JWT in the handshake) before joining private rooms.
For simple one-way updates, Server-Sent Events are a lighter alternative.
Example
// server.js
import express from 'express';
import { createServer } from 'node:http';
import { Server } from 'socket.io';
const app = express();
const server = createServer(app);
const io = new Server(server);
app.get('/', (req, res) => res.sendFile(import.meta.dirname + '/index.html'));
io.on('connection', (socket) => {
socket.broadcast.emit('system', 'A user joined the chat');
socket.on('chat', (text) => {
const message = String(text).slice(0, 500);
io.emit('chat', { id: socket.id.slice(0, 4), message, at: Date.now() });
});
socket.on('disconnect', () => io.emit('system', 'A user left'));
});
server.listen(3000, () => console.log('Chat on http://localhost:3000'));
/* index.html (client)
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
socket.on('chat', (m) => console.log(m.id + ': ' + m.message));
socket.emit('chat', 'Hello everyone!');
</script> */
Open http://localhost:3000 in two tabs: a message sent in one appears in both instantly, and joining or leaving shows a system message to the others.