Update to Netlify
Snapshot Nov 19, 2026 · 00:11 UTC · version 1.9.0
Collection source: downloaded plugin package.
Payment or plan references changed
Full description — Now says: Write, route, cache, and debug Netlify Edge Functions, the Deno-based TypeScript or JavaScript handlers in netlify/edge-functions that run at the network...
Observed in published text. Live prices and checkout terms have not been verified by this change.
Up to 3 plugins free · no card required.
All fields and original values.
Full description
Oct 7, 2026 · 00:02 UTC
Write and configure Netlify Edge Functions — TypeScript/JavaScript handlers running in a Deno runtime at the network edge. Use when adding auth middleware or auth redirects, geolocation or localization logic, A/B testing or personalizati...
Nov 19, 2026 · 00:11 UTC
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 wheneve...
Skill instructions
Oct 7, 2026 · 00:02 UTC
Write and configure Netlify Edge Functions — TypeScript/JavaScript handlers running in a Deno runtime at the network edge. Use when adding auth middleware or auth redirects, geolocation or localization logic, A/B testing or personalizati...
Nov 19, 2026 · 00:11 UTC
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 wheneve...
Compare saved observations
Download comparison JSONSKILL.md text changes
− removed · + added
--- before +++ after @@ -1,302 +1,331 @@ --- name: netlify-edge-functions -description: Write and configure Netlify Edge Functions — TypeScript/JavaScript handlers running in a Deno runtime at the network edge. Use when adding auth middleware or auth redirects, geolocation or localization logic, A/B testing or personalization, request/response transforms (rewrites/redirects), or edge SSR to a Netlify site. Triggers on tasks like "add an edge function", "auth check at the edge", "redirect visitors by country", "A/B test with cookies", "rewrite requests", "personalize by geo", or "cache an edge response". Covers the config export, path routing, the Context object, response caching, environment variables, and edge-vs-serverless choices. Check the framework's adapter first — only hand-write an edge function when the framework doesn't already generate one. +description: 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. --- # Netlify Edge Functions -## Modern syntax (reach for this) - -Export a default handler plus a `config` object. Import `Config`/`Context` types from `@netlify/edge-functions`; `Request`/`Response`/`URL` are global. +## Use this form ```ts +// netlify/edge-functions/hello.ts import type { Config, Context } from "@netlify/edge-functions"; export default async (request: Request, context: Context) => { - return new Response("Hello world"); + return new Response(`Hello from ${context.geo.country?.name ?? "somewhere"}`); }; -export const config: Config = { - path: "/test", -}; +export const config: Config = { path: "/hello" }; ``` -**Do not hand-write an edge function when your framework's adapter already generates middleware for the job** — duplicating it causes conflicts. Check the framework adapter/reference first. - -**Edge vs serverless:** use edge functions for low-latency request/response manipulation, geolocation logic, auth checks/redirects, and A/B personalization. Use serverless functions for long-running work (up to 15 min), heavy Node.js dependencies, database-heavy operations, background/scheduled tasks, or memory above 512 MB. - -## File location - -- Default directory: `YOUR_BASE_DIRECTORY/netlify/edge-functions`. Custom: `edge_functions` under `[build]` in `netlify.toml` (path relative to base directory). -- Keep the directory **outside your publish directory** so source files aren't deployed. -- Extensions: `.js`, `.ts`, `.jsx`, `.tsx` (`.jsx`/`.tsx` useful for SSR). -- Same-name conflict: if `my-function.ts` and `my-function.js` both exist, the **TypeScript file is ignored** and the JavaScript one is deployed. - -## Routing — required, or the function silently never runs - -⚠️ **An edge function without a route (no `config` export and no `netlify.toml` declaration) still deploys but never runs — no build error, no warning.** When "my edge function does nothing", check the route first. - -⚠️ **Scope `path` narrowly.** `path: "/*"` intercepts every request including static assets, adding latency and billing an edge invocation for each one. - -Edge functions are **not** auto-assigned a URL route. Configure via inline `config` or `netlify.toml`. - -`path` is a `URLPattern` expression, must start with `/`, single string or array: - -```ts -export const config: Config = { - path: ["/", "/products/*"], - excludedPath: ["/*.css", "/*.js"], -}; +- One file = one function: a default-export handler plus a **named** `config` export with the route. Alternatively, declare the route in `netlify.toml`. +- The default export can also be a [Fetchable module](https://fetchable.org/): an object with a `fetch` method. Netlify calls `fetch` with the same `(request, context)` arguments and uses its return value the same way; inside `fetch`, `this` is the exported object. Use it to share one handler with other platforms that accept Fetchable modules. + ```ts + export default { + async fetch(request: Request, context: Context) { + return new Response("Hello"); + }, + }; + export const config: Config = { path: "/hello" }; // still a named export + ``` +- `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 + +| What | Where | +|---|---| +| 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 toml | file name without extension (`auth.ts` → `function = "auth"`) | +| Import map | any JSON file, referenced by `[functions] deno_import_map = "./import_map.json"` | + +## Return values + +| Return | Effect | +|---|---| +| `Response` | sent to client; chain ends | +| `URL` | same-site rewrite, 200, address bar unchanged | +| `undefined` / `return;` | skip this function; chain continues | + +### Endpoint +```ts +export default async () => + new Response("Hello, World!", { headers: { "content-type": "text/html" } }); +export const config = { path: "/api/hello" }; ``` -Config properties: `path`, `excludedPath`, `pattern` (regex alternative to `path`), `excludedPattern`, `method`, `header`, `onError`, `cache`. - -### netlify.toml declaration - -Use `[[edge_functions]]` to declare multiple functions on one path and control order: - -```toml -[[edge_functions]] - path = "/admin" - function = "auth" - -[[edge_functions]] - path = "/admin" - function = "injector" - cache = "manual" - -[[edge_functions]] - pattern = "/products/(.*)" - excludedPattern = "/products/things/(.*)" - function = "highlight" -``` - -Properties: `function`, `path`, `excludedPath`, `pattern`, `excludedPattern`, `header`, `cache`. - -**Merge precedence:** if the same function is declared both inline and in `netlify.toml`, configs merge and are treated as inline; inline wins duplicate fields. - -### Match by headers - -`header` keys are HTTP header names (case-insensitive); values are `true` (present), `false` (absent), or a string regex on the value. Multiple same-name values match against the comma-joined list. - +### Redirect / rewrite ```ts -export const config: Config = { - header: { "x-required": true, "x-forbidden": false, "user-agent": "(iPhone|Android)" }, - path: "/*", +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`. -### Declaration processing order - -Netlify runs the whole declaration order **TWICE**: the first pass runs only edge functions **not** configured for caching; the second pass runs the ones **with** caching configured. Within that: - -1. Framework-generated functions declared in a config file. -2. Your `netlify.toml` declarations (top-to-bottom order). -3. Framework/integration-generated functions with inline config. -4. Your inline declarations (**alphabetical by function file name**). - -To control order across multiple functions on a path, prefer `netlify.toml` declarations over inline. - -After all functions run, Netlify evaluates redirect rules — unless a function returned a response and ended the chain. To customize order, use `netlify.toml`. - -**Order caveats:** -- A returned response ends the chain; redirects for that path don't occur. -- An edge function on the **target** of a static rewrite does **not** execute for rewritten requests. -- `fetch()` for internal requests or returning a `URL` starts a **new request chain** and re-runs matching edge functions. Use `context.next()` to avoid re-running them. - -## Function signature & return values - -Handler receives `(request: Request, context: Context)`. Return one of: -- a `Response` — delivered to the client; **ends the request chain** (declared redirects for that path don't run). -- a `URL` — rewrite to a **same-site** URL with 200 status; address bar unchanged. Same-site only — for other sites use `fetch`. -- `undefined` / empty `return;` — bypass this function, continue the chain. - -Modify a response as middleware by awaiting `context.next()`: - +### Middleware (modify origin response) ```ts import type { Context } from "@netlify/edge-functions"; export default async (request: Request, context: Context) => { - const url = new URL(request.url); - if (url.searchParams.get("method") !== "transform") return; - + if (new URL(request.url).searchParams.get("method") !== "transform") return; const response = await context.next(); - const text = await response.text(); - return new Response(text.toUpperCase(), response); + 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. -Netlify does **not** add headers to edge function requests — use `context` for client request info. - -## Common patterns - -**Redirect by geo + cookie:** +### Conditional requests ```ts -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)); - } +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. -**Rewrite (same-site, 200):** +### Read body, then continue ```ts -export default async (request: Request, { geo }: Context) => { - if (geo.city === "Paris") return new URL("/subscriber-sale", request.url); +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) })); }; ``` -**Read request body then continue** — a body can only be read once, so pass a new `Request` with an unread body: +### Netlify user gate (private / team-login-protected projects) ```ts +import type { Config, Context } from "@netlify/edge-functions"; + 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) })); + 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/*" }; ``` -**Conditional request:** +### Post-response work ```ts -export default async (req: Request, { next }: Context) => { - const res = await next({ sendConditionalRequest: true }); - if (res.status === 304) return res; - const text = await res.text(); - return new Response(text.toUpperCase(), res); +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. -**SSR with React (`.tsx`):** +### Streaming SSR (`.tsx`) ```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 function handler(req: Request, context: Context) { +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, { status: 200, headers: { "Content-Type": "text/html" } }); -} - + return new Response(stream, { headers: { "Content-Type": "text/html" } }); +}; export const config: Config = { path: "/hello" }; ``` -## Context object - -- **`geo`** — `city`, `country.{code,name}`, `subdivision.{code,name}`, `latitude`, `longitude`, `timezone`, `postalCode`. -- **`cookies`** — `get(name)`, `set(options)` (CookieStore.set format), `delete(name|options)`. Cross-subdomain cookies need a custom domain — impossible on `netlify.app` (Public Suffix List). -- **`next(options?)`** / **`next(request, options?)`** — invoke the next item in the chain; returns a `Promise<Response>` you can modify. `options.sendConditionalRequest: true` for conditional requests. Only call `next` if you need the response body. Pass an explicit `Request` when you've read the body. -- **`params`** — path params, e.g. path `/pets/:name` + request `/pets/winter` → `{name:"winter"}`. Query string: use `request.url`. -- **`ip`** — client IP string. -- **`requestId`** — Netlify request ID. -- **`account.id`**, **`site.{id,name,url}`**, **`server.region`**, **`deploy.{context,id,published,skewProtectionToken}`**. -- **`waitUntil(promise)`** — extend execution past the response (analytics, logs) without blocking it. Still subject to the CPU limit. - -**`Netlify` global:** `Netlify.context` (null outside the handler), `Netlify.env.{get,has,set,delete,toObject}`. `Netlify.env.set`/`delete` are **invocation-scoped only** — they do not persist env vars; use the Netlify env API endpoints. +## `Context` -## Response caching - -⚠️ **Caching requires BOTH opting in AND setting headers — it's both or neither.** Setting `Cache-Control` on the returned `Response` does nothing without `cache: "manual"` in config, and vice versa. Default (either missing): every request invokes the function. - -1. Opt in: `cache: "manual"` (inline or `netlify.toml`). -2. Set headers **inline in the function code** (not in `netlify.toml`): +| Property | Notes | +|---|---| +| `cookies.get(name)` / `.set(options)` / `.delete(name \| options)` | `set` and `delete` use `CookieStore` option format; they act on the outgoing response | +| `geo` | `city`, `country.{code,name}`, `subdivision.{code,name}`, `latitude`, `longitude`, `timezone`, `postalCode` (format varies) | +| `ip` | client IP | +| `next(options?)` / `next(request, options?)` | `Promise<Response>` from the next item in the chain | +| `params` | URLPattern 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](https://open-api.netlify.com/#tag/environmentVariables). + +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` +| Key | Value | +|---|---| +| `path` | URLPattern string or array; must start with `/` | +| `excludedPath` | URLPattern string or array; must start with `/` | +| `pattern` / `excludedPattern` | regex alternatives to `path` / `excludedPath` | +| `method` | HTTP 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"` | ```ts -import type { Context, Config } from "@netlify/edge-functions"; - -export default async (req: Request, context: Context) => { - return new Response("Hello world", { - headers: { "cache-control": "public, s-maxage=3600" }, - }); +export const config: Config = { + path: "/*", + excludedPath: ["/*.css", "/*.js", "/img/*"], + header: { "user-agent": "(iPhone|Android)" }, }; - -export const config: Config = { cache: "manual", path: "/hello" }; ``` +The `netlify-agent-category` request header maps any user-agent to a [client category](https://docs.netlify.com/build/user-agent-categories). -Supported cache headers: `Cache-Control`, `CDN-Cache-Control`, `Netlify-CDN-Cache-Control`, `Expires` (overridden by `max-age`/`s-maxage`), `Vary`, `Netlify-Vary`. See https://docs.netlify.com/build/caching/caching-overview - -**Atomic deploys void the cache:** `s-maxage`/`max-age`/`Expires` are discarded by a new deploy in the same deploy context, even mid-lifetime. - -**When to cache:** endpoint responses reusable across clients (e.g. identical SSR HTML). **Do not cache** middleware, routing/transform logic, or per-client personalization. - -⚠️ **Caching functions always shadow static files.** A caching function on `/*` serves `/cat.png` instead of the static `cat.png`. +### `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. -## Error handling (`onError`, inline only) - -- **`fail`** (default) — serve a generic error page. -- **`/YOUR_CUSTOM_PATH`** — rewrite to a same-site path (must start with `/`); served without invoking edge functions for that path. -- **`bypass`** — skip the erroring function, continue the chain. - -```ts -export const config: Config = { path: "/hello", onError: "/unavailable" }; -``` - -Fail closed for critical logic (auth); fail open (`bypass`) for progressive enhancement (nice-to-have localization). +```toml +[[edge_functions]] + path = "/admin" + function = "auth" -## Environment variables +[[edge_functions]] + path = "/admin" + function = "injector" + cache = "manual" -- Set via UI/CLI/API; scope **must include Functions** to reach edge runtime. -- **Env vars in `netlify.toml` are NOT available to edge functions.** -- **Build-scope vars are NOT available at edge runtime** — only during the build step. Embed their values at build time if needed. -- Changes require a **new build and deploy**; each deploy freezes values at deploy time. -- Access at runtime with `Netlify.env.get(key)` / `Netlify.env.toObject()`. +[[edge_functions]] + pattern = "/products/(.*)" + excludedPattern = "/products/things/(.*)" + function = "highlight" -```ts -export default async (request: Request, context: Context) => { - const value = Netlify.env.get("MY_IMPORTANT_VARIABLE"); - return new Response(`Value: ${value}`); -}; +[[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`. -Next.js Middleware note: with Netlify Edge Functions for Middleware on Next.js, `process.env` also works. +### 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. -## Runtime & modules +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. -Deno-based. Import modules by: -- **Node built-ins:** `import { randomBytes } from "node:crypto";` -- **Deno/URL imports:** `import React from "https://esm.sh/react";` -- **npm packages (beta):** `npm install` then import by name. ⚠️ Beta — packages using native binaries (Prisma) or runtime dynamic imports (cowsay) may fail. +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. -**Import maps** (module names instead of URLs) — use a separate import map file, declared in `netlify.toml`: +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. -```toml -[functions] - deno_import_map = "./path/to/your/import_map.json" -``` +An edge function declared on the *target* of a static rewrite does not run for rewritten requests. -Supported Web APIs include `fetch`/`Request`/`Response`/`URL`/`File`/`Blob`, `console`, `atob`/`btoa`, `TextEncoder`/`TextDecoder` (+ stream variants), Web Crypto (`randomUUID`, `getRandomValues`, `SubtleCrypto`), WebSocket, timers, Streams API, URLPattern, `Performance`. +## Response caching +```ts +import type { Config } from "@netlify/edge-functions"; -## Local dev & deploy +export default async () => + new Response("Hello world", { headers: { "cache-control": "public, s-maxage=3600" } }); -```bash -npm install netlify-cli -g -netlify dev # runs edge functions on local requests -# visit http://localhost:8888/test +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](https://docs.netlify.com/build/caching/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`) +| Value | Effect | +|---|---| +| `"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 | -- Debug: `netlify dev` with `--edge-inspect` or `--edge-inspect-brk` (see https://cli.netlify.com/commands/dev/). -- Geo mocking: `--geo=mock` (San Francisco) or `--geo=mock --country=XX`. -- ⚠️ **No local caching** — cache headers are ignored in local testing. -- Manual deploys require **Netlify CLI 12.2.8+** (older versions error). -- Deploys are **atomic** — old deploys keep old behavior until you publish a new production deploy. - -**Monitor:** production logs at Netlify UI **Cloud compute > Edge functions**. Each `console.*` log includes the generating function name. Retention ≥ 24h (7 days on some plans). Log Drains on Enterprise. +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. -## Limits & feature gaps - -- **Code size:** 20 MB compressed (bundle max). -- **Memory:** 512 MB per set of deployed edge functions. -- **CPU time:** 50 ms per request (excludes wait time; `waitUntil` work still counts). -- **Response header timeout:** 40 s. -- Cached responses do **not** count toward invocations. -- **Split Testing** enabled → edge functions do **not** run. -- **Custom Headers** (incl. basic auth) do **not** apply to edge functions. -- **Prerendering** does not apply to edge-served paths. -- Rewrites are **same-site only** — use `fetch` for other/external sites. -- Multiple framework plugins generating edge functions may collide. -- **Not** supported under HIPAA-compliant hosting. - -See the overview at https://docs.netlify.com/build/edge-functions/overview.md and the full example library at https://edge-functions-examples.netlify.app/ +## 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](https://docs.netlify.com/manage/monitoring/log-drains) are available on Enterprise plans. + +## Limits +| Limit | Value | +|---|---| +| Bundle size | 20 MB compressed | +| Memory (per set of deployed functions) | 512 MB | +| CPU time per request | 50 ms (excludes I/O wait) | +| Response header timeout | 40 s | + +- Prerendering does not apply to paths served by an edge function. +- Multiple framework plugins that generate edge functions may collide. + +Docs: [API](https://docs.netlify.com/build/edge-functions/api.md) · [Declarations](https://docs.netlify.com/build/edge-functions/declarations.md) · [Optional configuration](https://docs.netlify.com/build/edge-functions/optional-configuration.md) · [Limits](https://docs.netlify.com/build/edge-functions/limits.md) · [Examples](https://edge-functions-examples.netlify.app/) + +<!-- 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. --> +<!-- Undocumented: whether Netlify uses Fetchable module members other than `fetch`. --> <!-- system: agent-context/edge-functions/system.md — human-owned, merged by ctx-gen; edit system.md, not this section --> # Netlify house rules (edge-functions) @@ -329,3 +358,12 @@ 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.
Full technical diff · 2 changed fields
changed /description
"Write and configure Netlify Edge Functions — TypeScript/JavaScript handlers running in a Deno runtime at the network edge. Use when adding auth middleware or auth redirects, geolocation or localization logic, A/B testing or personalization, request/response transforms (rewrites/redirects), or edge SSR to a Netlify site. Triggers on tasks like \"add an edge function\", \"auth check at the edge\", \"redirect visitors by country\", \"A/B test with cookies\", \"rewrite requests\", \"personalize by geo\", or \"cache an edge response\". Covers the config export, path routing, the Context object, response caching, environment variables, and edge-vs-serverless choices. Check the framework's adapter first — only hand-write an edge function when the framework doesn't already generate one."
"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."
changed /skill_md_contents
"---\nname: netlify-edge-functions\ndescription: Write and configure Netlify Edge Functions — TypeScript/JavaScript handlers running in a Deno runtime at the network edge. Use when adding auth middleware or auth redirects, geolocation or localization logic, A/B testing or personalization, request/response transforms (rewrites/redirects), or edge SSR to a Netlify site. Triggers on tasks like \"add an edge function\", \"auth check at the edge\", \"redirect visitors by country\", \"A/B test with cookies\", \"rewrite requests\", \"personalize by geo\", or \"cache an edge response\". Covers the config export, path routing, the Context object, response caching, environment variables, and edge-vs-serverless choices. Check the framework's adapter first — only hand-write an edge function when the framework doesn't already generate one.\n---\n\n# Netlify Edge Functions\n\n## Modern syntax (reach for this)\n\nExport a default handler plus a `config` object. Import `Config`/`Context` types from `@netlify/edge-functions`; `Request`/`Response`/`URL` are global.\n\n```ts\nimport type { Config, Context } from \"@netlify/edge-functions\";\n\nexport default async (request: Request, context: Context) => {\n return new Response(\"Hello world\");\n};\n\nexport const config: Config = {\n path: \"/test\",\n};\n```\n\n**Do not hand-write an edge function when your framework's adapter already generates middleware for the job** — duplicating it causes conflicts. Check the framework adapter/reference first.\n\n**Edge vs serverless:** use edge functions for low-latency request/response manipulation, geolocation logic, auth checks/redirects, and A/B personalization. Use serverless functions for long-running work (up to 15 min), heavy Node.js dependencies, database-heavy operations, background/scheduled tasks, or memory above 512 MB.\n\n## File location\n\n- Default directory: `YOUR_BASE_DIRECTORY/netlify/edge-functions`. Custom: `edge_functions` under `[build]` in `netlify.toml` (path relative to base directory).\n- Keep the directory **outside your publish directory** so source files aren't deployed.\n- Extensions: `.js`, `.ts`, `.jsx`, `.tsx` (`.jsx`/`.tsx` useful for SSR).\n- Same-name conflict: if `my-function.ts` and `my-function.js` both exist, the **TypeScript file is ignored** and the JavaScript one is deployed.\n\n## Routing — required, or the function silently never runs\n\n⚠️ **An edge function without a route (no `config` export and no `netlify.toml` declaration) still deploys but never runs — no build error, no warning.** When \"my edge function does nothing\", check the route first.\n\n⚠️ **Scope `path` narrowly.** `path: \"/*\"` intercepts every request including static assets, adding latency and billing an edge invocation for each one.\n\nEdge functions are **not** auto-assigned a URL route. Configure via inline `config` or `netlify.toml`.\n\n`path` is a `URLPattern` expression, must start with `/`, single string or array:\n\n```ts\nexport const config: Config = {\n path: [\"/\", \"/products/*\"],\n excludedPath: [\"/*.css\", \"/*.js\"],\n};\n```\n\nConfig properties: `path`, `excludedPath`, `pattern` (regex alternative to `path`), `excludedPattern`, `method`, `header`, `onError`, `cache`.\n\n### netlify.toml declaration\n\nUse `[[edge_functions]]` to declare multiple functions on one path and control order:\n\n```toml\n[[edge_functions]]\n path = \"/admin\"\n function = \"auth\"\n\n[[edge_functions]]\n path = \"/admin\"\n function = \"injector\"\n cache = \"manual\"\n\n[[edge_functions]]\n pattern = \"/products/(.*)\"\n excludedPattern = \"/products/things/(.*)\"\n function = \"highlight\"\n```\n\nProperties: `function`, `path`, `excludedPath`, `pattern`, `excludedPattern`, `header`, `cache`.\n\n**Merge precedence:** if the same function is declared both inline and in `netlify.toml`, configs merge and are treated as inline; inline wins duplicate fields.\n\n### Match by headers\n\n`header` keys are HTTP header names (case-insensitive); values are `true` (present), `false` (absent), or a string regex on the value. Multiple same-name values match against the comma-joined list.\n\n```ts\nexport const config: Config = {\n header: { \"x-required\": true, \"x-forbidden\": false, \"user-agent\": \"(iPhone|Android)\" },\n path: \"/*\",\n};\n```\n\n### Declaration processing order\n\nNetlify runs the whole declaration order **TWICE**: the first pass runs only edge functions **not** configured for caching; the second pass runs the ones **with** caching configured. Within that:\n\n1. Framework-generated functions declared in a config file.\n2. Your `netlify.toml` declarations (top-to-bottom order).\n3. Framework/integration-generated functions with inline config.\n4. Your inline declarations (**alphabetical by function file name**).\n\nTo control order across multiple functions on a path, prefer `netlify.toml` declarations over inline.\n\nAfter all functions run, Netlify evaluates redirect rules — unless a function returned a response and ended the chain. To customize order, use `netlify.toml`.\n\n**Order caveats:**\n- A returned response ends the chain; redirects for that path don't occur.\n- An edge function on the **target** of a static rewrite does **not** execute for rewritten requests.\n- `fetch()` for internal requests or returning a `URL` starts a **new request chain** and re-runs matching edge functions. Use `context.next()` to avoid re-running them.\n\n## Function signature & return values\n\nHandler receives `(request: Request, context: Context)`. Return one of:\n- a `Response` — delivered to the client; **ends the request chain** (declared redirects for that path don't run).\n- a `URL` — rewrite to a **same-site** URL with 200 status; address bar unchanged. Same-site only — for other sites use `fetch`.\n- `undefined` / empty `return;` — bypass this function, continue the chain.\n\nModify a response as middleware by awaiting `context.next()`:\n\n```ts\nimport type { Context } from \"@netlify/edge-functions\";\n\nexport default async (request: Request, context: Context) => {\n const url = new URL(request.url);\n if (url.searchParams.get(\"method\") !== \"transform\") return;\n\n const response = await context.next();\n const text = await response.text();\n return new Response(text.toUpperCase(), response);\n};\n```\n\nNetlify does **not** add headers to edge function requests — use `context` for client request info.\n\n## Common patterns\n\n**Redirect by geo + cookie:**\n```ts\nexport default async (req: Request, { cookies, geo }: Context) => {\n if (geo.city === \"Paris\" && cookies.get(\"promo-code\") === \"15-for-followers\") {\n return Response.redirect(new URL(\"/subscriber-sale\", req.url));\n }\n};\n```\n\n**Rewrite (same-site, 200):**\n```ts\nexport default async (request: Request, { geo }: Context) => {\n if (geo.city === \"Paris\") return new URL(\"/subscriber-sale\", request.url);\n};\n```\n\n**Read request body then continue** — a body can only be read once, so pass a new `Request` with an unread body:\n```ts\nexport default async (req: Request, context: Context) => {\n const body = await req.json();\n if (!isValid(body.access_token)) return new Response(\"forbidden\", { status: 403 });\n return context.next(new Request(req, { body: JSON.stringify(body) }));\n};\n```\n\n**Conditional request:**\n```ts\nexport default async (req: Request, { next }: Context) => {\n const res = await next({ sendConditionalRequest: true });\n if (res.status === 304) return res;\n const text = await res.text();\n return new Response(text.toUpperCase(), res);\n};\n```\n\n**SSR with React (`.tsx`):**\n```tsx\nimport React from \"https://esm.sh/react\";\nimport { renderToReadableStream } from \"https://esm.sh/react-dom/server\";\nimport type { Config, Context } from \"@netlify/edge-functions\";\n\nexport default async function handler(req: Request, context: Context) {\n const stream = await renderToReadableStream(\n <html><body><h1>Hello {context.geo.country?.name}</h1></body></html>\n );\n return new Response(stream, { status: 200, headers: { \"Content-Type\": \"text/html\" } });\n}\n\nexport const config: Config = { path: \"/hello\" };\n```\n\n## Context object\n\n- **`geo`** — `city`, `country.{code,name}`, `subdivision.{code,name}`, `latitude`, `longitude`, `timezone`, `postalCode`.\n- **`cookies`** — `get(name)`, `set(options)` (CookieStore.set format), `delete(name|options)`. Cross-subdomain cookies need a custom domain — impossible on `netlify.app` (Public Suffix List).\n- **`next(options?)`** / **`next(request, options?)`** — invoke the next item in the chain; returns a `Promise<Response>` you can modify. `options.sendConditionalRequest: true` for conditional requests. Only call `next` if you need the response body. Pass an explicit `Request` when you've read the body.\n- **`params`** — path params, e.g. path `/pets/:name` + request `/pets/winter` → `{name:\"winter\"}`. Query string: use `request.url`.\n- **`ip`** — client IP string.\n- **`requestId`** — Netlify request ID.\n- **`account.id`**, **`site.{id,name,url}`**, **`server.region`**, **`deploy.{context,id,published,skewProtectionToken}`**.\n- **`waitUntil(promise)`** — extend execution past the response (analytics, logs) without blocking it. Still subject to the CPU limit.\n\n**`Netlify` global:** `Netlify.context` (null outside the handler), `Netlify.env.{get,has,set,delete,toObject}`. `Netlify.env.set`/`delete` are **invocation-scoped only** — they do not persist env vars; use the Netlify env API endpoints.\n\n## Response caching\n\n⚠️ **Caching requires BOTH opting in AND setting headers — it's both or neither.** Setting `Cache-Control` on the returned `Response` does nothing without `cache: \"manual\"` in config, and vice versa. Default (either missing): every request invokes the function.\n\n1. Opt in: `cache: \"manual\"` (inline or `netlify.toml`).\n2. Set headers **inline in the function code** (not in `netlify.toml`):\n\n```ts\nimport type { Context, Config } from \"@netlify/edge-functions\";\n\nexport default async (req: Request, context: Context) => {\n return new Response(\"Hello world\", {\n headers: { \"cache-control\": \"public, s-maxage=3600\" },\n });\n};\n\nexport const config: Config = { cache: \"manual\", path: \"/hello\" };\n```\n\nSupported cache headers: `Cache-Control`, `CDN-Cache-Control`, `Netlify-CDN-Cache-Control`, `Expires` (overridden by `max-age`/`s-maxage`), `Vary`, `Netlify-Vary`. See https://docs.netlify.com/build/caching/caching-overview\n\n**Atomic deploys void the cache:** `s-maxage`/`max-age`/`Expires` are discarded by a new deploy in the same deploy context, even mid-lifetime.\n\n**When to cache:** endpoint responses reusable across clients (e.g. identical SSR HTML). **Do not cache** middleware, routing/transform logic, or per-client personalization.\n\n⚠️ **Caching functions always shadow static files.** A caching function on `/*` serves `/cat.png` instead of the static `cat.png`.\n\n## Error handling (`onError`, inline only)\n\n- **`fail`** (default) — serve a generic error page.\n- **`/YOUR_CUSTOM_PATH`** — rewrite to a same-site path (must start with `/`); served without invoking edge functions for that path.\n- **`bypass`** — skip the erroring function, continue the chain.\n\n```ts\nexport const config: Config = { path: \"/hello\", onError: \"/unavailable\" };\n```\n\nFail closed for critical logic (auth); fail open (`bypass`) for progressive enhancement (nice-to-have localization).\n\n## Environment variables\n\n- Set via UI/CLI/API; scope **must include Functions** to reach edge runtime.\n- **Env vars in `netlify.toml` are NOT available to edge functions.**\n- **Build-scope vars are NOT available at edge runtime** — only during the build step. Embed their values at build time if needed.\n- Changes require a **new build and deploy**; each deploy freezes values at deploy time.\n- Access at runtime with `Netlify.env.get(key)` / `Netlify.env.toObject()`.\n\n```ts\nexport default async (request: Request, context: Context) => {\n const value = Netlify.env.get(\"MY_IMPORTANT_VARIABLE\");\n return new Response(`Value: ${value}`);\n};\n```\n\nNext.js Middleware note: with Netlify Edge Functions for Middleware on Next.js, `process.env` also works.\n\n## Runtime & modules\n\nDeno-based. Import modules by:\n- **Node built-ins:** `import { randomBytes } from \"node:crypto\";`\n- **Deno/URL imports:** `import React from \"https://esm.sh/react\";`\n- **npm packages (beta):** `npm install` then import by name. ⚠️ Beta — packages using native binaries (Prisma) or runtime dynamic imports (cowsay) may fail.\n\n**Import maps** (module names instead of URLs) — use a separate import map file, declared in `netlify.toml`:\n\n```toml\n[functions]\n deno_import_map = \"./path/to/your/import_map.json\"\n```\n\nSupported Web APIs include `fetch`/`Request`/`Response`/`URL`/`File`/`Blob`, `console`, `atob`/`btoa`, `TextEncoder`/`TextDecoder` (+ stream variants), Web Crypto (`randomUUID`, `getRandomValues`, `SubtleCrypto`), WebSocket, timers, Streams API, URLPattern, `Performance`.\n\n## Local dev & deploy\n\n```bash\nnpm install netlify-cli -g\nnetlify dev # runs edge functions on local requests\n# visit http://localhost:8888/test\n```\n\n- Debug: `netlify dev` with `--edge-inspect` or `--edge-inspect-brk` (see https://cli.netlify.com/commands/dev/).\n- Geo mocking: `--geo=mock` (San Francisco) or `--geo=mock --country=XX`.\n- ⚠️ **No local caching** — cache headers are ignored in local testing.\n- Manual deploys require **Netlify CLI 12.2.8+** (older versions error).\n- Deploys are **atomic** — old deploys keep old behavior until you publish a new production deploy.\n\n**Monitor:** production logs at Netlify UI **Cloud compute > Edge functions**. Each `console.*` log includes the generating function name. Retention ≥ 24h (7 days on some plans). Log Drains on Enterprise.\n\n## Limits & feature gaps\n\n- **Code size:** 20 MB compressed (bundle max).\n- **Memory:** 512 MB per set of deployed edge functions.\n- **CPU time:** 50 ms per request (excludes wait time; `waitUntil` work still counts).\n- **Response header timeout:** 40 s.\n- Cached responses do **not** count toward invocations.\n- **Split Testing** enabled → edge functions do **not** run.\n- **Custom Headers** (incl. basic auth) do **not** apply to edge functions.\n- **Prerendering** does not apply to edge-served paths.\n- Rewrites are **same-site only** — use `fetch` for other/external sites.\n- Multiple framework plugins generating edge functions may collide.\n- **Not** supported under HIPAA-compliant hosting.\n\nSee the overview at https://docs.netlify.com/build/edge-functions/overview.md and the full example library at https://edge-functions-examples.netlify.app/\n\n<!-- system: agent-context/edge-functions/system.md — human-owned, merged by ctx-gen; edit system.md, not this section -->\n# Netlify house rules (edge-functions)\n\nThese are org conventions and field-learned guardrails, not docs facts — they\nare merged into the rendered skill by ctx-gen and are never generated.\nExtracted from the previous hand-written netlify-edge-functions skill; owned\nby the skills maintainer.\n\n1. Check the framework's adapter/reference first: a custom edge function that\n duplicates adapter-generated middleware causes conflicts. Only hand-write\n an edge function when the framework doesn't already generate one for the\n job.\n2. Scope `path` narrowly. `path: \"/*\"` intercepts every request — including\n static assets — adding latency to each one and billing an edge invocation\n for it.\n3. An edge function without a route (no config export, no netlify.toml\n declaration) still deploys, but silently never runs: no build error, no\n warning. When \"my edge function does nothing\", check the route first.\n4. Choose edge vs serverless by workload shape: edge functions for low-latency\n request/response manipulation, geolocation logic, auth checks/redirects,\n and A/B personalization; serverless functions for long-running work (up to\n 15 min), heavy Node.js dependencies, database-heavy operations,\n background/scheduled tasks, or memory needs above 512 MB.\n5. Cache headers on an edge response do nothing without `cache: \"manual\"` in\n config — it's both or neither. Setting `Cache-Control` on the returned\n `Response` has no effect unless the function also opts in.\n6. When explaining declaration processing order, state the two-pass loop,\n not just the ordering: Netlify runs the whole declaration order TWICE —\n first pass runs only edge functions not configured for caching, second\n pass runs the ones with caching configured. \"Non-cached before cached\"\n without the loop framing is an incomplete answer.\n""---\nname: netlify-edge-functions\ndescription: 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.\n---\n\n# Netlify Edge Functions\n\n## Use this form\n\n```ts\n// netlify/edge-functions/hello.ts\nimport type { Config, Context } from \"@netlify/edge-functions\";\n\nexport default async (request: Request, context: Context) => {\n return new Response(`Hello from ${context.geo.country?.name ?? \"somewhere\"}`);\n};\n\nexport const config: Config = { path: \"/hello\" };\n```\n\n- One file = one function: a default-export handler plus a **named** `config` export with the route. Alternatively, declare the route in `netlify.toml`.\n- The default export can also be a [Fetchable module](https://fetchable.org/): an object with a `fetch` method. Netlify calls `fetch` with the same `(request, context)` arguments and uses its return value the same way; inside `fetch`, `this` is the exported object. Use it to share one handler with other platforms that accept Fetchable modules.\n ```ts\n export default {\n async fetch(request: Request, context: Context) {\n return new Response(\"Hello\");\n },\n };\n export const config: Config = { path: \"/hello\" }; // still a named export\n ```\n- `Request` and `Response` are global. Import `Context` and `Config` types from `@netlify/edge-functions`.\n- Read env vars with `Netlify.env.get()`. `process.env` works only for Next.js middleware.\n\n**Avoid these:**\n- A file with no `config.path` or `pattern` and no `[[edge_functions]]` entry. It deploys but never runs.\n- Import maps in `deno.json`. They are unsupported. Use a separate file with `[functions] deno_import_map`.\n- Variables set in `netlify.toml`. They are invisible to edge functions.\n- `Netlify.env.set()` or `Netlify.env.delete()` as persistence. They affect only the current invocation.\n- `fetch()` to the same site for the current path. Use `context.next()` instead.\n\n## ⚠️ Footguns\n\n- **No route = silent no-op.** Edge functions get no automatic URL.\n- **`path: \"/*\"` runs on every request**, including assets. Narrow it, or add `excludedPath`.\n- **Caching needs both parts:** `cache: \"manual\"` in config AND cache headers on the returned `Response`. With only one, nothing is cached.\n- **Cached functions shadow static files.** A cached function on `/*` serves `/cat.png` instead of the file.\n- **Returning a `Response` ends the chain.** Redirect rules for that path never run.\n- **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.\n- **The request body can be read once.** After `await req.json()`, pass `new Request(req, { body })` to `context.next()`.\n- **Same-named `foo.ts` and `foo.js`:** the TS file is ignored and the JS file deploys.\n- **50 ms CPU per request**, including `waitUntil` work.\n- **Not executed** on sites with Split Testing enabled.\n- **Custom Headers and basic-auth headers do not apply** to edge functions.\n- **Not supported** on HIPAA-compliant hosting.\n- **`netlify.app` is on the Public Suffix List.** Cross-subdomain cookies need a custom domain.\n\n## Files\n\n| What | Where |\n|---|---|\n| Functions | `<base>/netlify/edge-functions/*.{js,ts,jsx,tsx}` |\n| Custom dir | `[build] edge_functions = \"my-dir\"` (relative to base dir; keep it outside the publish dir) |\n| Name in toml | file name without extension (`auth.ts` → `function = \"auth\"`) |\n| Import map | any JSON file, referenced by `[functions] deno_import_map = \"./import_map.json\"` |\n\n## Return values\n\n| Return | Effect |\n|---|---|\n| `Response` | sent to client; chain ends |\n| `URL` | same-site rewrite, 200, address bar unchanged |\n| `undefined` / `return;` | skip this function; chain continues |\n\n### Endpoint\n```ts\nexport default async () =>\n new Response(\"Hello, World!\", { headers: { \"content-type\": \"text/html\" } });\nexport const config = { path: \"/api/hello\" };\n```\n\n### Redirect / rewrite\n```ts\nimport type { Context } from \"@netlify/edge-functions\";\n\nexport default async (req: Request, { cookies, geo }: Context) => {\n if (geo.city === \"Paris\" && cookies.get(\"promo-code\") === \"15-for-followers\") {\n return Response.redirect(new URL(\"/subscriber-sale\", req.url)); // redirect\n // or: return new URL(\"/subscriber-sale\", req.url); // rewrite (same-site only)\n }\n};\nexport const config = { path: \"/sale\" };\n```\nRewrites must target the same site. To reach other sites, use `fetch`.\n\n### Middleware (modify origin response)\n```ts\nimport type { Context } from \"@netlify/edge-functions\";\n\nexport default async (request: Request, context: Context) => {\n if (new URL(request.url).searchParams.get(\"method\") !== \"transform\") return;\n const response = await context.next();\n return new Response((await response.text()).toUpperCase(), response);\n};\nexport const config = { path: \"/blog/*\" };\n```\nCall `context.next()` only when you need the response body. If you just return `undefined`, the chain continues on its own.\n\n### Conditional requests\n```ts\nexport default async (req: Request, { next }: Context) => {\n const res = await next({ sendConditionalRequest: true });\n if (res.status === 304) return res;\n return new Response((await res.text()).toUpperCase(), res);\n};\n```\nBy default, `next()` strips conditional headers, so it always returns a full response.\n\n### Read body, then continue\n```ts\nexport default async (req: Request, context: Context) => {\n const body = await req.json();\n if (!isValid(body.access_token)) return new Response(\"forbidden\", { status: 403 });\n return context.next(new Request(req, { body: JSON.stringify(body) }));\n};\n```\n\n### Netlify user gate (private / team-login-protected projects)\n```ts\nimport type { Config, Context } from \"@netlify/edge-functions\";\n\nexport default async (req: Request, context: Context) => {\n const user = context.user; // undefined: public project, password protection, netlify dev\n if (!user) return new Response(\"Forbidden\", { status: 403 });\n const allowed = (Netlify.env.get(\"ADMIN_USER_IDS\") ?? \"\").split(\",\");\n if (!allowed.includes(user.id)) return new Response(\"Forbidden\", { status: 403 });\n // user.email may be undefined, so use it for display only\n};\nexport const config: Config = { path: \"/admin/*\" };\n```\n\n### Post-response work\n```ts\nexport default async (req: Request, context: Context) => {\n context.waitUntil(fetch(\"https://analytics.example.com/event\", { method: \"POST\" }));\n return new Response(\"ok\");\n};\n```\n`waitUntil` does not block the response, but it still counts against the 50 ms CPU limit.\n\n### Streaming SSR (`.tsx`)\n```tsx\nimport React from \"https://esm.sh/react\";\nimport { renderToReadableStream } from \"https://esm.sh/react-dom/server\";\nimport type { Config, Context } from \"@netlify/edge-functions\";\n\nexport default async (req: Request, context: Context) => {\n const stream = await renderToReadableStream(\n <html><body><h1>Hello {context.geo.country?.name}</h1></body></html>\n );\n return new Response(stream, { headers: { \"Content-Type\": \"text/html\" } });\n};\nexport const config: Config = { path: \"/hello\" };\n```\n\n## `Context`\n\n| Property | Notes |\n|---|---|\n| `cookies.get(name)` / `.set(options)` / `.delete(name \\| options)` | `set` and `delete` use `CookieStore` option format; they act on the outgoing response |\n| `geo` | `city`, `country.{code,name}`, `subdivision.{code,name}`, `latitude`, `longitude`, `timezone`, `postalCode` (format varies) |\n| `ip` | client IP |\n| `next(options?)` / `next(request, options?)` | `Promise<Response>` from the next item in the chain |\n| `params` | URLPattern named groups from `path` (`/pets/:name` → `{ name }`). For the query string, use `request.url` |\n| `user` | `{ id, email?, expiresAt }` or `undefined`. It is a Netlify account, not Netlify Identity; for Identity, use `getUser()` from `@netlify/identity` |\n| `waitUntil(promise)` | runs after the response is sent |\n| `requestId`, `account.id`, `server.region` | — |\n| `site` | `{ id, name, url }` |\n| `deploy` | `{ context, id, published, skewProtectionToken }` |\n\nNetlify adds no client-info headers to the request. Read client info from `context` instead.\n\n`Netlify.context` gives the same object, but only inside the handler. Outside it, it is `null`.\n\n`Netlify.env`: `get(name)`, `has(name)`, `toObject()`, and invocation-scoped `set` and `delete`. To change variables persistently, use the [env API](https://open-api.netlify.com/#tag/environmentVariables).\n\nWeb APIs:\n- `console`, `atob`, `btoa`\n- `fetch`, `Request`, `Response`, `URL`, `File`, `Blob`\n- `TextEncoder`/`TextDecoder` (and their Stream variants), `Performance`\n- Web Crypto: `randomUUID`, `getRandomValues`, `SubtleCrypto`\n- WebSocket\n- `setTimeout`, `clearTimeout`, `setInterval`\n- Streams: `ReadableStream`, `WritableStream`, `TransformStream`\n- URLPattern\n\nModules:\n- Node built-ins: use the `node:` prefix (`import { randomBytes } from \"node:crypto\"`).\n- Deno modules: import by URL, or through an import map.\n- npm packages (beta): import by name. Packages with native binaries or runtime dynamic imports may break.\n\n## Declarations\n\n### Inline `config`\n| Key | Value |\n|---|---|\n| `path` | URLPattern string or array; must start with `/` |\n| `excludedPath` | URLPattern string or array; must start with `/` |\n| `pattern` / `excludedPattern` | regex alternatives to `path` / `excludedPath` |\n| `method` | HTTP method string or array |\n| `header` | `{ name: true \\| false \\| \"regex\" }`; case-insensitive names; multi-value headers match the comma-joined list |\n| `onError` | `\"fail\"` (default), `\"/custom-path\"`, or `\"bypass\"` |\n| `cache` | `\"manual\"` |\n\n```ts\nexport const config: Config = {\n path: \"/*\",\n excludedPath: [\"/*.css\", \"/*.js\", \"/img/*\"],\n header: { \"user-agent\": \"(iPhone|Android)\" },\n};\n```\nThe `netlify-agent-category` request header maps any user-agent to a [client category](https://docs.netlify.com/build/user-agent-categories).\n\n### `netlify.toml`\nThe 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.\n\n```toml\n[[edge_functions]]\n path = \"/admin\"\n function = \"auth\"\n\n[[edge_functions]]\n path = \"/admin\"\n function = \"injector\"\n cache = \"manual\"\n\n[[edge_functions]]\n pattern = \"/products/(.*)\"\n excludedPattern = \"/products/things/(.*)\"\n function = \"highlight\"\n\n[[edge_functions]]\n path = \"/*\"\n excludedPath = \"/img/*\"\n function = \"common\"\n [edge_functions.header]\n x-required = true\n x-forbidden = false\n```\nA request to `/admin` runs `auth`, then `common`, then `injector`.\n\n### Order\nNetlify 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.\n\n1. Framework-generated functions declared in a config file.\n2. Your `netlify.toml` declarations, top to bottom.\n3. Framework- and integration-generated inline declarations.\n4. Your inline declarations, alphabetical by file name.\n\nIf the same function is declared both in toml and inline, the configs are merged and treated as step 4; inline wins for duplicate fields.\n\nAfter 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.\n\nAn edge function declared on the *target* of a static rewrite does not run for rewritten requests.\n\n## Response caching\n```ts\nimport type { Config } from \"@netlify/edge-functions\";\n\nexport default async () =>\n new Response(\"Hello world\", { headers: { \"cache-control\": \"public, s-maxage=3600\" } });\n\nexport const config: Config = { path: \"/hello\", cache: \"manual\" };\n```\n- Headers must be set in the function code. Supported headers:\n - `Cache-Control`, `CDN-Cache-Control`, `Netlify-CDN-Cache-Control`\n - `Expires` (overridden by `max-age`/`s-maxage`)\n - `Vary`, `Netlify-Vary`\n- See [caching overview](https://docs.netlify.com/build/caching/caching-overview).\n- A new deploy in the same deploy context invalidates cached responses.\n- Cached hits skip invocation, and they do not count toward invocation limits.\n- **Cache** reusable endpoint output, such as SSR.\n- **Don't cache** routing or personalization middleware, such as cookie-based product ordering.\n- Local dev has no cache. Cache headers are ignored locally.\n\n## Error handling (`onError`)\n| Value | Effect |\n|---|---|\n| `\"fail\"` (default) | chain stops; generic error page is shown |\n| `\"/unavailable\"` | rewrite to that same-site path; edge functions on it are not invoked |\n| `\"bypass\"` | skip the failing function; chain continues |\n\nFail 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.\n\n## Environment variables\n- Variables must have the **Functions** scope.\n- **Build**-scoped variables exist only at build time; embed their values during the build if needed.\n- Changing a variable requires a new deploy.\n- Deploy info (site, region, deploy id) comes from `context`, not from env vars.\n\n## Local dev / deploy / logs\n- Run `npm install netlify-cli -g`, then `netlify dev`. Visit `http://localhost:8888/<path>`.\n - Changes apply on the next request.\n - Debug with `--edge-inspect` or `--edge-inspect-brk`.\n - Mock location with `--geo=mock` (San Francisco), or `--geo=mock --country=DE`.\n - `context.user` is undefined locally.\n- Manual deploys require CLI **≥ 12.2.8**. Deploys are atomic, and Deploy Previews and rollbacks include edge functions.\n- Logs: in the Netlify UI, go to **Cloud compute > Edge functions** (`https://app.netlify.com/projects/{site_name}/edge-functions`).\n - For older deploys: **Deploys** → open the deploy → **Edge Functions**.\n - `console.log` output is tagged with the function name.\n - Retention is ≥ 24 h (7 days on some plans).\n - [Log Drains](https://docs.netlify.com/manage/monitoring/log-drains) are available on Enterprise plans.\n\n## Limits\n| Limit | Value |\n|---|---|\n| Bundle size | 20 MB compressed |\n| Memory (per set of deployed functions) | 512 MB |\n| CPU time per request | 50 ms (excludes I/O wait) |\n| Response header timeout | 40 s |\n\n- Prerendering does not apply to paths served by an edge function.\n- Multiple framework plugins that generate edge functions may collide.\n\nDocs: [API](https://docs.netlify.com/build/edge-functions/api.md) · [Declarations](https://docs.netlify.com/build/edge-functions/declarations.md) · [Optional configuration](https://docs.netlify.com/build/edge-functions/optional-configuration.md) · [Limits](https://docs.netlify.com/build/edge-functions/limits.md) · [Examples](https://edge-functions-examples.netlify.app/)\n\n<!-- Gaps: no legacy/deprecated handler form is documented; whether `method` works in netlify.toml is unstated. -->\n<!-- Undocumented: context.params with regex `pattern` declarations; monthly invocation limits per plan. -->\n<!-- Undocumented: whether Netlify uses Fetchable module members other than `fetch`. -->\n\n<!-- system: agent-context/edge-functions/system.md — human-owned, merged by ctx-gen; edit system.md, not this section -->\n# Netlify house rules (edge-functions)\n\nThese are org conventions and field-learned guardrails, not docs facts — they\nare merged into the rendered skill by ctx-gen and are never generated.\nExtracted from the previous hand-written netlify-edge-functions skill; owned\nby the skills maintainer.\n\n1. Check the framework's adapter/reference first: a custom edge function that\n duplicates adapter-generated middleware causes conflicts. Only hand-write\n an edge function when the framework doesn't already generate one for the\n job.\n2. Scope `path` narrowly. `path: \"/*\"` intercepts every request — including\n static assets — adding latency to each one and billing an edge invocation\n for it.\n3. An edge function without a route (no config export, no netlify.toml\n declaration) still deploys, but silently never runs: no build error, no\n warning. When \"my edge function does nothing\", check the route first.\n4. Choose edge vs serverless by workload shape: edge functions for low-latency\n request/response manipulation, geolocation logic, auth checks/redirects,\n and A/B personalization; serverless functions for long-running work (up to\n 15 min), heavy Node.js dependencies, database-heavy operations,\n background/scheduled tasks, or memory needs above 512 MB.\n5. Cache headers on an edge response do nothing without `cache: \"manual\"` in\n config — it's both or neither. Setting `Cache-Control` on the returned\n `Response` has no effect unless the function also opts in.\n6. When explaining declaration processing order, state the two-pass loop,\n not just the ordering: Netlify runs the whole declaration order TWICE —\n first pass runs only edge functions not configured for caching, second\n pass runs the ones with caching configured. \"Non-cached before cached\"\n without the loop framing is an incomplete answer.\n7. On a private project or one with team login protection, `context.user`\n is the Netlify user who made the request (`id`, `email`, `expiresAt`).\n Use it for per-person checks and personalization instead of adding a\n second login, and never take identity from client-sent headers or\n cookies: Netlify verifies the login before the edge function runs. Every\n example must handle `context.user` being `undefined` (public projects,\n basic password protection, `netlify dev`), and `email` can be\n `undefined` too, so key decisions on `id`. This is a Netlify account,\n not a Netlify Identity user.\n"Full snapshot data
{
"description": "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.",
"included_files": [],
"name": "netlify-edge-functions",
"skill_md_contents": "---\nname: netlify-edge-functions\ndescription: 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.\n---\n\n# Netlify Edge Functions\n\n## Use this form\n\n```ts\n// netlify/edge-functions/hello.ts\nimport type { Config, Context } from \"@netlify/edge-functions\";\n\nexport default async (request: Request, context: Context) => {\n return new Response(`Hello from ${context.geo.country?.name ?? \"somewhere\"}`);\n};\n\nexport const config: Config = { path: \"/hello\" };\n```\n\n- One file = one function: a default-export handler plus a **named** `config` export with the route. Alternatively, declare the route in `netlify.toml`.\n- The default export can also be a [Fetchable module](https://fetchable.org/): an object with a `fetch` method. Netlify calls `fetch` with the same `(request, context)` arguments and uses its return value the same way; inside `fetch`, `this` is the exported object. Use it to share one handler with other platforms that accept Fetchable modules.\n ```ts\n export default {\n async fetch(request: Request, context: Context) {\n return new Response(\"Hello\");\n },\n };\n export const config: Config = { path: \"/hello\" }; // still a named export\n ```\n- `Request` and `Response` are global. Import `Context` and `Config` types from `@netlify/edge-functions`.\n- Read env vars with `Netlify.env.get()`. `process.env` works only for Next.js middleware.\n\n**Avoid these:**\n- A file with no `config.path` or `pattern` and no `[[edge_functions]]` entry. It deploys but never runs.\n- Import maps in `deno.json`. They are unsupported. Use a separate file with `[functions] deno_import_map`.\n- Variables set in `netlify.toml`. They are invisible to edge functions.\n- `Netlify.env.set()` or `Netlify.env.delete()` as persistence. They affect only the current invocation.\n- `fetch()` to the same site for the current path. Use `context.next()` instead.\n\n## ⚠️ Footguns\n\n- **No route = silent no-op.** Edge functions get no automatic URL.\n- **`path: \"/*\"` runs on every request**, including assets. Narrow it, or add `excludedPath`.\n- **Caching needs both parts:** `cache: \"manual\"` in config AND cache headers on the returned `Response`. With only one, nothing is cached.\n- **Cached functions shadow static files.** A cached function on `/*` serves `/cat.png` instead of the file.\n- **Returning a `Response` ends the chain.** Redirect rules for that path never run.\n- **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.\n- **The request body can be read once.** After `await req.json()`, pass `new Request(req, { body })` to `context.next()`.\n- **Same-named `foo.ts` and `foo.js`:** the TS file is ignored and the JS file deploys.\n- **50 ms CPU per request**, including `waitUntil` work.\n- **Not executed** on sites with Split Testing enabled.\n- **Custom Headers and basic-auth headers do not apply** to edge functions.\n- **Not supported** on HIPAA-compliant hosting.\n- **`netlify.app` is on the Public Suffix List.** Cross-subdomain cookies need a custom domain.\n\n## Files\n\n| What | Where |\n|---|---|\n| Functions | `<base>/netlify/edge-functions/*.{js,ts,jsx,tsx}` |\n| Custom dir | `[build] edge_functions = \"my-dir\"` (relative to base dir; keep it outside the publish dir) |\n| Name in toml | file name without extension (`auth.ts` → `function = \"auth\"`) |\n| Import map | any JSON file, referenced by `[functions] deno_import_map = \"./import_map.json\"` |\n\n## Return values\n\n| Return | Effect |\n|---|---|\n| `Response` | sent to client; chain ends |\n| `URL` | same-site rewrite, 200, address bar unchanged |\n| `undefined` / `return;` | skip this function; chain continues |\n\n### Endpoint\n```ts\nexport default async () =>\n new Response(\"Hello, World!\", { headers: { \"content-type\": \"text/html\" } });\nexport const config = { path: \"/api/hello\" };\n```\n\n### Redirect / rewrite\n```ts\nimport type { Context } from \"@netlify/edge-functions\";\n\nexport default async (req: Request, { cookies, geo }: Context) => {\n if (geo.city === \"Paris\" && cookies.get(\"promo-code\") === \"15-for-followers\") {\n return Response.redirect(new URL(\"/subscriber-sale\", req.url)); // redirect\n // or: return new URL(\"/subscriber-sale\", req.url); // rewrite (same-site only)\n }\n};\nexport const config = { path: \"/sale\" };\n```\nRewrites must target the same site. To reach other sites, use `fetch`.\n\n### Middleware (modify origin response)\n```ts\nimport type { Context } from \"@netlify/edge-functions\";\n\nexport default async (request: Request, context: Context) => {\n if (new URL(request.url).searchParams.get(\"method\") !== \"transform\") return;\n const response = await context.next();\n return new Response((await response.text()).toUpperCase(), response);\n};\nexport const config = { path: \"/blog/*\" };\n```\nCall `context.next()` only when you need the response body. If you just return `undefined`, the chain continues on its own.\n\n### Conditional requests\n```ts\nexport default async (req: Request, { next }: Context) => {\n const res = await next({ sendConditionalRequest: true });\n if (res.status === 304) return res;\n return new Response((await res.text()).toUpperCase(), res);\n};\n```\nBy default, `next()` strips conditional headers, so it always returns a full response.\n\n### Read body, then continue\n```ts\nexport default async (req: Request, context: Context) => {\n const body = await req.json();\n if (!isValid(body.access_token)) return new Response(\"forbidden\", { status: 403 });\n return context.next(new Request(req, { body: JSON.stringify(body) }));\n};\n```\n\n### Netlify user gate (private / team-login-protected projects)\n```ts\nimport type { Config, Context } from \"@netlify/edge-functions\";\n\nexport default async (req: Request, context: Context) => {\n const user = context.user; // undefined: public project, password protection, netlify dev\n if (!user) return new Response(\"Forbidden\", { status: 403 });\n const allowed = (Netlify.env.get(\"ADMIN_USER_IDS\") ?? \"\").split(\",\");\n if (!allowed.includes(user.id)) return new Response(\"Forbidden\", { status: 403 });\n // user.email may be undefined, so use it for display only\n};\nexport const config: Config = { path: \"/admin/*\" };\n```\n\n### Post-response work\n```ts\nexport default async (req: Request, context: Context) => {\n context.waitUntil(fetch(\"https://analytics.example.com/event\", { method: \"POST\" }));\n return new Response(\"ok\");\n};\n```\n`waitUntil` does not block the response, but it still counts against the 50 ms CPU limit.\n\n### Streaming SSR (`.tsx`)\n```tsx\nimport React from \"https://esm.sh/react\";\nimport { renderToReadableStream } from \"https://esm.sh/react-dom/server\";\nimport type { Config, Context } from \"@netlify/edge-functions\";\n\nexport default async (req: Request, context: Context) => {\n const stream = await renderToReadableStream(\n <html><body><h1>Hello {context.geo.country?.name}</h1></body></html>\n );\n return new Response(stream, { headers: { \"Content-Type\": \"text/html\" } });\n};\nexport const config: Config = { path: \"/hello\" };\n```\n\n## `Context`\n\n| Property | Notes |\n|---|---|\n| `cookies.get(name)` / `.set(options)` / `.delete(name \\| options)` | `set` and `delete` use `CookieStore` option format; they act on the outgoing response |\n| `geo` | `city`, `country.{code,name}`, `subdivision.{code,name}`, `latitude`, `longitude`, `timezone`, `postalCode` (format varies) |\n| `ip` | client IP |\n| `next(options?)` / `next(request, options?)` | `Promise<Response>` from the next item in the chain |\n| `params` | URLPattern named groups from `path` (`/pets/:name` → `{ name }`). For the query string, use `request.url` |\n| `user` | `{ id, email?, expiresAt }` or `undefined`. It is a Netlify account, not Netlify Identity; for Identity, use `getUser()` from `@netlify/identity` |\n| `waitUntil(promise)` | runs after the response is sent |\n| `requestId`, `account.id`, `server.region` | — |\n| `site` | `{ id, name, url }` |\n| `deploy` | `{ context, id, published, skewProtectionToken }` |\n\nNetlify adds no client-info headers to the request. Read client info from `context` instead.\n\n`Netlify.context` gives the same object, but only inside the handler. Outside it, it is `null`.\n\n`Netlify.env`: `get(name)`, `has(name)`, `toObject()`, and invocation-scoped `set` and `delete`. To change variables persistently, use the [env API](https://open-api.netlify.com/#tag/environmentVariables).\n\nWeb APIs:\n- `console`, `atob`, `btoa`\n- `fetch`, `Request`, `Response`, `URL`, `File`, `Blob`\n- `TextEncoder`/`TextDecoder` (and their Stream variants), `Performance`\n- Web Crypto: `randomUUID`, `getRandomValues`, `SubtleCrypto`\n- WebSocket\n- `setTimeout`, `clearTimeout`, `setInterval`\n- Streams: `ReadableStream`, `WritableStream`, `TransformStream`\n- URLPattern\n\nModules:\n- Node built-ins: use the `node:` prefix (`import { randomBytes } from \"node:crypto\"`).\n- Deno modules: import by URL, or through an import map.\n- npm packages (beta): import by name. Packages with native binaries or runtime dynamic imports may break.\n\n## Declarations\n\n### Inline `config`\n| Key | Value |\n|---|---|\n| `path` | URLPattern string or array; must start with `/` |\n| `excludedPath` | URLPattern string or array; must start with `/` |\n| `pattern` / `excludedPattern` | regex alternatives to `path` / `excludedPath` |\n| `method` | HTTP method string or array |\n| `header` | `{ name: true \\| false \\| \"regex\" }`; case-insensitive names; multi-value headers match the comma-joined list |\n| `onError` | `\"fail\"` (default), `\"/custom-path\"`, or `\"bypass\"` |\n| `cache` | `\"manual\"` |\n\n```ts\nexport const config: Config = {\n path: \"/*\",\n excludedPath: [\"/*.css\", \"/*.js\", \"/img/*\"],\n header: { \"user-agent\": \"(iPhone|Android)\" },\n};\n```\nThe `netlify-agent-category` request header maps any user-agent to a [client category](https://docs.netlify.com/build/user-agent-categories).\n\n### `netlify.toml`\nThe 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.\n\n```toml\n[[edge_functions]]\n path = \"/admin\"\n function = \"auth\"\n\n[[edge_functions]]\n path = \"/admin\"\n function = \"injector\"\n cache = \"manual\"\n\n[[edge_functions]]\n pattern = \"/products/(.*)\"\n excludedPattern = \"/products/things/(.*)\"\n function = \"highlight\"\n\n[[edge_functions]]\n path = \"/*\"\n excludedPath = \"/img/*\"\n function = \"common\"\n [edge_functions.header]\n x-required = true\n x-forbidden = false\n```\nA request to `/admin` runs `auth`, then `common`, then `injector`.\n\n### Order\nNetlify 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.\n\n1. Framework-generated functions declared in a config file.\n2. Your `netlify.toml` declarations, top to bottom.\n3. Framework- and integration-generated inline declarations.\n4. Your inline declarations, alphabetical by file name.\n\nIf the same function is declared both in toml and inline, the configs are merged and treated as step 4; inline wins for duplicate fields.\n\nAfter 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.\n\nAn edge function declared on the *target* of a static rewrite does not run for rewritten requests.\n\n## Response caching\n```ts\nimport type { Config } from \"@netlify/edge-functions\";\n\nexport default async () =>\n new Response(\"Hello world\", { headers: { \"cache-control\": \"public, s-maxage=3600\" } });\n\nexport const config: Config = { path: \"/hello\", cache: \"manual\" };\n```\n- Headers must be set in the function code. Supported headers:\n - `Cache-Control`, `CDN-Cache-Control`, `Netlify-CDN-Cache-Control`\n - `Expires` (overridden by `max-age`/`s-maxage`)\n - `Vary`, `Netlify-Vary`\n- See [caching overview](https://docs.netlify.com/build/caching/caching-overview).\n- A new deploy in the same deploy context invalidates cached responses.\n- Cached hits skip invocation, and they do not count toward invocation limits.\n- **Cache** reusable endpoint output, such as SSR.\n- **Don't cache** routing or personalization middleware, such as cookie-based product ordering.\n- Local dev has no cache. Cache headers are ignored locally.\n\n## Error handling (`onError`)\n| Value | Effect |\n|---|---|\n| `\"fail\"` (default) | chain stops; generic error page is shown |\n| `\"/unavailable\"` | rewrite to that same-site path; edge functions on it are not invoked |\n| `\"bypass\"` | skip the failing function; chain continues |\n\nFail 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.\n\n## Environment variables\n- Variables must have the **Functions** scope.\n- **Build**-scoped variables exist only at build time; embed their values during the build if needed.\n- Changing a variable requires a new deploy.\n- Deploy info (site, region, deploy id) comes from `context`, not from env vars.\n\n## Local dev / deploy / logs\n- Run `npm install netlify-cli -g`, then `netlify dev`. Visit `http://localhost:8888/<path>`.\n - Changes apply on the next request.\n - Debug with `--edge-inspect` or `--edge-inspect-brk`.\n - Mock location with `--geo=mock` (San Francisco), or `--geo=mock --country=DE`.\n - `context.user` is undefined locally.\n- Manual deploys require CLI **≥ 12.2.8**. Deploys are atomic, and Deploy Previews and rollbacks include edge functions.\n- Logs: in the Netlify UI, go to **Cloud compute > Edge functions** (`https://app.netlify.com/projects/{site_name}/edge-functions`).\n - For older deploys: **Deploys** → open the deploy → **Edge Functions**.\n - `console.log` output is tagged with the function name.\n - Retention is ≥ 24 h (7 days on some plans).\n - [Log Drains](https://docs.netlify.com/manage/monitoring/log-drains) are available on Enterprise plans.\n\n## Limits\n| Limit | Value |\n|---|---|\n| Bundle size | 20 MB compressed |\n| Memory (per set of deployed functions) | 512 MB |\n| CPU time per request | 50 ms (excludes I/O wait) |\n| Response header timeout | 40 s |\n\n- Prerendering does not apply to paths served by an edge function.\n- Multiple framework plugins that generate edge functions may collide.\n\nDocs: [API](https://docs.netlify.com/build/edge-functions/api.md) · [Declarations](https://docs.netlify.com/build/edge-functions/declarations.md) · [Optional configuration](https://docs.netlify.com/build/edge-functions/optional-configuration.md) · [Limits](https://docs.netlify.com/build/edge-functions/limits.md) · [Examples](https://edge-functions-examples.netlify.app/)\n\n<!-- Gaps: no legacy/deprecated handler form is documented; whether `method` works in netlify.toml is unstated. -->\n<!-- Undocumented: context.params with regex `pattern` declarations; monthly invocation limits per plan. -->\n<!-- Undocumented: whether Netlify uses Fetchable module members other than `fetch`. -->\n\n<!-- system: agent-context/edge-functions/system.md — human-owned, merged by ctx-gen; edit system.md, not this section -->\n# Netlify house rules (edge-functions)\n\nThese are org conventions and field-learned guardrails, not docs facts — they\nare merged into the rendered skill by ctx-gen and are never generated.\nExtracted from the previous hand-written netlify-edge-functions skill; owned\nby the skills maintainer.\n\n1. Check the framework's adapter/reference first: a custom edge function that\n duplicates adapter-generated middleware causes conflicts. Only hand-write\n an edge function when the framework doesn't already generate one for the\n job.\n2. Scope `path` narrowly. `path: \"/*\"` intercepts every request — including\n static assets — adding latency to each one and billing an edge invocation\n for it.\n3. An edge function without a route (no config export, no netlify.toml\n declaration) still deploys, but silently never runs: no build error, no\n warning. When \"my edge function does nothing\", check the route first.\n4. Choose edge vs serverless by workload shape: edge functions for low-latency\n request/response manipulation, geolocation logic, auth checks/redirects,\n and A/B personalization; serverless functions for long-running work (up to\n 15 min), heavy Node.js dependencies, database-heavy operations,\n background/scheduled tasks, or memory needs above 512 MB.\n5. Cache headers on an edge response do nothing without `cache: \"manual\"` in\n config — it's both or neither. Setting `Cache-Control` on the returned\n `Response` has no effect unless the function also opts in.\n6. When explaining declaration processing order, state the two-pass loop,\n not just the ordering: Netlify runs the whole declaration order TWICE —\n first pass runs only edge functions not configured for caching, second\n pass runs the ones with caching configured. \"Non-cached before cached\"\n without the loop framing is an incomplete answer.\n7. On a private project or one with team login protection, `context.user`\n is the Netlify user who made the request (`id`, `email`, `expiresAt`).\n Use it for per-person checks and personalization instead of adding a\n second login, and never take identity from client-sent headers or\n cookies: Netlify verifies the login before the edge function runs. Every\n example must handle `context.user` being `undefined` (public projects,\n basic password protection, `netlify dev`), and `email` can be\n `undefined` too, so key decisions on `id`. This is a Netlify account,\n not a Netlify Identity user.\n"
}SHA-256 of public snapshot: 77c12a039a082108512433286901d57bd7ee76373751e40ed038cc6a9c1e305f