netlify-server

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Netlify Server

Netlify Server

Early Access, so APIs may change. It is available on credit-based plans and on Enterprise plans with credits enabled. It requires Node.js 24+ for both build and local dev, and Netlify CLI 27.17.0+ for both local dev and deploys.
It is free during Early Access and intended for evaluation, experimentation, and low-volume production use. At GA it will bill credits for reserved memory (GB-hours) and active CPU (vCPU-hours). Every request the server handles already counts toward the web requests meter.
当前处于 Early Access,因此 API 可能会发生变化。它可用于按额度计费的套餐,也适用于已启用额度的 Enterprise 套餐。无论构建还是本地开发,均要求使用 Node.js 24+;无论本地开发还是部署,均要求使用 Netlify CLI 27.17.0+。
Early Access 期间免费,主要面向评估、实验和低流量生产使用。GA 后,将按预留内存(GB-hours)和活跃 CPU(vCPU-hours)消耗额度。服务器处理的每个请求都已计入 Web 请求用量统计。

Reach for this / avoid this

推荐用法 / 避免用法

ts
// ✅ netlify/server/index.ts — handler (same signature as Netlify Functions)
import type { Context, Config } from "@netlify/server";
export default async (req: Request, context: Context) =>
  new Response(`Hello from ${context.geo.city ?? "somewhere"}`);
export const config: Config = { path: "/api/*" };
js
// ✅ Fetchable app (Hono etc.): export as is
export default app;
// ✅ Node request listener: wrap it, do NOT call listen(). WebSockets work.
export default createServer(handleRequest);
// ✅ Framework that starts itself (Express/Fastify): listen on PORT within 10 s
app.listen(process.env.PORT);
js
// ❌ export default (req, res) => {...}   // two params = treated as a fetch handler, breaks
// ❌ export default expressApp            // works, but WebSocket upgrades get 501
// ❌ server.close(() => process.exit(0))  // cuts off shutdown hooks and background work
// ❌ setInterval / fire-and-forget promise // invisible to Netlify; the instance can stop mid-work
You don't configure ports, add health endpoints, or install adapters. Install the package with
npm install @netlify/server
.
ts
// ✅ netlify/server/index.ts — handler (same signature as Netlify Functions)
import type { Context, Config } from "@netlify/server";
export default async (req: Request, context: Context) =>
  new Response(`Hello from ${context.geo.city ?? "somewhere"}`);
export const config: Config = { path: "/api/*" };
js
// ✅ Fetchable app (Hono etc.): export as is
export default app;
// ✅ Node request listener: wrap it, do NOT call listen(). WebSockets work.
export default createServer(handleRequest);
// ✅ Framework that starts itself (Express/Fastify): listen on PORT within 10 s
app.listen(process.env.PORT);
js
// ❌ export default (req, res) => {...}   // two params = treated as a fetch handler, breaks
// ❌ export default expressApp            // works, but WebSocket upgrades get 501
// ❌ server.close(() => process.exit(0))  // cuts off shutdown hooks and background work
// ❌ setInterval / fire-and-forget promise // invisible to Netlify; the instance can stop mid-work
你无需配置端口、添加健康检查端点或安装适配器。使用
npm install @netlify/server
安装该包。

Entry file and detection

入口文件与检测

  • Use one server per project:
    netlify/server/index.ts
    ,
    .mts
    ,
    .js
    , or
    .mjs
    . The build fails if more than one exists.
  • Startup runs once per instance:
    1. PORT
      is set.
    2. The entry file is imported, running top-level code (top-level
      await
      is awaited).
    3. onStart
      hooks run in order.
    4. The default export is inspected.
  • No traffic arrives until all steps finish. Any throw fails the start.
Netlify uses the first matching row for the default export:
Default exportRun asWebSockets
http.Server
without
listen()
Requests sent to it
upgrade
event (
ws
, Socket.IO)
Object with
fetch
(Fetchable, e.g. Hono)
fetch(request, context)
upgradeWebSocket
Express/Connect app, or a function with ≥3 paramsWrapped in its own HTTP server501
Any other function
(request, context) => Response
upgradeWebSocket
Anything else / nothingWaits for your code to listen
upgrade
event
⚠️ Self-started servers must listen within 10 s after start hooks finish.
  • If your code starts several servers, the one on
    process.env.PORT
    wins. If none listens on it, the start fails.
  • Reserved ports are
    53
    and
    15000–15099
    .
  • Only Node.js HTTP servers are supported, not raw TCP.
