Skip to main content
100%

Stream OpenAI response though NextJS API route

✓ Published0🌍 Public
AAnsonT
Last edited May 15, 2023
Created on May 15, 2023

This example demonstrates a Next.js API route that streams an OpenAI chat response directly to the client. The code uses a custom handler with `NextApiRequest` and `NextApiResponse`, forwarding the request body’s `input` field as a user message to the OpenAI API. It sets `stream: true` to enable token-by-token delivery, then pipes the response body—a Node.js `Readable` stream—straight to the client via `Readable.fromWeb(response.body).pipe(res)`. The route checks an authorization header against an environment variable before calling `fetch` to `OPENAI_URL`, showing a secure server-side proxy pattern for streaming AI responses without exposing API keys.

AI-generated description

Similar vizzes