Back to Digest
SnippetsNext.js 14 App Router Streaming SSE Endpoint
typescriptAdvancedCopied 278 times

Next.js 14 App Router Streaming SSE Endpoint

Native Server-Sent Events (SSE) route handler in Next.js 14 App Router supporting real-time token streaming.

typescript•
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { NextRequest } from "next/server"; export const dynamic = "force-dynamic"; export async function GET(req: NextRequest) { const encoder = new TextEncoder(); const stream = new ReadableStream({ async start(controller) { for (let i = 1; i <= 10; i++) { const payload = JSON.stringify({ step: i, message: `Streaming event #${i}` }); controller.enqueue(encoder.encode(`data: ${payload}\n\n`)); await new Promise((r) => setTimeout(r, 500)); } controller.close(); }, }); return new Response(stream, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache, no-transform", Connection: "keep-alive", }, }); }
25 lines • 716 charactersUsed by 278 developers

Usage & Production Best Practices

This implementation is specifically optimized for high-throughput production environments. When integrating this pattern into your codebase:

  • Ensure all asynchronous handles or listeners are cleaned up within the parent lifecycle.
  • Avoid unbounded memory allocation by pinning cache buffers and queue capacities.
  • Pair with automated unit tests to guarantee zero regressions under edge-case concurrency.
Featured Resourcein Next.js / Backend
Curated Tool