Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท Serverless and Edge Functions

Edge Functions and Middleware

Run code at the edge, close to visitors: Netlify Edge Functions on Deno, Vercel Routing Middleware, geolocation, redirects, A/B tests and auth checks, and when to avoid the edge.

A regular serverless function runs in one region you choose. Edge functions run in many locations, near the visitor, and execute before the cached response is returned. They are ideal for quick decisions that must happen on every request: redirect by country, pick an A/B variant, check a cookie, rewrite a path or add a header.

The trade-off is a smaller runtime: edge code has tight limits on time, memory and which APIs exist. Think of it as a very fast gatekeeper, not a place for heavy work.

Where edge code runs in the request path

Edge in the request path

Visitor Sends a request.
Edge code Inspects, rewrites or answers.
Cache or origin Static file or function.

Edge code sees the request first.

1 / 2

Netlify Edge Functions

Netlify Edge Functions run on the Deno runtime. Files live in netlify/edge-functions. The signature mirrors normal functions:

JavaScript
// netlify/edge-functions/geo-greeting.js
export default async (request, context) => {
  const country = context.geo?.country?.code ?? "unknown";
  const response = await context.next();   // continue to the normal page
  response.headers.set("x-visitor-country", country);
  return response;
};

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

Key points:

  • context.next() passes the request on to the next step (your static page or function) and gives you its response, which you can change.
  • Return a Response directly instead to answer without calling next().
  • config.path chooses which URLs trigger it; you can also exclude paths with excludedPath.
  • Use Netlify.env.get("NAME") for variables.
  • Import from URLs or npm: specifiers as Deno supports; check current docs for bundling details.

Vercel Routing Middleware

On Vercel the equivalent is Routing Middleware: a middleware.js (or .ts) file in the project root (in some framework versions the file has a different name or lives elsewhere, so check your framework's current guide). It runs before the request reaches your pages or functions.

JavaScript
// middleware.js
import { NextResponse } from "next/server";

export function middleware(request) {
  const country = request.headers.get("x-vercel-ip-country") ?? "unknown";
  if (country === "DE" && request.nextUrl.pathname === "/") {
    return NextResponse.rewrite(new URL("/de", request.url));
  }
  return NextResponse.next();
}

export const config = { matcher: ["/", "/pricing"] };

That example uses the Next.js helper API. For frameworks other than Next.js, Vercel offers a framework-agnostic package for middleware (@vercel/functions and @vercel/edge provide helpers); read the current docs for your stack. The matcher limits where it runs, which also saves cost.

Vercel functions can themselves opt into the edge runtime in some frameworks (for example export const runtime = "edge" in a Next.js route), though many projects now prefer the standard Node.js runtime unless low latency at the edge matters. Check current guidance.

Writing portable edge logic

The core logic is only Request in, Response or "continue" out, and you can test that logic with no platform. This stand-in implements a small middleware pipeline: geo redirect, A/B cookie and a header. The wiring (context.next() and NextResponse) differs between platforms; the decision code does not.

Node.js Middleware pipeline (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Applying the decision

An adapter turns the instruction into platform actions. Here is the Netlify-shaped version, so you can see how little glue is needed.

Node.js Adapter for an edge function (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Limits and when not to use the edge

  • Limited APIs. No full Node.js standard library and no long CPU work; heavy libraries may not run.
  • Short execution budget. Keep it to a few milliseconds of work.
  • Data far away. If your database sits in one region, an edge function in another continent makes a slow round trip. Edge is best when it needs no data or reads from a replicated, edge-friendly store.
  • Runs on every matching request. A broad path or matcher adds latency and cost to everything. Narrow it.
  • Hard to debug in production. Log sparingly and test the decision logic locally.

Prefer a normal serverless function for database-heavy work, long tasks and large dependencies.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main benefit of edge functions?

    Edge code runs near the visitor and sees every matching request first.
  2. 2. Which runtime do Netlify Edge Functions use?

    Netlify Edge Functions run on Deno.
  3. 3. In Netlify edge code, what does context.next() do?

    It continues to the normal page or function and gives you the response.
  4. 4. When should you avoid an edge function?

    Heavy work belongs in a regular serverless function near your data.

Summary

  • Edge code runs near the visitor before the page or function, ideal for redirects, rewrites, A/B tests and light checks.
  • Netlify Edge Functions (Deno) use context.next(); Vercel uses Routing Middleware with a matcher.
  • Keep decision logic as plain Request to instruction code so you can test it anywhere.
  • Narrow the path or matcher and keep work tiny.
  • Use regular serverless functions for heavy, data-bound work.

Next: Scheduled and Background Functions