Create shared resources such as a DB pool at top level so they are reused across requests.
⚠️ Outbound connections are closed after 60 s without data in either direction. TCP keepalives don't count.
  • Set your pool's idle timeout below 60 s (e.g.
    idleTimeoutMillis: 30_000
    ), or it hands out dead connections.
  • Quiet connections such as Postgres
    LISTEN
    need traffic at least every 60 s (e.g.
    SELECT 1
    ), or must reconnect on close. The symptom is
    Connection terminated unexpectedly
    .
  • 每个项目仅使用一个服务器:
    netlify/server/index.ts
    、
    .mts
    、
    .js
    或
    .mjs
    。如果存在多个入口文件,构建将失败。
  • 启动流程在每个实例上运行一次:
    1. PORT
      会被设置。
    2. 导入入口文件并运行顶层代码(顶层
      await
      会被等待)。
    3. onStart
      钩子按顺序运行。
    4. 检查默认导出。
  • 所有步骤完成前不会产生流量。任何异常都会导致启动失败。
Netlify 会根据默认导出使用表格中首个匹配项:
默认导出运行方式WebSockets
未调用
listen()
的
http.Server
向该服务器发送请求
upgrade
事件(
ws
、Socket.IO)
包含
fetch
的对象(Fetchable,例如 Hono)
fetch(request, context)
upgradeWebSocket
Express/Connect 应用,或包含 ≥3 个参数的函数包装在独立的 HTTP 服务器中501
其他任何函数
(request, context) => Response
upgradeWebSocket
其他内容或没有导出等待代码开始监听
upgrade
事件
⚠️ 自行启动的服务器必须在启动钩子完成后 10 秒内开始监听。
  • 如果代码启动了多个服务器,则监听
    process.env.PORT
    的服务器胜出。如果没有服务器监听该端口,启动将失败。
  • 保留端口为
    53
    和
    15000–15099
    。
  • 仅支持 Node.js HTTP 服务器,不支持原始 TCP。
在顶层创建共享资源(例如 DB pool),以便在各请求之间复用。
⚠️ 出站连接在任一方向连续 60 秒没有数据后会被关闭。TCP keepalive 不计入其中。
  • 将连接池的空闲超时时间设置为低于 60 秒(例如
    idleTimeoutMillis: 30_000
    ),否则连接池会返回失效连接。
  • Postgres
    LISTEN
    等静默连接需要至少每 60 秒产生一次流量(例如执行
    SELECT 1
    ),或者必须在连接关闭后重新连接。典型症状是
    Connection terminated unexpectedly
    。

Examples

示例

js
// netlify/server/index.mjs — Express, self-started
import express from "express";
import { getContext } from "@netlify/server";
const app = express();
app.get("/api/hello", (req, res) => {
  const { geo } = getContext();
  res.json({ message: `Hello from ${geo.city ?? "somewhere"}` });
});
app.listen(process.env.PORT || 3000);
js
// Fastify
const app = Fastify();
app.get("/api/hello", async () => ({ message: `Hello from ${getContext().geo.city ?? "somewhere"}` }));
await app.listen({ port: Number(process.env.PORT) || 3000 });
js
// netlify/server/index.mjs — Express, self-started
import express from "express";
import { getContext } from "@netlify/server";
const app = express();
app.get("/api/hello", (req, res) => {
  const { geo } = getContext();
  res.json({ message: `Hello from ${geo.city ?? "somewhere"}` });
});
app.listen(process.env.PORT || 3000);
js
// Fastify
const app = Fastify();
app.get("/api/hello", async () => ({ message: `Hello from ${getContext().geo.city ?? "somewhere"}` }));
await app.listen({ port: Number(process.env.PORT) || 3000 });

Background work after responding

响应后的后台工作

ts
export default async (req: Request, context: Context) => {
  const order = await saveOrder(await req.json());
  context.waitUntil(sendConfirmationEmail(order)); // keeps the instance alive until settled
  return Response.json(order, { status: 201 });
};
// In frameworks: const { waitUntil } = getContext();
How
waitUntil
behaves:
  • It is not bound by the request duration limit.
  • Rejections are logged.
  • On replacement, background work gets up to 90 s. Persist critical work to Netlify Database or Netlify Blobs.
