How do you stream responses from API routes?

Return a Response whose body is a ReadableStream. Next.js sends chunks to the client as you enqueue them, which is how you stream AI tokens, large exports or Server-Sent Events from a Route Handler. On the client, read response.body with a reader or use EventSource for SSE.

Building a stream

  • Create new ReadableStream({ async start(controller) { ... } }) and call controller.enqueue(encoder.encode(chunk)), then controller.close().
  • Or pass an existing stream through, such as an LLM SDK stream or a fetch response body.
  • Async generators can be converted with ReadableStream.from() (Node.js 20+).
  • Use TransformStream to modify chunks on the way.

Server-Sent Events

Set Content-Type: text/event-stream, Cache-Control: no-cache, no-transform and Connection: keep-alive, then write data: ...\n\n lines. Browsers reconnect automatically with EventSource.

Handling disconnects

Listen to request.signal (an AbortSignal) and stop work when the client goes away, to avoid paying for unused computation.

Platform considerations

  • Streaming must not be buffered by a reverse proxy (X-Accel-Buffering: no for nginx).
  • Serverless functions have a maximum duration; set export const maxDuration = 60 where supported.
  • Do not use "use cache" or prerendering for streaming handlers; they are request-time by nature.

Alternatives

For streaming UI rather than raw data, use React Server Components with <Suspense>. For AI chat, the Vercel AI SDK wraps streaming in hooks like useChat.

Code example

tsx
1// app/api/progress/route.ts - Server-Sent Events
2export async function GET(request: Request) {
3 const encoder = new TextEncoder();
4
5 const stream = new ReadableStream({
6 async start(controller) {
7 for (let pct = 0; pct <= 100; pct += 20) {
8 if (request.signal.aborted) break; // client disconnected
9 controller.enqueue(encoder.encode(`data: ${JSON.stringify({ pct })}\n\n`));
10 await new Promise((r) => setTimeout(r, 500));
11 }
12 controller.close();
13 },
14 });
15
16 return new Response(stream, {
17 headers: {
18 "Content-Type": "text/event-stream",
19 "Cache-Control": "no-cache, no-transform",
20 Connection: "keep-alive",
21 "X-Accel-Buffering": "no",
22 },
23 });
24}
25
26// Client:
27// const es = new EventSource("/api/progress");
28// es.onmessage = (e) => setPct(JSON.parse(e.data).pct);

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app