Push live updates to the browser. Learn why WebSockets exist, build a server with the ws library, broadcast to every connected client, connect from the browser, and know when to reach for Socket.IO.
Why: a normal HTTP request is one-way and one-shot — the browser asks, the server answers, the connection closes. That is fine for loading a page, but useless when the server needs to tell the browser something new (a chat message, a live price, a notification). A WebSocket is a single connection that stays open so both sides can send messages at any time. Note: the URL starts with ws:// (or wss:// when secured with TLS) instead of http://.
Why: ws is the small, standard WebSocket library for Node. You create a server, then react to events: connection (a client joined), message (it sent data), and close (it left). Here the server echoes every message back.
$ pnpm add ws// server.js
import { WebSocketServer } from 'ws'
const wss = new WebSocketServer({ port: 8080 })
wss.on('connection', (socket) => {
console.log('a client connected')
socket.on('message', (data) => {
// data is a Buffer — turn it into a string first
socket.send(`you said: ${data}`)
})
socket.on('close', () => console.log('a client left'))
})Why: the real power of WebSockets is pushing one message to everyone at once — that is what makes a chat or a live feed. The server keeps a list of connected clients (wss.clients); loop over it and send to each one whose connection is still open.
wss.on('connection', (socket) => {
socket.on('message', (data) => {
// send this message to every connected client
for (const client of wss.clients) {
if (client.readyState === client.OPEN) {
client.send(data.toString())
}
}
})
})Why: browsers have a built-in WebSocket object — no library needed. You open a connection, listen for messages with onmessage, and call send() to talk back. This is the other half of the chat.
// runs in the browser
const socket = new WebSocket('ws://localhost:8080')
socket.onopen = () => socket.send('Hello from the browser!')
socket.onmessage = (event) => {
console.log('server says:', event.data)
}When: raw ws is perfect for simple cases, but production apps often need automatic reconnection when the network drops, "rooms" to group clients, and a fallback for networks that block WebSockets. Socket.IO is a popular library that adds all of this on top. Note: it has its own client library — a plain browser WebSocket cannot talk to a Socket.IO server.
$ pnpm add socket.ioimport { Server } from 'socket.io'
const io = new Server(3000)
io.on('connection', (socket) => {
socket.join('lobby') // put this client in a room
socket.on('chat', (msg) => {
io.to('lobby').emit('chat', msg) // send only to that room
})
})