Edge Functions API

This feature is in BETA.

This page provides an overview of key concepts as well as a full reference.

# Overview

Use TypeScript or JavaScript to create an edge function file that exports a default function responsible for processing a request.

When the function is invoked, it receives two arguments:

The expected return value is either a standard Response object representing the HTTP response to be delivered to the client or undefined if you choose to bypass the current function.

For TypeScript, you can import the types for the Context object from https://edge.netlify.com. The types for the Request and Response objects are in the global scope.

import type { Context } from "https://edge.netlify.com";
export default async (request: Request, context: Context): Promise<Response> => {
    // ...
}

# Request handling

Edge functions can handle requests in two different ways - by returning a response directly as an endpoint or by modifying a response as middleware.

Looking for a list of available request headers?

Netlify doesn’t add specific headers to edge function requests. To find information about the client request, use the context object instead.

# Return a response

Similar to serverless functions and other endpoints, an edge function can just return a standard Response object. Once the function returns the response, the request chain ends and any redirects declared for that path do not occur.

For example, this edge function returns the string Hello, World! as text/html:

export default async (request: Request) => {
  return new Response("Hello, World!", {
    headers: { "content-type": "text/html" },
  });
};

# Modify a response

An edge function can act as middleware that modifies and returns the response of subsequent functions or requests. This kind of edge function calls either context.next() or context.rewrite() to continue the request chain and waits for a response to return before finishing execution.

Any edge functions that return undefined or use an empty return; also continue the request chain.

Once all edge functions for the initial path run, Netlify evaluates any redirect rules declared for that path and then continues the request chain to eventually serve static content or return a response from a serverless function. For more details on the order of events, review our docs on the declaration processing order.

For example, this edge function transforms the content of an HTTP response:

import { Context } from "https://edge.netlify.com";

export default async (request: Request, context: Context) => {
  const url = new URL(request.url);

  // Look for the query parameter, and return if we don't find it
  if (url.searchParams.get("method") !== "transform") {
    return;
  }

  const response = await context.next();
  const text = await response.text();

  return new Response(text.toUpperCase(), response);
};

When using context.next() to transform a response, we modify the request to the downstream asset so that conditional requests don’t apply and you always get a full response back.

If you want full control over the client caching behavior and you’d like to use conditional requests, you should pass the sendConditionalRequest to the context.next() call.

export default async (req: Request, { next }: Context) => {
  const res = await next({sendConditionalRequest: true});

  // If the response is a 304, it’s cached in the client and we can return it
  if (res.status === 304) {
    return res;
  }
  
  // Transform the response however you need
  const text = await res.text();

  return new Response(text.toUpperCase(), res);
};

# Runtime environment

Edge functions run in a Deno runtime environment that supports many standard Web API and open-source Deno endpoints. Deno does not use Node modules, or support Node APIs, but instead can load modules directly from URLs.

# Reference

This reference covers the following:

You may encounter undocumented APIs as you work with Edge Functions. These are not supported in any way and you should not use them. Using undocumented APIs may lead to unexpected or broken functionality.

# Netlify-specific Context object

The Context object exposes the following properties:

  • account: an object containing Netlify team account information with the following property:
    • id: unique ID of the team that the site and function belong to.
  • cookies: a simplified interface for reading and storing cookies:
    • cookies.get(name): reads a cookie with a given name from the incoming request.
    • cookies.set(options): sets a cookie on the outgoing response, using the same format as the options value in the CookieStore.set web standard.
    • cookies.delete(name) or cookies.delete(options): adds an instruction to the outgoing response for the client to delete a cookie. Following the CookieStore.delete web standard, accepts a string representing the name of the cookie, or an options object.
  • geo: an object containing geolocation data for the client with the following properties:
    • city: name of the city.
    • country:
      • code: ISO 3166 code for the country.
      • name: name of the country.
    • latitude: latitude of the location.
    • longitude: longitude of the location.
    • subdivision:
      • code: ISO 3166 code for the country subdivision.
      • name: name of the country subdivision.
    • timezone: timezone of the location.
  • ip: a string containing the client IP address.
  • json(value): a convenience method for returning a JSON-encoded response.
  • log(...values): a convenience method for outputting a log message associated with the current edge function. Recommended over console.log because context.log output indicates which edge function generated the log message.
  • next(): invokes the next edge function in the chain if there is one. If there are no more edge functions, the next step is evaluating redirect rules before serving static content or returning responses from Netlify Functions. You should only use next() if you need access to the response body for tasks like transforming it. The function returns a Promise containing the Response from the origin that can be modified before returning. If you want to bypass the current function, you should use an empty return.
  • requestId: a string containing the Netlify request ID; for example, 01FDWR77JMF2DA1CHF5YA6H07C.
  • rewrite(url): a convenience method for rewriting the incoming request to another same-site URL with a 200 status code; accepts a URL object, a full URL as a string, or a relative URL as a string. You cannot rewrite to a different domain, attempts to do so will fail with an error.
  • site: an object containing Netlify site metadata with the following properties:
    • id: unique ID for the site; for example, 1d01c0c0-4554-4747-93b8-34ce3448ab95.
    • name: name of the site, its Netlify subdomain; for example, petsof.
    • url: URL representing the main address to your site. It can be either a Netlify subdomain or your own custom domain if you set one; for example, https://petsof.netlify.app or https://www.petsofnetlify.com.

# Web APIs

Edge Functions support the following Web APIs:

# Deno APIs

Edge Functions support the following open-source Deno APIs:

  • Deno.env: interact with environment variables
    • get(key): get the value of an environment variable
    • toObject(): get all environment variables as an object
  • Deno.connect: connect to TCP sockets
  • Deno.connectTls: connect to TCP sockets using TLS
  • Deno.resolveDns: make DNS queries