You can use Edge Functions to create a long-running service that can stream data to the browser using Server-Sent Events (SSE). While there is a 50ms limit on CPU time, time spent waiting for a response from an upstream service, or waiting for a timer to expire, does not count towards this limit. This means you can create a long-running service that can stream data to the browser.
Edge Functions are files held in the netlify/edge-functions
directory.
import type { Context } from "@netlify/edge-functions";
export default async (request: Request, context: Context) => {
let index = 0
const encoder = new TextEncoder();
const body = new ReadableStream({
start(controller) {
setInterval(() => {
controller.enqueue(encoder.encode(`data: Hello ${index++}\n\n`));
}, 1000);
},
});
return new Response(body, {
headers: {
"Content-Type": "text/event-stream",
},
});
};
You can deploy this and all the other examples in this repo as a site of your own to explore and experiment with, by clicking this button.