ts
export default async (req: Request, context: Context) => {
  const order = await saveOrder(await req.json());
  context.waitUntil(sendConfirmationEmail(order)); // keeps the instance alive until settled
  return Response.json(order, { status: 201 });
};
// In frameworks: const { waitUntil } = getContext();
waitUntil
的行为如下:
  • 不受请求时长限制。
  • Promise rejections 会被记录到日志。
  • 实例被替换时,后台工作最多可获得 90 秒。关键工作应持久化到 Netlify Database 或 Netlify Blobs。

WebSockets (handler/Fetchable)

WebSockets(处理器/Fetchable)

ts
import { upgradeWebSocket } from "@netlify/server";
export default async (req: Request) => {
  if (req.headers.get("upgrade") === "websocket") {
    const { socket, response } = upgradeWebSocket(req, { idleTimeout: 30 }); // pings off unless set
    socket.onmessage = (e) => socket.send(`Echo: ${e.data}`);
    return response; // return as is
  }
  return new Response("Connect with a WebSocket client");
};
ts
import { upgradeWebSocket } from "@netlify/server";
export default async (req: Request) => {
  if (req.headers.get("upgrade") === "websocket") {
    const { socket, response } = upgradeWebSocket(req, { idleTimeout: 30 }); // pings off unless set
    socket.onmessage = (e) => socket.send(`Echo: ${e.data}`);
    return response; // return as is
  }
  return new Response("Connect with a WebSocket client");
};

WebSockets (
ws
on a self-started server)

WebSockets(自行启动的服务器使用
ws
)

js
const server = app.listen(process.env.PORT);
const wss = new WebSocketServer({ server });
wss.on("connection", (ws) => ws.on("message", (d) => ws.send(d)));
// On shutdown, close wss.clients yourself. getWebSockets() doesn't include them.
js
const server = app.listen(process.env.PORT);
const wss = new WebSocketServer({ server });
wss.on("connection", (ws) => ws.on("message", (d) => ws.send(d)));
// On shutdown, close wss.clients yourself. getWebSockets() doesn't include them.
关闭时,你需要自行关闭
wss.clients
。
getWebSockets()
不会包含这些客户端。

Server-Sent Events / streaming

Server-Sent Events / 流式传输

ts
export default async () => {
  const enc = new TextEncoder(); let t: ReturnType<typeof setInterval>;
  const stream = new ReadableStream({
    start(c) { t = setInterval(() => c.enqueue(enc.encode(`data: ${new Date().toISOString()}\n\n`)), 1000); },
    cancel() { clearInterval(t); },
  });
  return new Response(stream, { headers: { "content-type": "text/event-stream" } });
};
ts
export default async () => {
  const enc = new TextEncoder(); let t: ReturnType<typeof setInterval>;
  const stream = new ReadableStream({
    start(c) { t = setInterval(() => c.enqueue(enc.encode(`data: ${new Date().toISOString()}\n\n`)), 1000); },
    cancel() { clearInterval(t); },
  });
  return new Response(stream, { headers: { "content-type": "text/event-stream" } });
};

Client reconnect

客户端重连

Browser
WebSocket
doesn't reconnect on its own;
EventSource
does.
js
function connect() {
  const s = new WebSocket("wss://example.com/api/chat");
  s.addEventListener("close", (e) => setTimeout(connect, e.code === 1012 ? 0 : 1000));
  return s;
}
浏览器原生
WebSocket
不会自动重连;
EventSource
会自动重连。
js
function connect() {
  const s = new WebSocket("wss://example.com/api/chat");
  s.addEventListener("close", (e) => setTimeout(connect, e.code === 1012 ? 0 : 1000));
  return s;
}

Lifecycle hooks

生命周期钩子

ts
import { onStart, onShutdown, onHealthCheck, getWebSockets } from "@netlify/server";

onStart(async () => { await db.connect(); }); // in order; rejection = start fails

onShutdown(async ({ drained }) => {           // all hooks run in parallel
  queue.stop();
  for (const s of getWebSockets()) s.close(1012, "Server restarting");
  await drained;                              // never rejects
  await pool.end();                           // close resources only after drained
});

onHealthCheck(() => ({                        // load signal, not health
  utilization: { db_pool: (pool.totalCount - pool.idleCount) / pool.options.max }, // 0–1
  namedMetrics: { db_pool_waiting: pool.waitingCount },  // observability only
}), { interval: 1000 });                      // default and minimum 1000 ms
Hook rules:
  • onStart
    must be called while the entry file loads. Calling it later throws.
  • getContext()
    throws outside a request, including at top level and inside hooks.
  • In health reports,
    event_loop
    and
    memory
    are reserved keys.
    applicationUtilization
    (0–1) overrides the max entry.
  • A health hook that throws never stops the instance. Health hooks don't run locally.
