0PricingLogin
Next.js 15 Fullstack (App Router + Server Actions) · Lesson

Server-Sent Events from Route Handlers

Push live updates to clients with an SSE stream and reconnect logic from a Route Handler.

What Are Server-Sent Events?

Server-Sent Events (SSE) is a browser-native protocol that lets the server push data to the client over a single, long-lived HTTP connection. Unlike WebSockets, SSE is unidirectional — the server writes, the client reads.

  • Built on plain HTTP/1.1 or HTTP/2
  • The browser's EventSource API handles connection and automatic reconnection
  • Each message is a UTF-8 text frame with a defined wire format
  • Works through standard firewalls and proxies that block WebSockets

SSE is ideal for dashboards, live feeds, progress bars, and any scenario where only the server needs to initiate updates.

SSE Wire Format

The SSE protocol uses the text/event-stream MIME type. Each event is a block of plain text lines followed by a blank line:

  • data: <payload> — the actual message body (required)
  • event: <name> — optional custom event type (client listens with addEventListener)
  • id: <value> — optional cursor the browser sends back as Last-Event-ID on reconnect
  • retry: <ms> — tells the browser how long to wait before reconnecting

A minimal event looks like this:

// Raw SSE frame sent over the wire (TypeScript string)
const frame =
  'id: 42\n' +
  'event: stock-update\n' +
  'data: {"symbol":"AAPL","price":189.50}\n' +
  'retry: 3000\n' +
  '\n'; // <-- blank line terminates the event

console.log(frame);

All lessons in this course

  1. Server-Sent Events from Route Handlers
  2. Integrating WebSocket Services in a Serverless World
  3. Streaming AI Responses Token-by-Token
  4. Presence, Cursors, and Live Collaboration State
← Back to Next.js 15 Fullstack (App Router + Server Actions)