A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.netlify.com/edge-functions/api/ below:

Edge Functions API | Netlify Docs

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

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 one of the following:

For TypeScript, you can import the types for the Context and Config objects from @netlify/edge-functions. The types for the Request and Response objects are in the global scope.

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

export default async (request: Request, context: Context) => {

// ...

};

export const config: Config = {

path: "/",

};

Edge functions can handle requests in the following ways:

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.

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 () => {

return new Response("Hello, World!", {

headers: { "content-type": "text/html" }

});

};

You can use an edge function to return an HTTP redirect to any URL of your choice.

To do this, use the standard Response.redirect function, as shown in the example below.

export default async (req: Request, { cookies, geo }: Context) => {

if (

geo.city === "Paris" &&

cookies.get("promo-code") === "15-for-followers"

) {

const url = new URL("/subscriber-sale", req.url);

return Response.redirect(url);

}

};

Similar to our static routing engine, an edge function can also return a rewrite, which is a redirect with a 200 status code. This means that the URL in the visitor’s address bar remains the same, while Netlify’s servers fetch the new location behind the scenes.

To do this, return a standard URL object with the path you want to rewrite to.

export default async (request: Request, { cookies, geo }: Context) => {

if (

geo.city === "Paris" &&

cookies.get("promo-code") === "15-for-followers"

) {

return new URL("/subscriber-sale", request.url);

}

};

Same-site URLs only

Edge functions can rewrite to only same-site URLs. To fetch content hosted on another Netlify site or an external site, use the fetch Web API.

An edge function can act as middleware that modifies and returns the response of subsequent functions or requests. This kind of edge function calls context.next() 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 uses context.next() to transform the content of the HTTP response to the requested path:

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

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);

};

If you want to modify and return the content of a path other than the requested one, use fetch() to retrieve it.

export default async (req: Request) => {

const url = new URL("/welcome", req.url);

const res = await fetch(url);

return someTransformationFunction(res);

};

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

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);

};

If you want to read the request body in your edge function, you need to explicitly pass on a new request with an unused body when you call context.next() afterwards. For example, context.next(new Request(...)). Without this, attempts to read the request body in subsequent edge functions will cause an error because a request body can only be read once.

export default async (req: Request, context: Context) => {

const body = await req.json();

if (!isValid(body.access_token)) {

return new Response("forbidden", { status: 403 });

}

return context.next(new Request(req, { body: JSON.stringify(body) }));

};

Edge functions run in a Deno runtime environment that supports many standard Web APIs.

Edge Functions support Node.js built-in modules and Deno modules. Support for npm packages is in beta.

Edge functions have access to environment variables in the runtime environment. If you have the option to set specific scopes for your environment variables, the scope must include Functions to be available to edge functions during runtime. Learn more about how to set and use environment variables with functions.

When you import third-party modules in your edge function, it can be cumbersome to repeat the module’s full URL in every import statement.

To use module names in your import statements, use an import map file to map module URLs to names. Netlify edge functions support separate import map files instead of import maps defined in deno.json. You can place the import map file anywhere in the project directory. For example, this file maps html-rewriter to https://ghuc.cc/worker-tools/html-rewriter/index.ts:

{

"imports": {

"html-rewriter": "https://ghuc.cc/worker-tools/html-rewriter/index.ts"

}

}

To enable the import map, declare it in netlify.toml:

[functions]

deno_import_map = "./path/to/your/import_map.json"

You can now use html-rewriter as a shorthand for the module URL.

import { HTMLRewriter } from "html-rewriter";

export default async (request, context) => {

return new HTMLRewriter()

.on("p", {

element(element) {

element.tagName = "h1";

}

})

.transform(await context.next());

};

For TypeScript, you can import the types for the Context and Config objects from @netlify/edge-functions. The types for the Request and Response objects are in the global scope.

The Context object exposes the following properties:

An object containing Netlify team account information. The id property in the object holds the unique ID of the team that the site and function belong to.

A simplified interface for reading and storing cookies:

Setting cookies across subdomains requires a custom domain

Since the netlify.app domain is used by many customers, it is listed in the Mozilla Foundation’s Public Suffix List, which prevents setting cookies across subdomains.

An object containing Netlify deploy information with the following property:

An object containing geolocation data for the client with the following properties:

A string containing the client IP address.

Invokes the next item in the request chain. The method returns a Promise containing the Response from the origin that your edge function can modify before returning.

For best performance, you should only use this method if you need access to the response body. In all other cases, you do not need to explicitly call next.

The method accepts an optional options object with the following property:

Same method as above, except this one explicitly requires a Request object.

This variation allows you to read the request body in your edge function and then pass a new request object with an unread body to the next item in the request chain. Without this, the next() call could fail as a request body can only be read once.

An object containing the parameters set for the edge function’s path in the configuration object and the values they receive from the incoming request URL.

For example, for an edge function configured to run at /pets/:name, the params value for a request to /pets/winter will be {"name":"winter"}.

To access the query string, use request.url instead.

A string containing the Netlify request ID.

For example, 01FDWR77JMF2DA1CHF5YA6H07C.

An object containing server metadata with the following property:

An object containing Netlify site metadata with the following properties:

context.waitUntil() is a function that implements the ExtendableEvent.waitUntil standard. It allows you to extend the edge function’s execution until the given Promise it completed, without blocking the response to the client from being sent.

You can use it to perform any tasks after the response is sent, such as emitting analytics events or dispatching logs.

Usage notes:

This global object exposes the following properties:

The Netlify-specific context object.

This property is available within the scope of the function handler. If accessed from outside the handler, it returns null.

An object providing access to environment variables with the following properties:

Edge Functions support the following Web APIs:


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4