Streaming API Response
Stream long-running API responses using ReadableStream and TransformStream for real-time data delivery.
import { NextRequest } from 'next/server';
export const runtime = 'edge';
export async function GET(_request: NextRequest) {
const encoder = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
const items = ['Processing...', 'Fetching data...', 'Analyzing...', 'Complete!'];
for (const item of items) {
controller.enqueue(
encoder.encode(`data: ${JSON.stringify({ message: item, timestamp: Date.now() })}\n\n`)
);
await new Promise((r) => setTimeout(r, 1000));
}
controller.enqueue(encoder.encode('data: [DONE]\n\n'));
controller.close();
},
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
});
}
// Client usage:
// const res = await fetch('/api/stream');
// const reader = res.body!.getReader();
// const decoder = new TextDecoder();
// while (true) {
// const { done, value } = await reader.read();
// if (done) break;
// console.log(decoder.decode(value));
// }Use Cases
- AI response streaming
- Progress updates
- Server-sent events
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Python Streaming Data Processing
Process streaming data with generators, windowed aggregation, and memory-efficient line-by-line reading.
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Edge Middleware Geolocation
Use Vercel Edge geolocation headers to personalize content based on the visitor's country and city.
Edge Middleware Rate Limiter
Rate limit API requests at the edge using a sliding window counter with configurable thresholds.