netlify-functions
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNetlify Functions
Netlify Functions
Modern Syntax
现代语法
Always use the modern default export + Config pattern. Never use the legacy or named export.
exports.handlerhandlertypescript
import type { Context, Config } from "@netlify/functions";
export default async (req: Request, context: Context) => {
return new Response("Hello, world!");
};
export const config: Config = {
path: "/api/hello",
};The handler receives a standard Web API and returns a . The second argument is a Netlify object.
RequestResponseContext始终使用现代的默认导出 + Config模式,禁止使用旧版的或命名导出。
exports.handlerhandlertypescript
import type { Context, Config } from "@netlify/functions";
export default async (req: Request, context: Context) => {
return new Response("Hello, world!");
};
export const config: Config = {
path: "/api/hello",
};handler接收标准Web API 对象并返回对象,第二个参数为Netlify 对象。
RequestResponseContextFile Structure
文件结构
Place functions in :
netlify/functions/netlify/functions/
_shared/ # Non-function shared code (underscore prefix)
auth.ts
db.ts
items.ts # -> /.netlify/functions/items (or custom path via config)
users/index.ts # -> /.netlify/functions/usersUse or extensions. If both and exist with the same name, the file takes precedence.
.ts.mts.ts.js.js将函数放在目录下:
netlify/functions/netlify/functions/
_shared/ # 非函数类共享代码(下划线前缀)
auth.ts
db.ts
items.ts # -> /.netlify/functions/items(或通过config配置自定义路径)
users/index.ts # -> /.netlify/functions/users使用或后缀,若存在同名的和文件,文件优先级更高。
.ts.mts.ts.js.jsPath Routing
路径路由
Define custom paths via the export:
configtypescript
export const config: Config = {
path: "/api/items", // Static path
// path: "/api/items/:id", // Path parameter
// path: ["/api/items", "/api/items/:id"], // Multiple paths
// excludedPath: "/api/items/special", // Excluded paths
// preferStatic: true, // Don't override static files
};Without a config, functions are available at . Setting a makes the function available only at that path.
path/.netlify/functions/{name}pathAccess path parameters via :
context.paramstypescript
// config: { path: "/api/items/:id" }
export default async (req: Request, context: Context) => {
const { id } = context.params;
// ...
};通过导出的定义自定义路径:
configtypescript
export const config: Config = {
path: "/api/items", // 静态路径
// path: "/api/items/:id", // 路径参数
// path: ["/api/items", "/api/items/:id"], // 多路径配置
// excludedPath: "/api/items/special", // 排除路径
// preferStatic: true, // 不覆盖静态文件
};未配置时,函数的访问地址为;设置后,函数仅可通过该路径访问。
path/.netlify/functions/{函数名}path通过获取路径参数:
context.paramstypescript
// config: { path: "/api/items/:id" }
export default async (req: Request, context: Context) => {
const { id } = context.params;
// ...
};Method Routing
请求方法路由
typescript
export default async (req: Request, context: Context) => {
switch (req.method) {
case "GET": return handleGet(context.params.id);
case "POST": return handlePost(await req.json());
case "DELETE": return handleDelete(context.params.id);
default: return new Response("Method not allowed", { status: 405 });
}
};
export const config: Config = {
path: "/api/items/:id",
method: ["GET", "POST", "DELETE"],
};typescript
export default async (req: Request, context: Context) => {
switch (req.method) {
case "GET": return handleGet(context.params.id);
case "POST": return handlePost(await req.json());
case "DELETE": return handleDelete(context.params.id);
default: return new Response("Method not allowed", { status: 405 });
}
};
export const config: Config = {
path: "/api/items/:id",
method: ["GET", "POST", "DELETE"],
};Background Functions
后台函数
For long-running tasks (up to 15 minutes). The client receives an immediate response; return values are ignored.
202Name the file with a suffix:
-backgroundnetlify/functions/process-background.tsStore results externally (Netlify Blobs, database) for later retrieval.
用于运行长时任务(最长15分钟),客户端会立即收到响应,函数返回值会被忽略。
202文件名使用后缀:
-backgroundnetlify/functions/process-background.ts请将结果存储在外部服务(Netlify Blobs、数据库)中供后续查询。
Scheduled Functions
定时函数
Run on a cron schedule (UTC timezone):
typescript
export default async (req: Request) => {
const { next_run } = await req.json();
console.log("Next invocation at:", next_run);
};
export const config: Config = {
schedule: "@hourly", // or cron: "0 * * * *"
};Shortcuts: , , , , . Scheduled functions have a 30-second timeout and only run on published deploys.
@yearly@monthly@weekly@daily@hourly按cron表达式定时运行(时区为UTC):
typescript
export default async (req: Request) => {
const { next_run } = await req.json();
console.log("Next invocation at:", next_run);
};
export const config: Config = {
schedule: "@hourly", // 或cron表达式: "0 * * * *"
};快捷表达式:、、、、。定时函数超时时间为30秒,且仅在已发布的部署版本中运行。
@yearly@monthly@weekly@daily@hourlyStreaming Responses
流式响应
Return a body for streamed responses (up to 20 MB):
ReadableStreamtypescript
export default async (req: Request) => {
const stream = new ReadableStream({ /* ... */ });
return new Response(stream, {
headers: { "Content-Type": "text/event-stream" },
});
};返回类型的body实现流式响应(最大20 MB):
ReadableStreamtypescript
export default async (req: Request) => {
const stream = new ReadableStream({ /* ... */ });
return new Response(stream, {
headers: { "Content-Type": "text/event-stream" },
});
};Context Object
Context对象
| Property | Description |
|---|---|
| Path parameters from config |
| |
| Client IP address |
| |
| |
| |
| Team account ID |
| Unique request ID |
| Extend execution after response is sent |
| 属性 | 说明 |
|---|---|
| 来自配置的路径参数 |
| 地理位置信息: |
| 客户端IP地址 |
| 提供 |
| 部署信息: |
| 站点信息: |
| 团队账户ID |
| 唯一请求ID |
| 发送响应后延长函数执行时间 |
Environment Variables
环境变量
Use (not ) inside functions:
Netlify.envprocess.envtypescript
const apiKey = Netlify.env.get("API_KEY");在函数内部使用获取环境变量(不要使用):
Netlify.envprocess.envtypescript
const apiKey = Netlify.env.get("API_KEY");Resource Limits
资源限制
| Resource | Limit |
|---|---|
| Synchronous timeout | 60 seconds |
| Background timeout | 15 minutes |
| Scheduled timeout | 30 seconds |
| Memory | 1024 MB |
| Buffered payload | 6 MB |
| Streamed payload | 20 MB |
| 资源 | 限制 |
|---|---|
| 同步函数超时时间 | 60秒 |
| 后台函数超时时间 | 15分钟 |
| 定时函数超时时间 | 30秒 |
| 内存 | 1024 MB |
| 缓冲负载 | 6 MB |
| 流式负载 | 20 MB |
Framework Considerations
框架适配注意事项
Frameworks with server-side capabilities (Astro, Next.js, Nuxt, SvelteKit, TanStack Start) typically generate their own serverless functions via adapters. You usually do not write raw Netlify Functions in these projects — the framework adapter handles server-side rendering and API routes. Write Netlify Functions directly when:
- Using a client-side-only framework (Vite + React SPA, vanilla JS)
- Adding background or scheduled tasks to any project
- Building standalone API endpoints outside the framework's routing
See the netlify-frameworks skill for adapter setup.
具备服务端能力的框架(Astro、Next.js、Nuxt、SvelteKit、TanStack Start)通常会通过适配器自动生成对应的无服务器函数,这类项目中一般不需要手动编写原生Netlify Functions,框架适配器会处理服务端渲染和API路由。以下场景适合直接编写Netlify Functions:
- 使用仅客户端的框架(Vite + React SPA、原生JS)
- 为任意项目添加后台或定时任务
- 构建脱离框架路由的独立API端点
请参考netlify-frameworks skill了解适配器配置方法。