/

How to Use Netlify Edge Functions: A Step-by-Step Guide

How to Use Netlify Edge Functions: A Step-by-Step Guide

Netlify Edge Functions are a powerful feature offered by Netlify, the popular hosting platform. While Netlify is known for static hosting, Edge Functions enable you to perform dynamic actions on your website. These functions allow you to implement features like geolocation, localization, A/B testing, redirects, and much more. Similar to Netlify Serverless Functions, Edge Functions run on the Netlify Edge, which means they are closer to the user and run on multiple CDN locations. Additionally, Edge Functions have a higher call limit of 3 million calls per month per site, compared to 125,000 calls per month per site for Serverless Functions.

To enable Edge Functions, you need to add a netlify.toml file to your website repository (if you don’t have one already) with the following content:

1
2
3
[[edge_functions]]
function = "hello"
path = "/hello"

In this configuration, function refers to the file name in the netlify/edge-functions/ directory without the .js extension, and path defines the URL path where the function will be available.

You can write your function in a file named hello.js inside the netlify/edge-functions/ directory:

1
export default () => new Response("Hello world")

The Response object allows you to send the response back to the client. Once you deploy your repository, you can access the result of the Edge Function using the URL https://<YOURSITEDOMAIN>/hello. During the deployment process, you can monitor the logs to ensure everything is working correctly.

To run and test Edge Functions locally, you can use the Netlify CLI netlify dev. Make sure your Netlify CLI is up to date by running npm i -g netlify-cli. Running the Edge Functions locally allows you to debug and test your code before deploying it.

You can customize the response headers, such as the content type, by passing a second parameter to the new Response() function:

1
2
3
export default () => new Response('Hello world', {
headers: { 'content-type': 'text/html' },
})

Edge Functions receive two arguments: request and context. The request object allows you to access all the request data, similar to using the Fetch API. The context object provides additional features like accessing cookies, geolocation data, JSON data, and logging. You can write logs using context.log():

1
2
3
export default (request, context) => {
context.log('test')
}

The Edge Functions logs can be viewed in the Netlify Edge Functions menu of your website. To return JSON data, you can use the context.json function:

1
2
3
export default (request, context) => {
return context.json({ hello: 'world' })
}

If you need to create multiple functions, you can add additional entries in the netlify.toml file:

1
2
3
4
5
6
7
[[edge_functions]]
function = "hello"
path = "/hello"

[[edge_functions]]
function = "second"
path = "/second"

You can use async functions if you plan to use promise-based APIs like the Fetch API to retrieve JSON data from a remote server or even display an image directly.

Edge Functions also provide access to the user’s location. Here’s an example of retrieving location data in the function:

1
2
3
4
5
6
7
8
export default async (request, context) => {
return new Response(`
Country code: ${context.geo?.country?.code}
Country name: ${context.geo?.country?.name}
City: ${context.geo?.city}
Subdivision: ${context.geo?.subdivision?.code} - ${context.geo?.subdivision?.name}
`)
}

It’s important to note that edge-specific features like geolocation only work on the edge, not locally.

Edge Functions can also work with cookies. You can set a cookie using the following code:

1
2
3
4
5
6
export default (request, context) => {
context.cookies.set({
name: "alreadyvisited",
value: "yes"
})
}

To read the value of a cookie, you can use context.cookies.get(), and to delete a cookie, context.cookies.delete().

If you need to access environment variables in your Edge Functions, you can use Deno.env.get('YOUR_VARIABLE'):

1
export default () => new Response(Deno.env.get('YOUR_VARIABLE'))

Netlify Edge Functions run on Deno, and you can learn more about Deno in a Deno tutorial.

In conclusion, Netlify Edge Functions provide a versatile way to add dynamic functionality to your website. They are especially useful when deploying apps built with frameworks like Next.js, Remix, or SvelteKit on Netlify. For more examples and information, you can explore the full examples library at https://edge-functions-examples.netlify.app and read the documentation about Web APIs you can use with Edge Functions at https://docs.netlify.com/netlify-labs/experimental-features/edge-functions/api/.

tags: [“Netlify”, “Edge Functions”, “Serverless Functions”, “CDN”, “geolocation”, “localization”, “A/B testing”, “redirects”, “Netlify CLI”, “Fetch API”, “cookies”, “Deno”]