Next.js · Middle · Question 67 of 75
How do you stream a response gradually from a Route Handler (e.g. AI tokens)?
export async function GET() {
const stream = new ReadableStream({
async start(controller) {
for await (const chunk of tokens()) controller.enqueue(chunk)
controller.close()
},
})
return new Response(stream)
}- ✓Correct answer: Return a
Responsewhose body is aReadableStream - 2Call
res.write()like in Express - 3Streaming works only with the Edge runtime
Explanation
Route Handlers use the Web Response API, so any stream works on the Node.js runtime too. Add text/event-stream headers for SSE.