Build an Edge Handler

This feature is in early access BETA.

Netlify supports Edge Handlers written in JavaScript. All handlers have a similar structure, and you can use them to intercept or manipulate an incoming HTTP request or to transform an HTTP response.

File naming

To set up your Edge Handlers, each file name should match its Edge Handler identifier. For example, a handler in logRequests.js will be identified as logRequests while a handler in filter-requests.js will be identified as filter-requests.

Edge Handler syntax

All Edge Handlers have the same function signature. Handlers export a function named onRequest that receives an event object with information about the request that the handler is processing. Edge Handlers fully support the ES2020 specification, so features like template literals, BigInt, and async/await are supported natively without having to use a JavaScript compiler like Babel.

Here's an example implementation:

// Log every incoming request URL
export function onRequest(event) {
  console.log(`Incoming request for ${event.request.url}`);
}

In the sample code above, the console logs each incoming request URL, and then requests execute normally to serve any assets associated with the request path.

Modify requests and responses

Edge Handlers allow you to intercept incoming HTTP requests, manipulate incoming requests to fetch different resources, and transform HTTP responses.

Intercept HTTP requests

Netlify Edge Handlers allow your site to intercept incoming HTTP requests and serve different content than what our Edge network would serve for a request that wasn't intercepted. This feature is useful if you want to prevent visitors from accessing specific content but you still want to give them something.

Here's an example of intercepting a request:

export function onRequest(event) {
  if (event.request.url.pathname === '/secret') {
    event.replaceResponse(() => {
      const response = new Response('<h1>Access denied</h1>', {
        headers: {
          'content-type': 'text/html'
        },
        status: 404,
      }, );

      return response;
    });
  }
}

The replaceResponse method takes a callback as an argument. The callback can be synchronous or asynchronous and produces the response that is sent to the client.

Manipulate HTTP requests

Requests received via an Edge Handler can be manipulated to fetch different resources than the ones our Edge network would serve by default. This feature allows changing query parameters, request paths, and headers. It doesn't allow modifying other request attributes like the HTTP method, request body, or protocol.

Here is an example of manipulating a request:

export function onRequest(event) {
  if (event.request.url.pathname === '/secret' && 
    !event.request.headers.get('Authorization') {
      let url = new URL(event.request.url);
      url.pathname = "/login";
      event.replaceResponse(() => fetch(url.href));
  }
}

In this example, if an incoming request to /secret doesn't include authorization information, the response points to /login.

Transform HTTP responses

You can also use Edge Handlers to transform default responses sent from the Edge network back to the browser in response to incoming requests.

Here's an example:

export function onRequest(event) {
  event.replaceResponse(async () => {
    const originResponse = await fetch(event.request);
    const transformation = new TransformStream({
      flush(controller) {
        const encoder = new TextEncoder();
        const buf = encoder.encode(
          "<p>Served from a Netlify Edge Handler</p>");
        controller.enqueue(buf);
      },
    });
	
    const transformedBody = originResponse.body.pipeThrough(transformation);
    const headers = {
      'Content-Type': 'text/html'
    };

    return new Response(transformedBody, {
      headers
    });
  });
}

In this example, the original response is transformed to an updated response body that includes Served from a Netlify Edge Handler.

Helper objects

The Edge Handlers runtime environment includes objects to help you work with handlers.

Console

The console object enables logging information about Edge Handlers as they execute. You can inspect the output of these calls in the Edge Handler logs in the Netlify UI.

These exported console methods are available:

  • assert()
  • debug()
  • error()
  • info()
  • log()
  • warn()

Here's an example using a console method within an Edge Handler:

export function onRequest(event) {
  console.log(`incoming request for ${event.request.path}`);
}

URL

The URL object enables working with resource locations. This object is compatible with the core JavaScript URL object.

Here's an example using the URL object to create a new URL to fetch content from:

export function onRequest(event) {
  let url = new URL("https://api.github.com");
  url.pathname = "/emojis";
  event.replaceResponse(() => fetch(url.href));
}

URLSearchParams

The URLSearchParams object holds search parameters key/value pairs. This object uses the application/x-www-form-urlencoded format to serialize the query parameters as described in the URL standard.