0
0
Node.jsframework~5 mins

Long polling as fallback in Node.js

Choose your learning style9 modes available
Introduction

Long polling helps keep a connection open to get updates when real-time methods like WebSockets are not available.

When you want to update a web page with new data but the browser or network does not support WebSockets.
When you need a simple way to get server updates without constantly asking the server again and again.
When building chat apps or notifications but want a fallback for older browsers.
When you want to reduce server load by waiting for new data before responding.
When you want to keep users informed in near real-time without complex setups.
Syntax
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.

Examples
This example waits 10 seconds before responding if no data is ready.
Node.js
app.get('/poll', (req, res) => {
  if (dataReady) {
    res.send('Here is your data');
  } else {
    setTimeout(() => res.send('No new data'), 10000);
  }
});
This example checks every second for new data and responds immediately when available.
Node.js
app.get('/poll', (req, res) => {
  const checkData = () => {
    if (dataReady) {
      res.json({ data: 'new data' });
    } else {
      setTimeout(checkData, 1000);
    }
  };
  checkData();
});
Sample Program

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.

Node.js
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');
});
OutputSuccess
Important Notes

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.

Summary

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.