Skip to content

Streaming with Edge Functions

Fetch streamable data in Edge Functions to deliver faster responses

Edge Functions are available in Beta on all plans

Vercel Edge Functions support the Streams Web API, which allows you to read, write, transform, encode, and decode streams. You can also set your function responses to be streams, which will cause them to respond as data is transmitted in chunks, rather than wait until all the data is fetched.

To create an Edge Function that returns a readable stream, your Function's exported handler method should return a Reponse object that takes an instance of the ReadableStream interface as the first argument in its constructor. For example:

streaming-example.ts
export default async function handler(_) {
  const encoder = new TextEncoder();

  const customReadable = new ReadableStream({
    start(controller) {
      controller.enqueue(encoder.encode('Basic Streaming Test'));
      controller.close();
    },
  });

  return new Response(customReadable, {
    headers: { 'Content-Type': 'text/html; charset=utf-8' },
  });
}

The following example demonstrates an Edge Function that returns a ReadableStream object which contains an HTML page. The page says "Vercel Edge Functions + Streaming", and this code works in both JavaScript and TypeScript.

streaming-example.ts
export const config = {
  runtime: 'experimental-edge',
};

export default async function handler(_) {
  const encoder = new TextEncoder();

  const readable = new ReadableStream({
    start(controller) {
      controller.enqueue(
        encoder.encode(
          '<html><head><title>Vercel Edge Functions + Streaming</title></head><body>',
        ),
      );
      controller.enqueue(encoder.encode('Vercel Edge Functions + Streaming'));
      controller.enqueue(encoder.encode('</body></html>'));
      controller.close();
    },
  });

  return new Response(readable, {
    headers: { 'Content-Type': 'text/html; charset=utf-8' },
  });
}

The amount of data you can stream in an Edge Function is limited by its memory allocation, and execution duration. Exceeding these limits will cause your function to fail.

To learn more about the Streams API, and its concepts see the MDN docs: