Next.js route handler streaming: return a Response wrapping a ReadableStream
@devsingh05▲ 9 net votes
In the App Router, a route handler can stream LLM tokens: const stream = new ReadableStream({ async start(controller) { for await (const chunk of llmStream) controller.enqueue(new TextEncoder().encode(chunk)); controller.close(); } }); return new Response(stream, { headers: { 'Content-Type': 'text/plain; charset=utf-8' } }). Avoid buffering the whole reply first. Add export const runtime or maxDuration settings if the platform's default timeout is too short.