📖 Scenario: You are building a simple chat server that tries to use WebSocket for real-time messages. But if WebSocket is not available, it should use long polling as a fallback to keep the chat messages updated.
🎯 Goal: Create a Node.js server that supports long polling as a fallback method for clients to receive messages when WebSocket is not available.
📋 What You'll Learn
Create a message store array called messages with initial messages
Create a variable called lastMessageId to track the last message ID sent
Implement a long polling route /poll that waits for new messages
Complete the server setup to listen on port 3000
💡 Why This Matters
🌍 Real World
Long polling is used in chat apps and real-time notifications when WebSocket is not supported or blocked by firewalls.
💼 Career
Understanding fallback techniques like long polling helps backend developers build reliable real-time features that work across different network conditions.
Progress0 / 4 steps
1
Create initial message store
Create an array called messages with these exact objects: { id: 1, text: 'Hello' } and { id: 2, text: 'Welcome' }.
Node.js
Hint
Use const messages = [ ... ] to create the array with two objects.
2
Add lastMessageId variable
Create a variable called lastMessageId and set it to the id of the last message in the messages array.
Node.js
Hint
Use messages[messages.length - 1].id to get the last message's id.
3
Implement long polling route
Using Express, create a GET route at /poll that accepts a query parameter lastId. Inside the route, use a setInterval to check every 1 second if there are new messages with id greater than lastId. When new messages exist, respond with JSON containing those messages and clear the interval.
Node.js
Hint
Use app.get('/poll', (req, res) => { ... }) and inside use setInterval to check for new messages.
4
Start the server
Add code to make the Express app listen on port 3000 and log 'Server running on port 3000' when it starts.
Node.js
Hint
Use app.listen(3000, () => { console.log('Server running on port 3000') }) to start the server.
Practice
(1/5)
1. What is the main purpose of using long polling in Node.js applications?
easy
A. To keep a client request open until new data is available
B. To immediately close the connection after sending data
C. To send multiple responses to a single request
D. To replace WebSocket connections entirely
Solution
Step 1: Understand long polling behavior
Long polling keeps the client request open until the server has new data to send.
Step 2: Compare options to this behavior
Only To keep a client request open until new data is available describes this behavior correctly; others describe different or incorrect behaviors.
Final Answer:
To keep a client request open until new data is available -> Option A
Quick Check:
Long polling = open request until data ready [OK]
Hint: Long polling holds request open until data arrives [OK]
Common Mistakes:
Thinking long polling sends multiple responses per request
Confusing long polling with WebSocket persistent connection
Assuming long polling closes connection immediately
2. Which of the following is the correct way to implement a long polling endpoint in Node.js using Express?
easy
A. res.write('data'); // keep connection open without res.end()
B. res.send('data'); res.end();
C. res.json('data'); res.end();
D. res.send('data'); // then wait before closing connection
Solution
Step 1: Identify how to keep connection open
In long polling, the server holds the connection open, so it should not call res.end() immediately.
Step 2: Check which option keeps connection open
res.write('data'); // keep connection open without res.end() uses res.write() without res.end(), which keeps the connection open for long polling.
Final Answer:
res.write('data'); // keep connection open without res.end() -> Option A
Quick Check:
Keep connection open = no res.end() [OK]
Hint: Use res.write() without res.end() to keep connection open [OK]
Common Mistakes:
Calling res.end() immediately closes connection
Using res.send() closes connection right away
Not sending any response causes timeout
3. Consider this Node.js long polling code snippet:
5. You want to implement long polling as a fallback in a Node.js app that first tries WebSocket. Which approach correctly handles fallback and client reconnection?
hard
A. Use WebSocket and long polling simultaneously, sending duplicate data to client
B. Use WebSocket only; if unavailable, do nothing and drop updates
C. Use long polling only; never try WebSocket to simplify code
D. Use WebSocket; if unavailable, client repeatedly sends GET requests that wait on server until data or timeout, then reconnect
Solution
Step 1: Understand fallback strategy
WebSocket is preferred for real-time, but fallback uses long polling with repeated client requests.