ts
import { onStart, onShutdown, onHealthCheck, getWebSockets } from "@netlify/server";

onStart(async () => { await db.connect(); }); // in order; rejection = start fails

onShutdown(async ({ drained }) => {           // all hooks run in parallel
  queue.stop();
  for (const s of getWebSockets()) s.close(1012, "Server restarting");
  await drained;                              // never rejects
  await pool.end();                           // close resources only after drained
});

onHealthCheck(() => ({                        // load signal, not health
  utilization: { db_pool: (pool.totalCount - pool.idleCount) / pool.options.max }, // 0–1
  namedMetrics: { db_pool_waiting: pool.waitingCount },  // observability only
}), { interval: 1000 });                      // default and minimum 1000 ms
钩子规则:
  • onStart
    必须在入口文件加载期间调用。延后调用会抛出异常。
  • getContext()
    在请求之外调用会抛出异常,包括在顶层和钩子内部调用。
  • 在健康报告中,
    event_loop
    和
    memory
    是保留键。
    applicationUtilization
    (0–1)会覆盖最大条目。
  • 抛出异常的健康检查钩子不会停止实例。健康检查钩子不会在本地运行。

Edge caching

边缘缓存

Responses are never cached unless you set headers.
ts
return Response.json(data, { headers: { "Netlify-CDN-Cache-Control": "public, max-age=3600, durable" } });
// Express: res.set(...)  Hono: c.header(...)  Fastify: reply.header(...)
Supported features:
  • stale-while-revalidate
  • Cache keys varied by query, header, language, country, or cookie
  • Invalidation by site or cache tag
Each deploy invalidates the previous cache.
除非设置响应头,否则响应永远不会被缓存。
ts
return Response.json(data, { headers: { "Netlify-CDN-Cache-Control": "public, max-age=3600, durable" } });
// Express: res.set(...)  Hono: c.header(...)  Fastify: reply.header(...)
支持的功能:
  • stale-while-revalidate
  • 可按 query、header、语言、国家或 cookie 区分缓存键
  • 按站点或 cache tag 失效缓存
每次部署都会使previous缓存失效。

Context (
context
arg or
getContext()
)

Context(
context
参数或
getContext()
)

  • geo
    :
    city
    ,
    country{code,name}
    ,
    subdivision{code,name}
    ,
    latitude
    ,
    longitude
    ,
    postalCode
    ,
    timezone
    .
  • ip
    (same as
    req.socket.remoteAddress
    /
    req.ip
    ),
    url
    (
    URL
    ),
    requestId
    .
  • cookies.get(name)
    /
    .set(options)
    /
    .delete(name|options)
    follow CookieStore semantics.
  • deploy
    :
    id
    ,
    branch
    ,
    context
    ,
    published
    ,
    skewProtectionToken
    .
  • site
    :
    id
    ,
    name
    ,
    url
    .
    account.id
    .
    server.region
    .
  • user
    :
    { id, email, expiresAt }
    on private projects or with team login protection, otherwise
    undefined
    .
  • waitUntil(promise)
    .
Types:
Config
,
Context
,
HealthReport
,
HealthCheckHook
,
HealthCheckOptions
,
LifecycleHook
,
ShutdownHook
,
ShutdownContext
,
ServerRegion
,
ServerSize
,
UpgradeWebSocketOptions
,
WebSocketUpgrade
.
  • geo
    :
    city
    、
    country{code,name}
    、
    subdivision{code,name}
    、
    latitude
    、
    longitude
    、
    postalCode
    、
    timezone
    。
  • ip
    (与
    req.socket.remoteAddress
    /
    req.ip
    相同)、
    url
    (
    URL
    )、
    requestId
    。
  • cookies.get(name)
    /
    .set(options)
    /
    .delete(name|options)
    遵循 CookieStore 语义。
  • deploy
    :
    id
    、
    branch
    、
    context
    、
    published
    、
    skewProtectionToken
    。
  • site
    :
    id
    、
    name
    、
    url
    。
    account.id
    。
    server.region
    。
  • user
    :私有项目或启用团队登录保护时为
    { id, email, expiresAt }
    ,否则为
    undefined
    。
  • waitUntil(promise)
    。
类型:
Config
、
Context
、
HealthReport
、
HealthCheckHook
、
HealthCheckOptions
、
LifecycleHook
、
ShutdownHook
、
ShutdownContext
、
ServerRegion
、
ServerSize
、
UpgradeWebSocketOptions
、
WebSocketUpgrade
。

