Edge Functions Examples / Long-running Edge Functions

Long-running Netlify Edge Functions

Edge Functions are limited to 50ms of CPU time, but this does not include time spent waiting or making network calls. As long as a function returns headers within 40 seconds it can run indefinitely. If you need to make API calls or perform other work that takes longer than this, you can return a stream from the function and write to it when you have the data.

import type { Context } from "@netlify/edge-functions";

export default (request: Request, context: Context) => {
  const body = new ReadableStream({
    async start(controller) {
      // this might be an API call or other slow external operation
      const response = await doSomethingSlow();
      controller.enqueue(new TextEncoder().encode(response));
      controller.close()
    }
  });
  return new Response(body, {
    headers: {
      "Content-Type": "text/plain",
    },
  });
};

See this in action

Pro tip!

Need to send updates to the browser from a long-running edge function? Check out the server-sent events (SSE) example.

Explore more examples

What are Edge Functions?

Using JavaScript and TypeScript, Netlify Edge Functions give you the power to modify network requests to localize content, serve relevant ads, authenticate visitors, A/B test content, and much more! And this all happens at the Edge — directly from the worldwide location closest to each user.

To use Edge Functions on Netlify, add JavaScript or TypeScript files to an edge-functions directory in your project.

Learn more in the docs.


Deploy this site to Netlify

Try out Edge Functions on Netlify today! Click the button below to deploy this site with all of its demos to your Netlify account.

Deploy to Netlify