Skip to content

Latest commit

 

History

History

server-sent-events

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Netlify examples

Server-Sent Events (SSE) with Netlify Edge Functions

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.

Code example

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",
    },
  });
};

View this example on the web

Deploy to Netlify

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.

Deploy to Netlify