Configuration

配置

Set config with
export const config: Config
in the entry file (or
config
on a default-exported Fetchable), or in
netlify.toml
. The entry file wins per setting. Unknown keys or invalid values fail the build.
toml
[server]
  region = "fra"
  size = "medium"
[server.scale]
  max = 2
KeyValues / default
path
One or more paths starting with
/
. Same syntax as function paths. Default
/*
excludedPath
Paths handed back to the rest of the project, e.g.
["/legacy/*", "/status"]
region
cmh
(US East Ohio, default) or
fra
(Frankfurt). Also settable in the UI under Server → Region, but a
netlify.toml
region overrides it. Changes apply on the next deploy
size
small
(1 GB, shared vCPU, 512 MB disk, 32 concurrent requests, default);
medium
(2 GB/1 vCPU/1 GB/64);
large
(4 GB/2 vCPU/2 GB/128). Free/Personal plans can use
small
only
scale
{ min, max }
.
min
must be 0
in Early Access.
max
≤ 3, or 1 on Free/Personal. Higher values fail the deploy
includedFiles
Globs for files read at runtime. Entry-file globs are relative to the entry file and replace the toml list. Read them via
import.meta.dirname
, never
process.cwd()
Other settings:
  • Environment variables: use
    process.env
    with variables scoped to Functions. Values are fixed at deploy time, so redeploy after changes.
  • Filesystem: read-only except
    /tmp
    , which is per-instance and wiped on stop.
通过入口文件中的
export const config: Config
(或默认导出的 Fetchable 上的
config
)设置配置,也可以在
netlify.toml
中设置。按单项设置计算,入口文件优先。 未知键或无效值都会导致构建失败。
toml
[server]
  region = "fra"
  size = "medium"
[server.scale]
  max = 2
键值 / 默认值
path
一个或多个以
/
开头的路径。语法与 function paths 相同。默认值为
/*
excludedPath
交还项目其余部分处理的路径,例如
["/legacy/*", "/status"]
region
cmh
(美国东部俄亥俄州,默认值)或
fra
(法兰克福)。也可以在 UI 的 Server → Region 中设置,但
netlify.toml
中的 region 会覆盖 UI 设置。更改将在下次部署时生效
size
small
(1 GB、共享 vCPU、512 MB 磁盘、32 个并发请求,默认值);
medium
(2 GB/1 vCPU/1 GB/64);
large
(4 GB/2 vCPU/2 GB/128)。Free/Personal 套餐只能使用
small
scale
{ min, max }
。Early Access 中
min
必须为 0
。
max
≤ 3,Free/Personal 套餐则 ≤ 1。更高的值将导致部署失败
includedFiles
运行时读取文件的 Glob。入口文件的 Glob 相对于入口文件目录,并会替换 toml 中的列表。通过
import.meta.dirname
读取这些文件,绝不要使用
process.cwd()
其他设置:
  • 环境变量: 使用
    process.env
    读取限定为 Functions 作用域的变量。值在部署时固定,因此更改后需要重新部署。
  • 文件系统: 除
    /tmp
    外均为只读。
    /tmp
    属于实例级空间,实例停止时会被清除。

Routing

路由

Requests are handled in this order:
  1. Edge functions
  2. Redirects/rewrites
  3. Static files
  4. Functions
  5. The server, which owns its own 404s
⚠️ Server gets no requests? Check these causes:
  • An SPA catch-all
    /* /index.html 200
    swallows everything. Scope it to frontend paths.
  • A static file or function already occupies the same path. Static files always win.
  • path
    /
    excludedPath
    excludes the path.
  • /.netlify/server/
    is reserved.
  • Full-stack frameworks (Next.js, Astro, Nuxt, SvelteKit, React Router, TanStack Start) don't run on Netlify Server. Their adapters claim every path, so don't add a server to those projects.
Choosing between options:
  • Use a server for a new backend.
  • Use scheduled functions for cron jobs and webhooks.
  • Use edge functions for logic close to visitors.
  • Functions are cheaper for rarely used backends, because instances idle for 5 min before stopping.
请求按以下顺序处理:
  1. Edge functions
  2. 重定向/重写
  3. 静态文件
  4. Functions
  5. 服务器,由服务器自行处理 404
⚠️ 服务器没有收到请求? 检查以下原因:
  • SPA 的
    /* /index.html 200
    全捕获规则会吞掉所有请求。应将其范围限制到前端路径。
  • 静态文件或 Function 已占用同一路径。静态文件始终优先。
  • path
    /
    excludedPath
    排除了该路径。
  • /.netlify/server/
    是保留路径。
  • 全栈框架(Next.js、Astro、Nuxt、SvelteKit、React Router、TanStack Start)无法在 Netlify Server 上运行。它们的适配器会占用所有路径,因此不要向这类项目添加服务器。
如何选择:
  • 新后端使用服务器。
  • 使用定时函数处理 cron 作业和 webhook。
  • 使用 edge functions 处理靠近访问者的逻辑。
  • 对于很少使用的后端,Functions 成本更低,因为实例闲置 5 分钟后才会停止。

Instances and lifecycle

实例与生命周期

Assume multiple instances. They overlap during deploys and are replaced every 8 h, and memory and
/tmp
are per-instance. Practical consequences:
  • In-memory state is a cache. Put shared data in Netlify Database or Netlify Blobs.
  • Each instance holds its own WebSocket connections.
  • Once-only work can run twice or never. Use a scheduled function and record completion.
Scaling and limits:
  • Concurrency: depends on size: 32 (
    small
    ), 64 (
    medium
    ), or 128 (
    large
    ) requests per instance. Each open SSE/stream holds one of those slots. WebSockets don't use these slots. They have a separate limit of a couple of hundred per instance, and an instance full of WebSockets still serves ordinary requests.
  • Routing: new requests go to the least-loaded instance, judged by event loop, memory, and health hooks.
  • Scale to zero: an instance stops after 5 min idle. Open requests, WS/SSE connections, and
    waitUntil
    work pause the timer;
    setInterval
    does not.
  • Cold starts: the first request waits for the entry file and start hooks. That time counts toward the 20 s response timeout. Lazy-init route-specific services and keep dependencies small.
Shutdown sequence:
  1. New traffic stops.
  2. SIGTERM
    is sent.
  3. Your server stops accepting connections.
  4. Shutdown hooks start.
  5. In-flight work and connections get up to 90 s.
  6. Hooks get up to 115 s from their start (at least 25 s after work ends).
  7. Remaining connections are force-closed.
Close sockets with code
1012
in
onShutdown
so clients move immediately.
Deploys:
  • A production deploy publishes only after its new server has started. If the server fails to start, the deploy isn't published and the old one keeps serving.
  • Rollback rolls back the server too.
  • Deploy Previews and branch deploys start their server on first request. That request is a cold start, so slow startup can turn it into a 502.
假定会有多个实例。 部署期间这些实例会重叠运行,并每 8 小时被替换一次。内存和
/tmp
均为实例级。实际影响如下:
  • 内存状态只应作为缓存使用。共享数据应放入 Netlify Database 或 Netlify Blobs。
  • 每个实例维护自己的 WebSocket 连接。
  • 仅执行一次的工作可能执行两次,也可能一次都不执行。请使用 scheduled function 并记录完成状态。
扩缩容与限制:
  • **并发:**取决于实例大小:每个实例可同时处理 32(
    small
    )、64(
    medium
    )或 128(
    large
    )个请求。每个打开的 SSE/stream 会占用一个并发槽。WebSocket 不占用这些槽位,而有独立的每实例数百个连接限制;即使实例的 WebSocket 已满,仍可服务普通请求。
  • **路由:**新请求会发送到负载最低的实例,负载根据事件循环、内存和健康检查钩子判断。
  • **缩容到零:**实例闲置 5 分钟后会停止。打开的请求、WS/SSE 连接和
    waitUntil
    工作会暂停计时器;
    setInterval
    不会。
  • **冷启动:**第一个请求需要等待入口文件和启动钩子执行完毕。该时间计入 20 秒响应超时。 应延迟初始化特定路由的服务,并保持依赖项精简。
关闭顺序:
  1. 停止接收新流量。
  2. 发送
    SIGTERM
    。
  3. 服务器停止接受连接。
  4. 关闭钩子开始运行。
  5. 进行中的工作和连接最多可获得 90 秒。
  6. 钩子从启动时起最多可获得 115 秒(工作结束后至少仍有 25 秒)。
  7. 剩余连接会被强制关闭。
在
onShutdown
中使用代码
1012
关闭 socket,让客户端立即迁移。
部署:
  • 生产部署只有在新的服务器成功启动后才会发布。如果服务器启动失败,部署不会发布,旧版本会继续提供服务。
  • 回滚也会回滚服务器。
  • Deploy Preview 和分支部署会在首次请求时启动服务器。该请求会经历冷启动,因此启动过慢可能引发 502。

Limits

限制

LimitValue
Response timeout20 s to send status + headers, else 502. Cold-start time is included. Stream the body, or respond and finish with
waitUntil
Request duration (incl. WS/SSE)30 min; 2 h on Pro, Business, and Enterprise
Outbound connectionsClosed after 60 s idle; keepalives don't count
Instance lifetime8 h
Instances3 (credit-based Pro/Enterprise); 1 (Free/Personal)
限制值
响应超时必须在 20 秒内发送状态码和响应头,否则返回 502。冷启动时间也包含在内。 请流式传输响应正文,或先响应,再使用
waitUntil
完成工作
请求时长(包括 WS/SSE)30 分钟;Pro、Business 和 Enterprise 为 2 小时
出站连接闲置 60 秒后关闭;keepalive 不计入其中
实例生命周期8 小时
实例数量3 个(按额度计费的 Pro/Enterprise);1 个(Free/Personal)

Errors

错误

StatusMeaning / fix
429All concurrency slots (32/64/128 by size) are full at max instances. Long SSE streams are often the cause
500The instance failed to start (top-level/start hook threw, or no listen on PORT within 10 s), or the handler threw
501WebSocket upgrade on a directly exported Express/Connect app. Use
listen()
or
createServer
502No headers within 20 s (including cold start), or the instance crashed/OOM'd
状态码含义 / 修复方法
429达到最大实例数量时,所有并发槽位(按大小为 32/64/128)均已占满。长时间运行的 SSE 流通常是原因
500实例启动失败(顶层代码或启动钩子抛出异常,或未在 10 秒内监听 PORT),或者处理器抛出异常
501直接导出的 Express/Connect 应用尝试进行 WebSocket upgrade。请使用
listen()
或
createServer
50220 秒内未发送响应头(包含冷启动时间),或者实例崩溃/OOM

Local dev and logs

本地开发与日志

Local dev:
  • Run
    netlify dev
    (CLI 27.17.0+). The Netlify Vite plugin doesn't run the server.
  • The CLI restarts the server on changes inside
    netlify/server/
    only. Restart the CLI for changes elsewhere.
  • Local differences from production:
    • Single instance.
    • path
      /
      excludedPath
      ignored.
    • No limits enforced.
    • 5 s shutdown.
    • No
      SIGTERM
      on Windows.
    • No health hooks.
  • For E2E tests, use
    @netlify/dev
    :
    new NetlifyDev({ projectRoot, server: { enabled: true } })
    , then
    start()
    /
    stop()
    .
Monitoring and logs:
  • Use the Server page under Cloud compute. It opens in Live mode (last hour) and shows production by default, and you can switch branches to see branch deploys or Deploy Previews.
    • Overview: requests/errors, p95 latency, memory, CPU, and saturation.
    • Instances table: state, start reason, and failed-start warnings.
    • Requests view: cold start, queue wait, and Open in Observability.
    • Logs view.
  • Per-request views are also in observability.
  • Use
    console.*
    inside a request to attach the
    requestId
    . Direct
    process.stdout
    writes aren't linked to requests.
CLI and log drains:
bash
netlify logs                                # server + functions + edge functions, last 10 min
netlify logs --source server --since 30m    # server only; --until ends the window
netlify logs --source server --follow       # stream lines as written
  • --level
    and
    --json
    work.
    --deploy-id
    and
    --url
    don't work with server logs
    , because they can't be filtered by deploy.
  • Long windows show only the most recent lines. Narrow
    --since
    /
    --until
    to see older ones.
  • For log drains, select Server logs as a log type.
<!-- Gaps: instance cap, medium/large size availability, and scale.max default for Business plans are not documented. --> <!-- Exact per-instance WebSocket limit, netlify.toml spelling of excludedPath/includedFiles, and GA credit rates are unstated. --> <!-- system: agent-context/server/system.md — human-owned, merged by ctx-gen; edit system.md, not this section -->
本地开发:
  • 运行
    netlify dev
    (CLI 27.17.0+)。Netlify Vite 插件不会运行服务器。
  • CLI 仅在
    netlify/server/
    内的代码发生变化时重启服务器。其他位置的代码发生变化时,需要重启 CLI。
  • 本地环境与生产环境的差异:
    • 单实例。
    • 忽略
      path
      /
      excludedPath
      。
    • 不强制执行限制。
    • 关闭时间为 5 秒。
    • Windows 上不发送
      SIGTERM
      。
    • 无健康检查钩子。
  • 如需 E2E 测试,请使用
    @netlify/dev
    :
    new NetlifyDev({ projectRoot, server: { enabled: true } })
    ,然后调用
    start()
    /
    stop()
    。
监控与日志:
  • 使用 Cloud compute 下的 Server 页面。它以 Live 模式(最近一小时)打开,默认显示生产环境;可以切换分支以查看分支部署或 Deploy Preview。
    • **概览:**请求数/错误、p95 延迟、内存、CPU 和饱和度。
    • **实例表格:**状态、启动原因和启动失败警告。
    • **请求视图:**冷启动、排队等待时间以及 Open in Observability。
    • 日志视图。
  • Observability 中也提供按请求查看的视图。
  • 在请求处理中使用
    console.*
    可关联
    requestId
    。直接写入
    process.stdout
    的内容不会与请求关联。
CLI 与日志导出:
bash
netlify logs                                # server + functions + edge functions, last 10 min
netlify logs --source server --since 30m    # server only; --until ends the window
netlify logs --source server --follow       # stream lines as written
  • --level
    和
    --json
    可用。
    --deploy-id
    和
    --url
    对服务器日志不可用
    ,因为无法按部署进行筛选。
  • 较长的时间窗口仅显示最近的若干行。缩小
    --since
    /
    --until
    范围可以查看更早的日志。
  • 配置日志导出时,请选择 Server logs 作为日志类型。
<!-- 尚未记录的细节:实例上限、medium/large 实例大小的可用性,以及 Business 套餐的 scale.max 默认值。 --> <!-- 尚未明确:每个实例的精确 WebSocket 限制、netlify.toml 中 excludedPath/includedFiles 的准确拼写,以及 GA 额度费率。 --> <!-- system: agent-context/server/system.md — human-owned, merged by ctx-gen; edit system.md, not this section -->

Netlify house rules (server)

Netlify 内部规则(server)

These are org conventions, not docs facts — they are merged into the rendered skill by ctx-gen and are never generated. Owned by the Netlify Server team.
  1. Never keep a server alive on purpose: no self-pings, no
    setInterval
    or scheduled function that calls the server, no
    waitUntil
    chain that schedules more work to stay running. Scale to zero is the design. If the user asks for an always-on server, explain this and build without it.
  2. Run scheduled work with a scheduled function that calls a server route, never with timers inside the server.
  3. An endpoint that fetches a URL the user supplies must resolve the hostname and refuse loopback, private, link-local and unique-local addresses (including 169.254.169.254), re-check after every redirect, and return only what the feature needs. Never build a generic
    /proxy?url=
    endpoint or forward the caller's method, headers or body — that is an open relay.
  4. Process memory is lost on every scale-to-zero, deploy and platform maintenance event. In-memory caches are fine; anything that must survive belongs in Netlify Blobs or Netlify Database.
  5. Don't detach child processes; they are killed on scale-to-zero. Keep work in-process with
    waitUntil
    , or use a background function.
以下内容是组织约定,而非文档事实——它们由 ctx-gen 合并到最终呈现的 skill 中,绝不会自动生成。由 Netlify Server 团队负责维护。
  1. 绝不要故意让服务器持续运行:不要使用自 ping,不要使用
    setInterval
    ,不要使用调用服务器的 scheduled function,也不要创建会继续调度更多工作的
    waitUntil
    链。缩容到零是设计目标。如果用户要求始终在线的服务器,请解释这一点,并在不依赖常驻服务器的情况下进行构建。
  2. 定时工作应使用 scheduled function 调用服务器路由,绝不要在服务器内部使用定时器。
  3. 如果端点获取用户提供的 URL,必须解析主机名,并拒绝回环地址、私有地址、链路本地地址和唯一本地地址(包括 169.254.169.254),每次重定向后都要重新检查,并且只返回该功能所需的内容。绝不要构建通用的
    /proxy?url=
    端点,也不要转发调用方的 method、headers 或 body——这会形成开放中继。
  4. 进程内存会在每次缩容到零、部署和平台维护事件后丢失。内存缓存没有问题;必须持久保存的数据应放入 Netlify Blobs 或 Netlify Database。
  5. 不要分离(detach)子进程;缩容到零时子进程会被终止。将工作保留在进程内并使用
    waitUntil
    ,或者使用 background function。