netlify-edge-functions
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNetlify 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 . Uses , , , or extensions.
netlify/edge-functions/.ts.js.tsx.jsxtypescript
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.jsxConfig 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 to invoke the next handler in the chain and optionally modify the response:
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;
};Return to pass through without modification:
undefinedtypescript
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;
};返回即可不做任何修改直接透传:
undefinedtypescript
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=UStypescript
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=USEnvironment Variables
环境变量
Use (not or ):
Netlify.envprocess.envDeno.envtypescript
const secret = Netlify.env.get("API_SECRET");使用(不要使用或):
Netlify.envprocess.envDeno.envtypescript
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
undefinednetlify.toml
netlify.toml
[functions]
deno_import_map = "./import_map.json"
undefined[functions]
deno_import_map = "./import_map.json"
undefinedWhen to Use Edge vs Serverless
边缘计算 vs Serverless 选型建议
| Use Edge Functions for | Use Serverless Functions for |
|---|---|
| Low-latency responses | Long-running operations (up to 15 min) |
| Request/response manipulation | Complex Node.js dependencies |
| Geolocation-based logic | Database-heavy operations |
| Auth checks and redirects | Background/scheduled tasks |
| A/B testing, personalization | Tasks needing > 512 MB memory |
| 适用Edge Functions的场景 | 适用Serverless Functions的场景 |
|---|---|
| 低延迟响应 | 长时间运行的任务(最长15分钟) |
| 请求/响应处理 | 依赖复杂Node.js模块的场景 |
| 基于地理位置的逻辑 | 重度数据库操作 |
| 身份校验与重定向 | 后台/定时任务 |
| A/B测试、个性化定制 | 需要超过512MB内存的任务 |
Limits
使用限制
| Resource | Limit |
|---|---|
| CPU time | 50 ms per request |
| Memory | 512 MB per deployed set |
| Response header timeout | 40 seconds |
| Code size | 20 MB compressed |
| 资源 | 限制 |
|---|---|
| CPU时间 | 单请求50ms |
| 内存 | 每个部署实例集512MB |
| 响应头超时 | 40秒 |
| 代码体积 | 压缩后20MB |