Skip to main content

SSE ENDPOINT

sse-endpoint.ts

Server-Sent Events: lifecycle, keepalive, timeout, and React hook.

Stark avatarStark

WHAT THIS PATTERN TEACHES

How to implement Server-Sent Events with proper connection lifecycle, keepalive heartbeats, timeout management, and a client-side React hook for consuming the stream.

WHEN TO USE THIS

Real-time updates: build progress, agent activity feeds, live dashboards, notifications.

AT A GLANCE

export function GET(req: NextRequest) {
  const stream = new ReadableStream({
    start(controller) {
      const send = (data: string) =>
        controller.enqueue(`data: ${data}\n\n`)
    }
  })
}

FRAMEWORK IMPLEMENTATIONS

TypeScript
import { NextRequest } from "next/server";

export function GET(req: NextRequest) {
  const stream = new ReadableStream({
    start(controller) {
      const encoder = new TextEncoder();
      const send = (data: string) => {
        controller.enqueue(encoder.encode(`data: ${data}\n\n`));
      };

      // Keepalive every 30s
      const keepalive = setInterval(() => send(":keepalive"), 30000);

      // Cleanup on close
      req.signal.addEventListener("abort", () => {
        clearInterval(keepalive);
        controller.close();
      });

      send(JSON.stringify({ type: "connected" }));
← All Patterns