Skip to content

Commit 6a91ff2

Browse files
authored
docs: streaming responses with pages API routes (#79269)
1 parent 9003170 commit 6a91ff2

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

docs/02-pages/03-building-your-application/01-routing/07-api-routes.mdx

+24-3
Original file line numberDiff line numberDiff line change
@@ -416,8 +416,29 @@ The `query` objects are as follows:
416416
- `pages/api/post/[pid].js` - Will match `/api/post/1`, `/api/post/abc`, etc. But not `/api/post/create`
417417
- `pages/api/post/[...slug].js` - Will match `/api/post/1/2`, `/api/post/a/b/c`, etc. But not `/api/post/create`, `/api/post/abc`
418418

419-
## Edge API Routes
419+
## Streaming responses
420420

421-
If you would like to use API Routes with the Edge Runtime, we recommend incrementally adopting the App Router and using [Route Handlers](/docs/app/building-your-application/routing/route-handlers) instead.
421+
While the Pages Router does support streaming responses with API Routes, we recommend incrementally adopting the App Router and using [Route Handlers](/docs/app/building-your-application/routing/route-handlers) if you are on Next.js 14+.
422422

423-
The Route Handlers function signature is isomorphic, meaning you can use the same function for both Edge and Node.js runtimes.
423+
Here's how you can stream a response from an API Route with `writeHead`:
424+
425+
```js filename="pages/api/hello.js"
426+
import { NextApiRequest, NextApiResponse } from 'next'
427+
428+
export default async function handler(
429+
req: NextApiRequest,
430+
res: NextApiResponse
431+
) {
432+
res.writeHead(200, {
433+
'Content-Type': 'text/event-stream',
434+
'Cache-Control': "no-store",
435+
})
436+
let i = 0
437+
while (i < 10) {
438+
res.write(`data: ${i}\n\n`)
439+
i++
440+
await new Promise((resolve) => setTimeout(resolve, 1000))
441+
}
442+
res.end()
443+
}
444+
```

0 commit comments

Comments
 (0)