Blog · 2026-12-04
Real-time notifications in Next.js with Server-Sent Events (no WebSockets needed)
Why I used Server-Sent Events instead of WebSockets for instant notifications in a task management app, with the route handler, keep-alive pings and a fallback for serverless hosting.
At Famous Drive I built TaskFlow, an internal task management app. Managers assign daily, one-off and recurring tasks, and people need to see a new assignment, a comment or a "sent back for changes" the moment it happens. My first thought was WebSockets. I shipped Server-Sent Events (SSE) instead.
Why SSE instead of WebSockets
Notifications only flow one way: server to browser. The browser already talks to the server through normal requests and server actions. SSE covers that one-way stream with:
- a plain HTTP response, so cookies, auth and proxies work as usual;
- automatic reconnects built into the browser's
EventSource; - no extra server or library, just a Next.js route handler.
The route handler
The handler checks the session, subscribes the user to an in-memory event bus, and writes each event to a stream. A simplified version:
// app/api/stream/route.js
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
export async function GET(request) {
const user = await getSession();
if (!user) return new Response("Unauthorized", { status: 401 });
const encoder = new TextEncoder();
const stream = new ReadableStream({
start(controller) {
const send = (text) => controller.enqueue(encoder.encode(text));
const unsubscribe = subscribe(user.id, (event) =>
send(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`)
);
// Comment lines keep proxies from closing an idle connection.
const ping = setInterval(() => send(": ping\n\n"), 25000);
request.signal.addEventListener("abort", () => {
clearInterval(ping);
unsubscribe();
controller.close();
});
send("retry: 5000\n\n"); // reconnect after 5s if dropped
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
},
});
}Three details that matter in production:
- Keep-alive pings. Proxies and tunnels close connections that look idle. A comment line every 25 seconds keeps it open.
- Clean up on abort. When the tab closes, stop the timer and unsubscribe, or every visit leaks a listener.
- Tell the browser how long to wait before reconnecting with
retry:, so a server restart doesn't cause a reconnect storm.
The client
useEffect(() => {
const es = new EventSource("/api/stream");
es.addEventListener("notification", () => refreshFeed());
return () => es.close();
}, []);The catch: serverless
The event bus lives in the memory of one server process. On serverless hosting, the request that creates a notification and the open stream can run on different instances, so the event never arrives. The route handles this honestly: on serverless it returns 204 No Content, which tells EventSource to stop reconnecting, and the notification bell falls back to a slow poll.
For alerts when the app isn't open at all, the app also supports Web Push, so a notification can arrive even with the tab closed.
When I would use WebSockets
If the browser had to send a constant stream back too, such as live collaborative editing, chat with typing indicators, or multiplayer state, WebSockets (or a hosted service) would be the right tool. For server-to-user notifications, SSE was less code and fewer moving parts.