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)
}

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.

Further reading

Problem with a question

Next.js · Middle · question 67

Test yourself

Take the Next.js · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz