How to build edge functions

Before you begin

To get started and excel as an edge developer, it’s important to:

Azion Edge Functions works on the Azion Runtime, which is a set of tools that enable the development.

It’s paramount to take a look at the list of available APIs, methods, and types. Learn more about Azion Runtime.


Code Editor

The Edge Functions Code Editor provides a development experience similar to what developers are accustomed to. The Edge Functions ChatGPT Integration helps you to write, refactor, and review code.


Edge Functions and Edge Applications

To develop your first edge function for Edge Application:

  1. Access Azion Console > Edge Functions.
  2. Click + Edge Function.
  3. Choose a name for your function.
  4. Write your edge function. But wait, before that, keep reading:

Writing an edge function

First, the edge functions for edge applications work based on a fetch event. It’s initialized with an addEventListener function, passing fetch as the event type, and an event. For example:

  addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)); });

Second, it’s necessary to define the behavior of the handleRequest function. This function has the event.request as the signature. This data can be used later on to implement the necessary logic, such as:

  • Manipulate cookies.
  • Implement a behavior based on the request method (POST, GET, PUT, DELETE).
  • Access request metadata.

The handleRequest function can be defined as:

  const html = `<!DOCTYPE html> <body> <h1>Hello World</h1> <p>This markup was generated by Azion - Edge Functions.</p> </body>` async function handleRequest(request) { return new Response(html, { headers: { "content-type": "text/html;charset=UTF-8", }, }) }

In this example, the response will be the HTML content, declared previously by the const html. The headers can be manipulated as well, and in the example, the content type is set.

  1. Click the Save button.

Testing and Debugging

After writing your edge functions, you can preview the response and inspect the code. The preview simulates a request, and this simulation can be altered to meet the developer’s needs.

Learn more about Azion Preview Deployment.

It’s possible to debug the functions through:


Function instantiation

Once you’ve saved your edge function, it’s necessary to instantiate it in an edge application.

Learn more on how to instantiate an edge function on Edge Application.


Contributors