Long polling helps keep a connection open to get updates when real-time methods like WebSockets are not available.
Long polling as fallback in Node.js
app.get('/updates', (req, res) => { if (newDataAvailable) { res.json(newData); } else { // wait and respond later } });
The server holds the request open until new data is ready or a timeout happens.
The client sends a new request after each response to keep listening.
app.get('/poll', (req, res) => { if (dataReady) { res.send('Here is your data'); } else { setTimeout(() => res.send('No new data'), 10000); } });
app.get('/poll', (req, res) => { const checkData = () => { if (dataReady) { res.json({ data: 'new data' }); } else { setTimeout(checkData, 1000); } }; checkData(); });
This Node.js Express server uses long polling to send data when ready or after 15 seconds if no data arrives. It simulates new data arriving after 5 seconds.
import express from 'express'; const app = express(); let dataReady = false; let newData = { message: 'Hello from server!' }; app.get('/long-poll', (req, res) => { if (dataReady) { res.json(newData); dataReady = false; // reset } else { const timer = setTimeout(() => { if (!res.writableEnded) { res.json({ message: 'No new data' }); } }, 15000); // 15 seconds timeout // Simulate data arrival after 5 seconds setTimeout(() => { if (!res.writableEnded) { clearTimeout(timer); dataReady = true; res.json(newData); dataReady = false; } }, 5000); } }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Long polling keeps the connection open but can use more server resources than WebSockets.
Always set a timeout to avoid hanging requests forever.
The client must send a new request after each response to continue receiving updates.
Long polling is a way to get updates by holding a request open until data is ready.
It works well as a fallback when real-time connections are not possible.
Remember to handle timeouts and client re-requests for smooth updates.