New syntax for rewrites in Edge Functions

One of the common use cases for Edge Functions is redirecting clients to a different URL path based on certain conditions defined programmatically. In addition to a standard HTTP redirect, you can choose to return a redirect with a 200 status code, which means that the URL in the visitor’s address bar remains the same, while Netlify’s servers fetch the new location behind the scenes.

This is commonly called a rewrite and has been available via the rewrite method in the Netlify context object. We’re deprecating this method and introducing a new syntax to represent rewrites.

The old method is still supported, so your existing code will continue to work. But the new API is more performant and more aligned with web platform standards, so we encourage you to adopt it. Read below to learn how.

Returning a rewrite

If you want to terminate the response with a rewrite to another path, your function should return a standard URL object with the new URL.

For example, the snippet below returns a redirect to the /sale path if the client is accessing your site from Paris and they have a promo-code cookie with the value baguette.

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

export default async (req: Request, { cookies, geo }: Context) => {
  if (
    geo.city === "Paris" &&
    cookies.get("promo-code") === "baguette"
  ) {
    return new URL("/sale", request.url);
  }
};

export const config: Config = {
  path: "/"
};

Transforming a page

If you want to return a transformed version of another path, you should retrieve its contents using the standard fetch method and modify the response as needed.

Any edge functions that are configured to run on that patch will be invoked.

Let’s modify our example to show how we could render the /sale path but transform its contents such that every instance of the word baguette is replaced with the :baguette_bread: emoji.

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

export default async (req: Request, { cookies, geo }: Context) => {
  if (
    geo.city === "Paris" &&
    cookies.get("promo-code") === "baguette"
  ) {
    const newURL = new URL("/sale", req.url);
    const res = await fetch(newURL);
    const text = await res.text();
  
    return new Response(text.replaceAll("baguette", "🥖"), res);
  }
};

export const config: Config = {
  path: "/"
};

If you use Netlify Build, you can start to use this syntax immediately. If you deploy using the Netlify CLI, make sure you upgrade to version 13.12.0 or above.

You can find more information about the Edge Functions API in our documentation pages. If you have any questions or want to report any issues, please let us know in this thread.

2 Likes