#Stream api on api route

1 messages · Page 1 of 1 (latest)

fresh yarrow
#

The implementation is based on Stream API. (ReadableStream, WritableStream)

In the Route Handler of the App Router, I was able to implement it by passing ReadableStream to NextResponse, but I’m not able to make it in the API Routes of the Pages Router.

Pages Router does not support Stream API?

shell cloakBOT
#

Hi @fresh yarrow. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you are correct. The Pages Router in Next.js does not support streaming. This is confirmed in a Github issue (https://github.com/vercel/next.js/issues/1209) where a member of the Next.js team stated that they are not planning to add streaming to the Pages Router. They explained that specific APIs (i.e., metadata) had to be added to make early flushing work, and without Server Components, you can't stream in data so you wouldn't get clear benefits from having it for Pages like you do in App Router.

However, even if the rest of your app uses Next.js Pages Router, you can use route handlers in the App Router to stream responses. The App Router supports streaming rendering by default. Here is an example of how you can do this:

//Next.js App Router will always support streaming with Route Handlers

You can follow the App Router examples in the Next.js documentation (https://nextjs.org/docs/app/building-your-application/routing/route-handlers) to implement this.

For the Stream APIs, Next.js provides several APIs that you can use:

  • ReadableStream: Represents a readable stream
  • ReadableStreamBYOBReader: Represents a reader of a ReadableStream
  • ReadableStreamDefaultReader: Represents a reader of a ReadableStream
  • TransformStream: Represents a transform stream
  • WritableStream: Represents a writable stream
  • WritableStreamDefaultWriter: Represents a writer of a WritableStream

You can find more information about these APIs in the Next.js documentation (https://nextjs.org/docs/pages/api-reference/edge#stream-apis).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: