MCPInstall

netlify-edge-functions

Write, route, cache, and debug Netlify Edge Functions, the Deno-based TypeScript or JavaScript handlers in netlify/edge-functions that run at the network edge in front of static files and serverless functions. Activate this skill whenever someone wants to add auth middleware or a login gate, redirect or rewrite visitors by country or cookie, localize or personalize a page with geolocation, run A/B testing, transform or inject HTML into a response, stream server-side rendering at the edge, or cache an edge response. Also use it when an edge function silently does nothing, runs in the wrong order, ignores its Cache-Control headers, or cannot read an environment variable.

Installs
3.1K
Last 24h
+24
Trending rank
#5031
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/netlify/context-and-tools --skill netlify-edge-functions
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads netlify-edge-functions automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Netlify Edge Functions

Use this form

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

export default async (request: Request, context: Context) => {
  return new Response(`Hello from ${context.geo.country?.name ?? "somewhere"}`);
};

export const config: Config = { path: "/hello" };
  • One file = one function: a default-export handler plus a config export with the route. Alternatively, declare the route in netlify.toml.
  • Request and Response are global. Import Context and Config types from @netlify/edge-functions.
  • Read env vars with Netlify.env.get(). process.env works only for Next.js middleware.

Avoid these:

  • A file with no config.path or pattern and no [[edge_functions]] entry. It deploys but never runs.
  • Import maps in deno.json. They are unsupported. Use a separate file with [functions] deno_import_map.
  • Variables set in netlify.toml. They are invisible to edge functions.
  • Netlify.env.set() or Netlify.env.delete() as persistence. They affect only the current invocation.
  • fetch() to the same site for the current path. Use context.next() instead.

