netlify-edge-functions

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Netlify Edge Functions

Netlify Edge Functions

Edge functions run on Netlify's globally distributed edge network (Deno runtime), providing low-latency responses close to users.
Edge Functions运行在Netlify的全球分布式边缘网络上(基于Deno runtime),可在靠近用户的位置提供低延迟响应。

Syntax

语法

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

export default async (req: Request, context: Context) => {
  return new Response("Hello from the edge!");
};

export const config: Config = {
  path: "/hello",
};
Place files in
netlify/edge-functions/
. Uses
.ts
,
.js
,
.tsx
, or
.jsx
extensions.
typescript
import type { Config, Context } from "@netlify/edge-functions";

export default async (req: Request, context: Context) => {
  return new Response("Hello from the edge!");
};

export const config: Config = {
  path: "/hello",
};
请将文件放在
netlify/edge-functions/
目录下,支持
.ts
.js
.tsx
.jsx
后缀。

Config Object

配置对象

typescript
export const config: Config = {
  path: "/api/*",                    // URLPattern path(s)
  excludedPath: "/api/public/*",     // Exclusions
  method: ["GET", "POST"],           // HTTP methods
  onError: "bypass",                 // "fail" (default), "bypass", or "/error-page"
  cache: "manual",                   // Enable response caching
};
typescript
export const config: Config = {
  path: "/api/*",                    // URLPattern path(s)
  excludedPath: "/api/public/*",     // Exclusions
  method: ["GET", "POST"],           // HTTP methods
  onError: "bypass",                 // "fail" (default), "bypass", or "/error-page"
  cache: "manual",                   // Enable response caching
};

Middleware Pattern

中间件模式

Use
context.next()
to invoke the next handler in the chain and optionally modify the response:
typescript
export default async (req: Request, context: Context) => {
  // Before: modify request or short-circuit
  if (!isAuthenticated(req)) {
    return new Response("Unauthorized", { status: 401 });
  }

  // Continue to origin/next function
  const response = await context.next();

  // After: modify response
  response.headers.set("x-custom-header", "value");
  return response;
};
Return
undefined
to pass through without modification:
typescript
export default async (req: Request, context: Context) => {
  if (!shouldHandle(req)) return; // continues to next handler
  return new Response("Handled");
};
使用
context.next()
调用链路中的下一个处理程序,还可按需修改响应:
typescript
export default async (req: Request, context: Context) => {
  // Before: modify request or short-circuit
  if (!isAuthenticated(req)) {
    return new Response("Unauthorized", { status: 401 });
  }

  // Continue to origin/next function
  const response = await context.next();

  // After: modify response
  response.headers.set("x-custom-header", "value");
  return response;
};
返回
undefined
即可不做任何修改直接透传:
typescript
export default async (req: Request, context: Context) => {
  if (!shouldHandle(req)) return; // continues to next handler
  return new Response("Handled");
};

Geolocation and IP

地理定位与IP

typescript
export default async (req: Request, context: Context) => {
  const { city, country, subdivision, timezone } = context.geo;
  const ip = context.ip;

  if (country?.code === "DE") {
    return Response.redirect(new URL("/de", req.url));
  }
};
Local dev with mocked geo:
netlify dev --geo=mock --country=US
typescript
export default async (req: Request, context: Context) => {
  const { city, country, subdivision, timezone } = context.geo;
  const ip = context.ip;

  if (country?.code === "DE") {
    return Response.redirect(new URL("/de", req.url));
  }
};
本地开发时可使用模拟地理定位:
netlify dev --geo=mock --country=US

Environment Variables

环境变量

Use
Netlify.env
(not
process.env
or
Deno.env
):
typescript
const secret = Netlify.env.get("API_SECRET");
使用
Netlify.env
(不要使用
process.env
Deno.env
):
typescript
const secret = Netlify.env.get("API_SECRET");

Module Support

模块支持

  • Node.js builtins:
    import { randomBytes } from "node:crypto";
  • npm packages: Install via npm and import by name
  • Deno modules: URL imports (e.g.,
    import X from "https://esm.sh/package"
    )
For URL imports, use an import map:
json
// import_map.json
{ "imports": { "html-rewriter": "https://ghuc.cc/worker-tools/html-rewriter/index.ts" } }
toml
undefined
  • Node.js内置模块
    import { randomBytes } from "node:crypto";
  • npm包:通过npm安装后直接按名称导入
  • Deno模块:URL导入(例如
    import X from "https://esm.sh/package"
若使用URL导入,可配置导入映射:
json
// import_map.json
{ "imports": { "html-rewriter": "https://ghuc.cc/worker-tools/html-rewriter/index.ts" } }
toml
undefined

netlify.toml

netlify.toml

[functions] deno_import_map = "./import_map.json"
undefined
[functions] deno_import_map = "./import_map.json"
undefined

When to Use Edge vs Serverless

边缘计算 vs Serverless 选型建议

Use Edge Functions forUse Serverless Functions for
Low-latency responsesLong-running operations (up to 15 min)
Request/response manipulationComplex Node.js dependencies
Geolocation-based logicDatabase-heavy operations
Auth checks and redirectsBackground/scheduled tasks
A/B testing, personalizationTasks needing > 512 MB memory
适用Edge Functions的场景适用Serverless Functions的场景
低延迟响应长时间运行的任务(最长15分钟)
请求/响应处理依赖复杂Node.js模块的场景
基于地理位置的逻辑重度数据库操作
身份校验与重定向后台/定时任务
A/B测试、个性化定制需要超过512MB内存的任务

Limits

使用限制

ResourceLimit
CPU time50 ms per request
Memory512 MB per deployed set
Response header timeout40 seconds
Code size20 MB compressed
资源限制
CPU时间单请求50ms
内存每个部署实例集512MB
响应头超时40秒
代码体积压缩后20MB