WebSockets & SSE in expressjs

medium · Express.js — Web APIs & middleware

While standard HTTP follows a "Request-Response" model where the client must always ask for data, WebSockets and Server-Sent Events (SSE) allow the server to push data to the client in real-time . This is essential for features like live chat, stock tickers, or real-time job alerts on your platform . 1. WebSockets (Full-Duplex) Theory: WebSockets provide a persistent, two-way (bi-directional) communication channel over a single TCP connection . It starts as an HTTP request that "upgrades" to a WebSocket connection . Bi-directional: Both the client and server can send messages at any time . Low Latency: Once the connection is open, there is very little overhead, making it faster than repeatedly opening HTTP connections . Use Case: Real-time collaboration tools, gaming, or the "Zoom-like" application logic you've worked on . The Process (using Socket.io): const io = require('socket.io')(server); io.on('connection', (socket) => {   console.log('A user connected');      // Listening for a message from the client   socket.on('chat-message', (msg) => {     // Broadcasting the message to everyone connected     io.emit('chat-message', msg);   }); }); 2. Server-Sent Events (SSE) (Uni-directional) Theory: SSE is a standard that allows servers to push data to web pages over HTTP . Unlike WebSockets, it is one-way : data only flows from the server to the client . Uni-directional: The server "streams" updates to the client . Automatic Reconnection: Browsers handle reconnections automatically if the link drops . Lightweight: It uses standard HTTP and doesn't require complex protocols or heavy libraries . Use Case: Real-time dashboards, stock price updates, or news feeds . app.get('/events', (req, res) => {   res.setHeader('Content-Type', 'text/event-stream');   res.setHeader('Cache-Control', 'no-cache');   res.setHeader('Connection', 'keep-alive');   // Sending a message every 5 seconds   setInterval(() => {     res.write(`data: ${JSON.stringify({ time: new Date() })}\n\n`);   }, 5000); });

Back to Express.js — Web APIs & middleware

Browse all study material on Careeroza