⚠️ Footguns

  • No route = silent no-op. Edge functions get no automatic URL.
  • path: "/*" runs on every request, including assets. Narrow it, or add excludedPath.
  • Caching needs both parts: cache: "manual" in config AND cache headers on the returned Response. With only one, nothing is cached.
  • Cached functions shadow static files. A cached function on /* serves /cat.png instead of the file.
  • Returning a Response ends the chain. Redirect rules for that path never run.
  • Same-site fetch() and URL rewrites start a new request chain. Matching edge functions run again. Use context.next() to reach the static asset or serverless function at the same path.
  • The request body can be read once. After await req.json(), pass new Request(req, { body }) to context.next().
  • Same-named foo.ts and foo.js: the TS file is ignored and the JS file deploys.
  • 50 ms CPU per request, including waitUntil work.
  • Not executed on sites with Split Testing enabled.
  • Custom Headers and basic-auth headers do not apply to edge functions.
  • Not supported on HIPAA-compliant hosting.
  • netlify.app is on the Public Suffix List. Cross-subdomain cookies need a custom domain.

Files

WhatWhere
Functions<base>/netlify/edge-functions/*.{js,ts,jsx,tsx}
Custom dir[build] edge_functions = "my-dir" (relative to base dir; keep it outside the publish dir)
Name in tomlfile name without extension (auth.ts → function = "auth")
Import mapany JSON file, referenced by [functions] deno_import_map = "./import_map.json"

Return values

ReturnEffect
Responsesent to client; chain ends
URLsame-site rewrite, 200, address bar unchanged
undefined / return;skip this function; chain continues

Endpoint

export default async () =>
  new Response("Hello, World!", { headers: { "content-type": "text/html" } });
export const config = { path: "/api/hello" };

Redirect / rewrite

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

export default async (req: Request, { cookies, geo }: Context) => {
  if (geo.city === "Paris" && cookies.get("promo-code") === "15-for-followers") {
    return Response.redirect(new URL("/subscriber-sale", req.url)); // redirect
    // or: return new URL("/subscriber-sale", req.url);             // rewrite (same-site only)
  }
};
export const config = { path: "/sale" };

Rewrites must target the same site. To reach other sites, use fetch.

Middleware (modify origin response)

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

export default async (request: Request, context: Context) => {
  if (new URL(request.url).searchParams.get("method") !== "transform") return;
  const response = await context.next();
  return new Response((await response.text()).toUpperCase(), response);
};
export const config = { path: "/blog/*" };

Call context.next() only when you need the response body. If you just return undefined, the chain continues on its own.

Conditional requests

export default async (req: Request, { next }: Context) => {
  const res = await next({ sendConditionalRequest: true });
  if (res.status === 304) return res;
  return new Response((await res.text()).toUpperCase(), res);
};

By default, next() strips conditional headers, so it always returns a full response.

Read body, then continue

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

Netlify user gate (private / team-login-protected projects)

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

export default async (req: Request, context: Context) => {
  const user = context.user; // undefined: public project, password protection, netlify dev
  if (!user) return new Response("Forbidden", { status: 403 });
  const allowed = (Netlify.env.get("ADMIN_USER_IDS") ?? "").split(",");
  if (!allowed.includes(user.id)) return new Response("Forbidden", { status: 403 });
  // user.email may be undefined, so use it for display only
};
export const config: Config = { path: "/admin/*" };

Post-response work

export default async (req: Request, context: Context) => {
  context.waitUntil(fetch("https://analytics.example.com/event", { method: "POST" }));
  return new Response("ok");
};

waitUntil does not block the response, but it still counts against the 50 ms CPU limit.

Streaming SSR (.tsx)

import React from "https://esm.sh/react";
import { renderToReadableStream } from "https://esm.sh/react-dom/server";
import type { Config, Context } from "@netlify/edge-functions";

export default async (req: Request, context: Context) => {
  const stream = await renderToReadableStream(
    <html><body><h1>Hello {context.geo.country?.name}</h1></body></html>
  );
  return new Response(stream, { headers: { "Content-Type": "text/html" } });
};
export const config: Config = { path: "/hello" };

Context

PropertyNotes
cookies.get(name) / .set(options) / .delete(name | options)set and delete use CookieStore option format; they act on the outgoing response
geocity, country.{code,name}, subdivision.{code,name}, latitude, longitude, timezone, postalCode (format varies)
ipclient IP
next(options?) / next(request, options?)Promise<Response> from the next item in the chain
paramsURLPattern named groups from path (/pets/:name → { name }). For the query string, use request.url
user{ id, email?, expiresAt } or undefined. It is a Netlify account, not Netlify Identity; for Identity, use getUser() from @netlify/identity
waitUntil(promise)runs after the response is sent
requestId, account.id, server.region—
site{ id, name, url }
deploy{ context, id, published, skewProtectionToken }

Netlify adds no client-info headers to the request. Read client info from context instead.

Netlify.context gives the same object, but only inside the handler. Outside it, it is null.

Netlify.env: get(name), has(name), toObject(), and invocation-scoped set and delete. To change variables persistently, use the env API.

Web APIs:

  • console, atob, btoa
  • fetch, Request, Response, URL, File, Blob
  • TextEncoder/TextDecoder (and their Stream variants), Performance
  • Web Crypto: randomUUID, getRandomValues, SubtleCrypto
  • WebSocket
  • setTimeout, clearTimeout, setInterval
  • Streams: ReadableStream, WritableStream, TransformStream
  • URLPattern

Modules:

  • Node built-ins: use the node: prefix (import { randomBytes } from "node:crypto").
  • Deno modules: import by URL, or through an import map.
  • npm packages (beta): import by name. Packages with native binaries or runtime dynamic imports may break.

Declarations

Inline config

KeyValue
pathURLPattern string or array; must start with /
excludedPathURLPattern string or array; must start with /
pattern / excludedPatternregex alternatives to path / excludedPath
methodHTTP method string or array
header{ name: true | false | "regex" }; case-insensitive names; multi-value headers match the comma-joined list
onError"fail" (default), "/custom-path", or "bypass"
cache"manual"
export const config: Config = {
  path: "/*",
  excludedPath: ["/*.css", "/*.js", "/img/*"],
  header: { "user-agent": "(iPhone|Android)" },
};

The netlify-agent-category request header maps any user-agent to a client category.

netlify.toml

The toml form supports function, path, excludedPath, pattern, excludedPattern, [edge_functions.header], and cache. Set onError inline. Use toml when you need explicit ordering of several functions on one path.

[[edge_functions]]
  path = "/admin"
  function = "auth"

[[edge_functions]]
  path = "/admin"
  function = "injector"
  cache = "manual"

[[edge_functions]]
  pattern = "/products/(.*)"
  excludedPattern = "/products/things/(.*)"
  function = "highlight"

[[edge_functions]]
  path = "/*"
  excludedPath = "/img/*"
  function = "common"
  [edge_functions.header]
  x-required = true
  x-forbidden = false

A request to /admin runs auth, then common, then injector.

Order

Netlify walks the following order twice for the request path. The first pass runs only functions without caching configured. The second pass runs only cached functions.

  1. Framework-generated functions declared in a config file.
  2. Your netlify.toml declarations, top to bottom.
  3. Framework- and integration-generated inline declarations.
  4. Your inline declarations, alphabetical by file name.

If the same function is declared both in toml and inline, the configs are merged and treated as step 4; inline wins for duplicate fields.

After the edge functions, redirect rules run, unless a function already returned a Response. A redirect to a new path repeats the whole process for that path.

An edge function declared on the target of a static rewrite does not run for rewritten requests.

Response caching

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

export default async () =>
  new Response("Hello world", { headers: { "cache-control": "public, s-maxage=3600" } });

export const config: Config = { path: "/hello", cache: "manual" };
  • Headers must be set in the function code. Supported headers:
    • Cache-Control, CDN-Cache-Control, Netlify-CDN-Cache-Control
    • Expires (overridden by max-age/s-maxage)
    • Vary, Netlify-Vary
  • See caching overview.
  • A new deploy in the same deploy context invalidates cached responses.
  • Cached hits skip invocation, and they do not count toward invocation limits.
  • Cache reusable endpoint output, such as SSR.
  • Don't cache routing or personalization middleware, such as cookie-based product ordering.
  • Local dev has no cache. Cache headers are ignored locally.

Error handling (onError)

ValueEffect
"fail" (default)chain stops; generic error page is shown
"/unavailable"rewrite to that same-site path; edge functions on it are not invoked
"bypass"skip the failing function; chain continues

Fail closed for critical logic: use the default for internal auth, or a custom path for customer-facing auth. Fail open (bypass) for nice-to-haves such as localization.

Environment variables

  • Variables must have the Functions scope.
  • Build-scoped variables exist only at build time; embed their values during the build if needed.
  • Changing a variable requires a new deploy.
  • Deploy info (site, region, deploy id) comes from context, not from env vars.

Local dev / deploy / logs

  • Run npm install netlify-cli -g, then netlify dev. Visit http://localhost:8888/<path>.
    • Changes apply on the next request.
    • Debug with --edge-inspect or --edge-inspect-brk.
    • Mock location with --geo=mock (San Francisco), or --geo=mock --country=DE.
    • context.user is undefined locally.
  • Manual deploys require CLI ≥ 12.2.8. Deploys are atomic, and Deploy Previews and rollbacks include edge functions.
  • Logs: in the Netlify UI, go to Cloud compute > Edge functions (https://app.netlify.com/projects/{site_name}/edge-functions).
    • For older deploys: Deploys → open the deploy → Edge Functions.
    • console.log output is tagged with the function name.
    • Retention is ≥ 24 h (7 days on some plans).
    • Log Drains are available on Enterprise plans.

Limits

LimitValue
Bundle size20 MB compressed
Memory (per set of deployed functions)512 MB
CPU time per request50 ms (excludes I/O wait)
Response header timeout40 s
  • Prerendering does not apply to paths served by an edge function.
  • Multiple framework plugins that generate edge functions may collide.

Docs: API · Declarations · Optional configuration · Limits · Examples

<!-- Gaps: no legacy/deprecated handler form is documented; whether `method` works in netlify.toml is unstated. --> <!-- Undocumented: context.params with regex `pattern` declarations; monthly invocation limits per plan. --> <!-- system: agent-context/edge-functions/system.md — human-owned, merged by ctx-gen; edit system.md, not this section -->

Netlify house rules (edge-functions)

These are org conventions and field-learned guardrails, not docs facts — they are merged into the rendered skill by ctx-gen and are never generated. Extracted from the previous hand-written netlify-edge-functions skill; owned by the skills maintainer.

  1. Check the framework's adapter/reference first: a custom edge function that duplicates adapter-generated middleware causes conflicts. Only hand-write an edge function when the framework doesn't already generate one for the job.
  2. Scope path narrowly. path: "/*" intercepts every request — including static assets — adding latency to each one and billing an edge invocation for it.
  3. An edge function without a route (no config export, no netlify.toml declaration) still deploys, but silently never runs: no build error, no warning. When "my edge function does nothing", check the route first.
  4. Choose edge vs serverless by workload shape: edge functions for low-latency request/response manipulation, geolocation logic, auth checks/redirects, and A/B personalization; serverless functions for long-running work (up to 15 min), heavy Node.js dependencies, database-heavy operations, background/scheduled tasks, or memory needs above 512 MB.
  5. Cache headers on an edge response do nothing without cache: "manual" in config — it's both or neither. Setting Cache-Control on the returned Response has no effect unless the function also opts in.
  6. When explaining declaration processing order, state the two-pass loop, not just the ordering: Netlify runs the whole declaration order TWICE — first pass runs only edge functions not configured for caching, second pass runs the ones with caching configured. "Non-cached before cached" without the loop framing is an incomplete answer.
  7. On a private project or one with team login protection, context.user is the Netlify user who made the request (id, email, expiresAt). Use it for per-person checks and personalization instead of adding a second login, and never take identity from client-sent headers or cookies: Netlify verifies the login before the edge function runs. Every example must handle context.user being undefined (public projects, basic password protection, netlify dev), and email can be undefined too, so key decisions on id. This is a Netlify account, not a Netlify Identity user.

FAQ

What does the netlify-edge-functions skill do?

Write, route, cache, and debug Netlify Edge Functions, the Deno-based TypeScript or JavaScript handlers in netlify/edge-functions that run at the network edge in front of static files and serverless functions. Activate this skill whenever someone wants to add auth middleware or a login gate, redirect or rewrite visitors by country or cookie, localize or personalize a page with geolocation, run A/B testing, transform or inject HTML into a response, stream server-side rendering at the edge, or cache an edge response. Also use it when an edge function silently does nothing, runs in the wrong order, ignores its Cache-Control headers, or cannot read an environment variable.

How do I install netlify-edge-functions?

Run npx skills add https://github.com/netlify/context-and-tools --skill netlify-edge-functions in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/netlify-edge-functions/ (personal) or .claude/skills/netlify-edge-functions/ (project).

Which AI agents can use netlify-edge-functions?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is netlify-edge-functions safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains netlify-edge-functions?

It is published by netlify in netlify/context-and-tools. It has 3,126 recorded installs.

More from netlify/context-and-tools

View all →

netlify-deploy

netlify/context-and-tools

Create, configure, and manage Netlify deploys from code — reach for this when setting up Git continuous deployment, running netlify deploy or netlify deploy --prod from the CLI, writing netlify.toml deploy contexts, adding a Deploy to Netlify button, wiring build hooks, configuring Deploy Previews or branch deploys, locking or skipping deploys, fixing a failed or secrets-scanning deploy, or when someone asks to "deploy my site", "set up preview deploys", "add per-branch build config", "keep staging out of Google", or "add a deploy button to my README".

DevOps & Cloud3.4K installs

netlify-config

netlify/context-and-tools

Configure Netlify builds and routing via netlify.toml, redirects, and headers. Use when setting a build command or publish directory, adding redirects or rewrites or proxies, adding an SPA fallback rewrite, setting custom response headers or basic auth, managing environment variables and secrets, scoping vars per deploy context, marking a var as secret, disabling secret scanning, configuring functions bundling, ignoring builds, or wiring up a monorepo or JavaScript SPA on Netlify.

DevOps & Cloud3.3K installs

netlify-functions

netlify/context-and-tools

Write, configure, and deploy Netlify serverless functions in TypeScript, JavaScript, or Go. Use this when adding an API endpoint or backend route, adding a contact form handler, wiring auth or Identity signup/login hooks, identifying which Netlify user is calling a private or team-login-protected app, building streaming or AI-proxy responses, scheduling cron jobs, running long background jobs (batch processing/scraping), reacting to deploy or form events, setting up rate limiting or region/memory config, or reading environment variables and secrets inside a function. Covers file locations, the Request/Context/Response handler shape, path routing, config options, and local testing with netlify dev.

DevOps & Cloud3.3K installs

netlify-frameworks

netlify/context-and-tools

Deploy and configure web frameworks on Netlify — build settings and SSR/edge adapters plus local platform emulation and env vars. Use when setting up or fixing a framework deploy (Next.js / Astro / Nuxt / SvelteKit / Remix / React Router / TanStack Start / SolidStart / Gatsby / Angular / Vite / Express / Hydrogen / Hugo / Eleventy / Vue / React), adding SSR or edge functions or middleware wired to Netlify context, fixing SPA redirect and catch-all rules, setting a build command or publish directory, or debugging "why isn't my env var updating" and framework build failures.

DevOps & Cloud3.2K installs

netlify-forms

netlify/context-and-tools

Serverless form handling on Netlify-hosted sites — detects HTML forms at deploy time, stores submissions, filters spam, and sends notifications. Use when adding a contact form, lead-capture form, file-upload form, or newsletter signup to a Netlify site; wiring AJAX form submission; setting up a custom thank-you page; adding a honeypot or reCAPTCHA to a form; getting forms working in Next.js, Nuxt, SvelteKit, Astro, or Gatsby; reading form submissions via the Netlify API; setting up submission notifications or ChatGPT automations on form submission events; or debugging missing submissions and forms that silently fail to register.

DevOps & Cloud3.1K installs

netlify-caching

netlify/context-and-tools

Cache dynamic and static responses on Netlify's CDN from Functions, Edge Functions, and proxies. Use when you add caching or cache-control headers to a function response, tune cache TTL or stale-while-revalidate, set up the durable cache, vary a cache key by query/header/cookie/country/language, purge or invalidate the cache by site or cache tag, use the programmatic Cache API (caches.open/match/put) or @netlify/cache helpers (fetchWithCache/cacheHeaders/getCacheStatus), speed up an expensive API call, add ISR or on-demand revalidation, or debug why a response is or isn't cached via the Cache-Status header.

DevOps & Cloud3.1K installs

Popular devops & cloud skills

View category →

microsoft-foundry

microsoft/azure-skills

Build, deploy, evaluate, optimize, fine-tune, and manage Microsoft Foundry agents, models, and resources end to end. USE FOR: foundry, azd ai agent, azd provision/deploy, hosted agent scaffold/develop/run/deploy/troubleshoot, prompt agent create, managed harness agent create, GitHub Copilot harness agent, create agent, update agent, add tool to agent, invoke agent, agent insights, evaluate agent, batch eval, continuous eval, continuous monitoring, agent CI/CD, optimize prompt, improve prompt, optimize agent instructions, Agent Optimizer scaffold, dataset curation from traces, deploy model, model fine-tuning (SFT/DPO/RFT), Foundry project, RBAC, role assignment, permissions, quota, capacity, region, deployment failure, AI Services, create Foundry resource, knowledge index, customize deployment, onboard, availability, training-data, grader, distillation, large file upload. DO NOT USE FOR: Azure Functions, App Service, general Azure deploy (use azure-deploy), general Azure prep (use azure

OfficialDevOps & Cloud579.1K installs

azure-diagnostics

microsoft/azure-skills

Debug Azure production issues on Azure using AppLens, Azure Monitor, resource health, and safe triage. WHEN: debug production issues, troubleshoot app service, app service high CPU, app service deployment failure, troubleshoot container apps, container app 503 or target port mismatch, troubleshoot functions, function telemetry missing or stopped after a config/connection-string change, troubleshoot AKS, VM RDP, Linux SSH, VM black screen, can't connect to VM, reset VM password, NSG or firewall blocking, kubectl cannot connect, kube-system/CoreDNS failures, pod pending, crashloop, node not ready, upgrade failures, analyze logs, KQL, insights, image pull failures, cold start issues, health probe failures, resource health, root cause of errors, troubleshoot event hubs, troubleshoot service bus, messaging SDK error, AMQP connection failure, message lock lost, lock renewal during long-running processing, service bus dead letter.

OfficialDevOps & Cloud569.8K installs

azure-prepare

microsoft/azure-skills

Prepare azd-based Azure projects for deployment: generates azure.yaml, infrastructure (Bicep/Terraform), and Dockerfiles for the Azure Developer CLI (azd) workflow. USE ONLY when the user explicitly wants to use azd as the deployment tool, or the project already has an azure.yaml file. DO NOT USE FOR: non-azd deployments, Python App Service code-only deploys (use python-appservice-deploy), or cross-cloud migration (use azure-cloud-migrate). WHEN: prepare app for azd, create azure.yaml, set up azd infrastructure, modernize app for Azure with azd, deploy with azd, function app, timer trigger, service bus trigger, event-driven function, managed identity, generate Bicep, generate Terraform, create and deploy to Azure.

OfficialDevOps & Cloud569K installs

azure-ai

microsoft/azure-skills

Use for Azure AI: Search, Speech, OpenAI, Document Intelligence. Helps with search, vector/hybrid search, speech-to-text, text-to-speech, transcription, OCR. WHEN: AI Search, query search, vector search, hybrid search, semantic search, speech-to-text, text-to-speech, transcribe, OCR, convert text to speech.

OfficialDevOps & Cloud568.8K installs

azure-deploy

microsoft/azure-skills

Execute Azure deployments for ALREADY-PREPARED applications that have existing .azure/deployment-plan.md and infrastructure files. DO NOT use this skill when the user asks to CREATE a new application — use azure-prepare instead. This skill runs azd up, azd deploy, terraform apply, and az deployment commands with built-in error recovery. Requires .azure/deployment-plan.md from azure-prepare and validated status from azure-validate. WHEN: "run azd up", "run azd deploy", "execute deployment", "push to production", "push to cloud", "go live", "ship it", "bicep deploy", "terraform apply", "publish to Azure", "launch on Azure". DO NOT USE WHEN: "create and deploy", "build and deploy", "create a new app", "set up infrastructure", "create and deploy to Azure using Terraform" — use azure-prepare for these.

OfficialDevOps & Cloud568.6K installs

azure-validate

microsoft/azure-skills

Pre-deployment validation for Azure readiness. Run deep checks on configuration, infrastructure (Bicep or Terraform), RBAC role assignments, managed identity permissions, and prerequisites before deploying. WHEN: validate my app, check deployment readiness, run preflight checks, verify configuration, check if ready to deploy, validate azure.yaml, validate Bicep, test before deploying, troubleshoot deployment errors, validate Azure Functions, validate function app, validate serverless deployment, verify RBAC roles, check role assignments, review managed identity permissions, what-if analysis, validate Container Apps deployment.

OfficialDevOps & Cloud568K installs