Streaming
Kaito supports streaming out of the box we let you return a Response with a ReadableStream body, but we also have built-in utilities for doing server-sent events (SSE).
SSE
SSE is a technology that allows you to stream data to the client in realtime. You can learn about it on MDN .
Kaito has a built-in utility for doing SSE, called sse. Return it from your route and Kaito will handle setting up the right headers and streaming everything to the client.
import {sse} from '@kaito-http/core/stream';
const stream = router.get('/', async ({ctx}) => {
return sse(async function* () {
yield {data: 'Hello, world!'};
await new Promise(resolve => setTimeout(resolve, 1000));
yield {data: 'Hello, world!'};
});
});Basic streaming
You can also return a response with a ReadableStream body.
router.get('/', async () => {
const stream = new ReadableStream<string>({
async start(controller) {
controller.enqueue('Hello, ');
await sleep(1000);
controller.enqueue('world!');
await sleep(1000);
controller.close();
},
});
return new Response(stream, {
headers: {'Content-Type': 'text/plain'},
});
});Last updated on