I’m having trouble with streaming responses from OpenAI in my Next.js app. Following a tutorial that used the old toAIStreamResponse() method, but now I need to use toDataStreamResponse() since the old one is deprecated.
Here’s my current setup:
import { openai } from "@ai-sdk/openai";
import { streamText } from "ai";
export const maxDuration = 30;
export async function POST() {
const userQuery = "provide me alternatives for the word energetic";
const response = streamText({
model: openai("gpt-4o"),
prompt: userQuery,
});
console.log("Stream response:", response.toDataStreamResponse());
return response.toDataStreamResponse();
}
My environment file contains:
OPENAI_API_KEY=abc123def456ghi789jkl012mno345
The API key seems to be detected automatically by the OpenAI SDK. However, when I log the result from toDataStreamResponse(), the stream body always shows as undefined:
body: { stream: undefined, source: null, length: null }
How can I fix this to get actual data in the body.stream property?
yeah, this happens often - undefined stream in console is normal. you gotta remember that toDataStreamResponse() gives a ReadableStream that the client uses. instead of console.log on it directly, try logging response.textStream first to see if there’s any data.
The undefined stream body is actually working fine. I ran into this exact same issue months ago and spent hours thinking I’d broken something. Turns out ReadableStreams don’t show their content in console.log - that’s just how they work. The stream gets consumed by the browser or client making the request, not by your server-side logging. Your code looks right to me. The problem isn’t your implementation, it’s how you’re trying to inspect it. Want to verify it’s working? Make an actual HTTP request to your endpoint from a frontend component or testing tool. The data will flow to the client just fine even though your server logs show undefined.
That’s expected behavior - console.log won’t show anything useful for ReadableStreams. They’re meant to be consumed once and streamed to the client, not logged. Your code looks right. The stream works fine when your frontend consumes it, even though logging shows undefined. Want to test it? Hit your endpoint from the client or use Postman to see the actual streaming response. toDataStreamResponse() creates a proper Response object that browsers handle correctly for streaming.