Netlify Edge Functions

Guide for writing Netlify Edge Functions. Use when building middleware, geolocation-based logic, request/response manipulation, authentication

What Is This?

Overview

Netlify Edge Functions are lightweight compute units that run on Netlify's globally distributed edge network, powered by the Deno runtime. Unlike traditional serverless functions that execute in a single region, edge functions run in data centers closest to the end user, dramatically reducing latency and improving response times. They intercept HTTP requests before they reach your origin server, allowing you to modify, redirect, or respond to traffic at the network edge.

Edge functions are written in TypeScript or JavaScript and follow the Deno module system. They support modern web APIs such as the Fetch API, URL, and Request/Response interfaces. Because they execute before content is served, they are ideal for tasks that require low-latency decision-making, such as authentication checks, content personalization, and request routing.

The Deno runtime used by Netlify Edge Functions provides a secure, sandboxed execution environment with built-in TypeScript support and no need for a separate build step. This makes development faster and deployment simpler compared to Node.js-based serverless alternatives.

Who Should Use This

  • Frontend developers building personalized user experiences based on location or session data
  • Full-stack engineers who need middleware logic without managing dedicated server infrastructure
  • Security engineers implementing authentication and authorization at the network layer
  • Growth and product teams running A/B tests or feature flag experiments at scale
  • Platform engineers optimizing global application performance and reducing origin server load
  • Developers building multi-tenant applications that require request routing based on subdomain or header values

Why Use It?

Problems It Solves

  • High latency caused by routing all requests through a single-region serverless function or origin server
  • Complex middleware logic that is difficult to manage inside application code or framework configuration
  • Geolocation-based content delivery that previously required third-party services or server-side rendering
  • Authentication checks that add round-trip delays when handled at the application layer
  • A/B testing implementations that require consistent, low-overhead request splitting without client-side flicker

Core Highlights

  • Runs on Deno runtime with native TypeScript support and no build configuration required
  • Executes at the network edge, close to the user, for sub-millisecond decision-making
  • Supports the context.next() pattern for composable middleware chains
  • Provides built-in geolocation data on every incoming request via the context object
  • Integrates natively with Netlify's routing and redirect system
  • Supports request and response transformation, including header manipulation and body rewriting
  • Compatible with standard web platform APIs for portability and familiarity
  • Deployable per route or globally using the netlify.toml configuration file

How to Use It?

Basic Usage

Create a file in the netlify/edge-functions/ directory. The function must export a default handler.

// netlify/edge-functions/hello.ts
import type { Context } from "https://edge.netlify.com";

export default async function handler(request: Request, context: Context) {
  return new Response("Hello from the edge", { status: 200 });
}

Register the function in netlify.toml:

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

Specific Scenarios

Geolocation-based redirects: Use the context object to read the user's country and redirect accordingly.

export default async function handler(request: Request, context: Context) {
  const country = context.geo?.country?.code ?? "US";
  if (country === "DE") {
    return Response.redirect("https://example.com/de", 302);
  }
  return context.next();
}

Authentication middleware: Validate a token before allowing access to protected routes.

export default async function handler(request: Request, context: Context) {
  const token = request.headers.get("Authorization");
  if (!token || token !== `Bearer ${Deno.env.get("SECRET_TOKEN")}`) {
    return new Response("Unauthorized", { status: 401 });
  }
  return context.next();
}

Real-World Examples

  • Serving localized pricing pages based on the visitor's detected country without a backend API call
  • Injecting custom response headers for security policies such as Content Security Policy across all routes

When to Use It?

Use Cases

  • Redirecting users to region-specific content based on geolocation data
  • Enforcing authentication before serving protected static assets or API routes
  • Running A/B tests by splitting traffic at the edge without modifying application code
  • Rewriting request URLs dynamically based on query parameters or headers
  • Adding or removing HTTP headers before responses reach the client
  • Personalizing content for returning users based on cookie values
  • Rate limiting or blocking requests from specific IP ranges

Important Notes

Requirements

  • A Netlify account with a connected site repository
  • Functions must be placed in the netlify/edge-functions/ directory
  • Route bindings must be declared in netlify.toml or using the config export
  • Environment variables must be configured in the Netlify dashboard or CLI