javascript / expert
Snippet
High-Performance Data Streaming in Route Handlers
Streaming large datasets directly from Route Handlers using the `ReadableStream` API is a powerful pattern for reducing 'Time to First Byte' (TTFB). By sending data in chunks as it becomes available, you avoid waiting for the entire payload to be generated on the server. This is essential for AI-driven text generation or processing massive logs where memory overhead must be kept minimal.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
export async function GET() {const stream = new ReadableStream({async start(controller) {const encoder = new TextEncoder();for (let i = 0; i < 100; i++) {controller.enqueue(encoder.encode(`Chunk ${i}\n`));await new Promise(r => setTimeout(r, 100));}controller.close();},});return new Response(stream, { headers: { 'Content-Type': 'text/plain' } });}
nextjs
Breakdown
1
new ReadableStream({ async start(controller) { ... } })
Creates a manual stream controller to push data incrementally to the client.
2
controller.enqueue(encoder.encode(...))
Encodes a string into Uint8Array chunks and adds them to the stream queue.
3
return new Response(stream, ...)
Returns a Response object that consumes the stream, enabling chunked transfer encoding.