Next.js Real-Time: WebSockets, SSE, and Polling
Next.js has no built-in WebSocket support, and the omission is architectural: the App Router's deployment targets â serverless functions and edge isolates â are request-scoped and cannot hold a socket open for hours. Real-time features therefore require either a custom Node server that owns the connection lifecycle, a separate socket service, or a one-way push protocol that rides on ordinary HTTP responses. Each option carries different operational weight, and picking the heaviest one for a notifications badge is how teams end up maintaining a socket fleet nobody needed.
This lesson compares polling, Server-Sent Events, and full WebSockets, then implements each where it belongs â including the pub/sub layer that lets multiple server instances broadcast to the same room without sharing process memory. The comparison is deliberately cost-ordered: start from the cheapest mechanism that satisfies the product requirement, and move up only when the data's direction or rate forces it. Most applications end up with one WebSocket-backed feature and a handful of SSE feeds, not a socket layer under every component. Getting the classification right early prevents the most expensive real-time mistake, which is re-architecting a notifications badge into a connection fleet six months after launch when the original decision was never written down.
Prerequisites
- !Comfort with route handlers and custom servers
- !Understanding of why serverless cannot hold sockets
- !Node.js process and deployment basics
What You'll Learn
- 1Decide between polling, SSE, and WebSockets from product requirements
- 2Implement SSE streaming from an App Router route handler
- 3Add Socket.io behind a custom Next.js server
- 4Fan messages across instances with a Redis pub/sub channel
Choosing the cheapest protocol that fits
Start from the data's direction and rate. If the client asks occasionally and can tolerate staleness, polling with a sensible interval is fine and needs no new infrastructure. If the server pushes updates to many clients and clients never talk back over the same channel, SSE is simpler and proxies more gracefully. If the conversation is genuinely bidirectional â chat, collaborative cursors, live games â WebSockets earn their cost.
| Pattern | Direction | Connection | Infra cost | Best for |
|---|---|---|---|---|
| Polling | Client pulls | Short requests | None | Low-churn dashboards |
| SSE | Server pushes | One long HTTP response | Standard HTTP | Feeds, notifications, live scores |
| WebSocket | Bidirectional | Long-lived upgrade | Custom server or service | Chat, collaboration, games |
| Long polling | Pseudo-push | Repeating long requests | None | Legacy fallback only |
The table is deliberately conservative: many features labeled real-time are one-directional updates that SSE handles with a fraction of the moving parts.
Server-Sent Events from a route handler
SSE is plain HTTP with a content type of text/event-stream. The browser's EventSource API handles reconnection for you, and a route handler can stream directly â no custom server required.
// app/api/live-orders/route.js
export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';
export async function GET(request) {
const encoder = new TextEncoder();
const stream = new ReadableStream({
start(controller) {
const send = (event, data) => {
controller.enqueue(
encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
);
};
send('connected', { at: Date.now() });
const interval = setInterval(async () => {
const orders = await fetchRecentOrders();
if (orders.length > 0) {
send('orders', orders);
}
}, 5000);
request.signal.addEventListener('abort', () => {
clearInterval(interval);
controller.close();
});
},
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
},
});
}
Two details matter in production. The abort signal cleanup prevents interval leaks when clients disconnect â the most common source of memory growth in SSE deployments. And no-transform tells compressing proxies to leave the stream alone; a buffered proxy turns push into accidental polling.
// components/OrderFeed.js
'use client';
import { useEffect, useState } from 'react';
export function OrderFeed() {
const [orders, setOrders] = useState([]);
useEffect(() => {
const source = new EventSource('/api/live-orders');
source.addEventListener('orders', (e) => {
const incoming = JSON.parse(e.data);
setOrders((prev) => [...incoming, ...prev].slice(0, 20));
});
source.onerror = () => {
// EventSource reconnects automatically; surface state if needed
};
return () => source.close();
}, []);
return (
<ul aria-live="polite">
{orders.map((order) => (
<li key={order.id}>
{order.item} â {order.status}
</li>
))}
</ul>
);
}
WebSockets behind a custom server
Bidirectional features need a protocol upgrade, which means owning the HTTP server. A custom server file creates the Node server, attaches Socket.io, and delegates normal requests back to Next.js â routing, rendering, and API routes keep working exactly as before.
// server.js
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const { Server } = require('socket.io');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const io = new Server(app.getServer() ?? undefined, {
path: '/api/socketio',
cors: { origin: process.env.APP_URL, methods: ['GET', 'POST'] },
});
app.prepare().then(() => {
const server = createServer((req, res) => {
handle(req, res, parse(req.url, true));
});
io.attach(server);
io.on('connection', (socket) => {
socket.on('join-room', (room) => {
socket.join(room);
});
socket.on('chat-message', async ({ room, text, userId }) => {
const message = await persistMessage({ room, text, userId });
io.to(room).emit('chat-message', message);
});
});
server.listen(process.env.PORT || 3000);
});
A custom server changes the deployment contract: platforms that expect the default standalone output may need a Dockerfile or a dedicated Node host. Keep that trade-off visible in the decision â it is the main operational cost of the WebSocket path.
Broadcasting across instances with pub/sub
A single process broadcasting to its own sockets fails the moment you scale to two. Socket.io's adapter backed by Redis moves the fan-out into a shared channel so every instance delivers to its connected clients.
// lib/socket-server.js (fragment inside server.js setup)
const { createAdapter } = require('@socket.io/redis-adapter');
const { createClient } = require('redis');
const pubClient = createClient({ url: process.env.REDIS_URL });
const subClient = pubClient.duplicate();
Promise.all([pubClient.connect(), subClient.connect()]).then(() => {
io.adapter(createAdapter(pubClient, subClient));
});
With the adapter in place, io.to(room).emit reaches clients connected to any instance. Persisting messages before broadcasting â as the chat handler above does â keeps history consistent even when a room's members span regions.
Authentication on the upgrade
Handshake security is where custom servers leak value. Authenticate during the connection event by parsing the session cookie from the upgrade request, and reject connections that fail. For rooms, check membership server-side on join-room rather than trusting the client's claim â a guessed room ID should never grant access to another tenant's stream.
io.on('connection', async (socket) => {
const session = await getSessionFromCookie(socket.request.headers.cookie);
if (!session) {
socket.disconnect(true);
return;
}
socket.data.userId = session.userId;
socket.on('join-room', async (room) => {
const allowed = await canAccessRoom(session.userId, room);
if (allowed) {
socket.join(room);
}
});
});
Rate-limit messages per socket as well. A single compromised client flooding a room degrades every participant until the server drops the connection.
Presence, ordering, and delivery guarantees
Chat and collaboration features raise expectations the raw protocol does not automatically meet. Delivery is at-most-once unless you add acknowledgment: a message that reaches the socket layer during a disconnect is simply gone. Production chat systems attach a client-generated message ID, persist before broadcast, and have the sender retry with the same ID until the server confirms â idempotency on the write path turns a flaky network into delayed messages instead of lost ones.
Ordering has the same caveat. Socket.io preserves order per connection, but a reconnect can reorder messages relative to what other participants saw, because the disconnected client missed the intervening broadcasts. A per-room sequence number assigned by the server gives every message a total order that clients can sort on receipt and use to detect gaps. When a gap appears, the client refetches the missing range over HTTP rather than trusting the live stream to fill it.
Presence â who is online, who is typing â is a separate subsystem riding the same connections. Typing indicators are pure ephemeral broadcasts with a short client-side timeout that clears the state if no follow-up event arrives, because a user who closes the tab never sends a stop-typing message. Online presence needs a heartbeat and a shared store: the server records the last heartbeat per user across all instances, and a sweeper removes entries older than a threshold. A user with the app open on two devices must appear once, not twice, so presence is keyed by user rather than by socket. These features look trivial in a demo and accumulate real edge cases the first week they run against real networks â design their failure behavior before launch rather than patching it during an incident.
Operational notes
Disable Nagle's algorithm or use Socket.io's ping settings tuned to your network so idle connections survive load balancers with aggressive idle timeouts â sixty seconds is a common ceiling. Log connection counts and room sizes; an unbounded join-all pattern can pin memory. And design a degraded mode: when the socket layer is down, the client should fall back to short-interval polling so the product remains usable rather than frozen.
Common Mistakes
Reaching for WebSockets for a read-only activity feed
Fix: Use SSE from a route handler; it reconnects natively and needs no custom server.
Forgetting to clear intervals or timers on client disconnect
Fix: Listen to the request abort signal and tear down all timers when the stream ends.
Broadcasting only within one process after scaling out
Fix: Install a Redis-backed Socket.io adapter so every instance fans out.
Trusting a client-supplied room ID on join
Fix: Verify membership server-side during the join handler before admitting the socket.
Best Practices
- Classify each real-time feature by direction and rate before choosing a protocol
- Keep the custom server file thin and delegate everything non-socket to Next.js
- Authenticate the handshake and re-authorize every room join
- Ship a polling fallback so socket outages degrade instead of blanking the UI
Interview Questions
Q1: Why can't WebSockets run in a standard serverless Next.js deployment?
Serverless functions are request-scoped with short lifetimes; they cannot maintain the long-lived TCP upgrade a WebSocket requires. A custom server or separate service must own the connection.
Q2: When is SSE preferable to a WebSocket?
When updates flow only server-to-client. SSE rides on normal HTTP, reconnects automatically, and deploys without a custom server.
Q3: How do messages reach clients connected to different server instances?
A Redis pub/sub adapter replicates emits across instances so each one delivers to its local sockets.
Key Takeaways
- Match the protocol to the data: polling, SSE, then WebSockets in increasing cost.
- SSE streams from route handlers with no custom server and built-in reconnection.
- WebSockets need a custom Node server and change your deployment story.
- Redis adapters make broadcasts correct once you run more than one instance.
- Authenticate handshakes and room joins; design a polling fallback for outages.