← NetlifyCONTENT HISTORY
WHAT CHANGED
Update to Netlify
Snapshot Nov 19, 2026 · 00:11 UTC · version 1.9.0
Collection source: downloaded plugin package.
First saved snapshot
No earlier snapshot is available to establish a change.
Save Netlify and check future changes in Following.
Up to 3 plugins free · no card required.
Compare saved observations
Download comparison JSONFull technical diff · 0 changed fields
Full snapshot data
{
"description": "Build and deploy a long-lived Node.js backend on Netlify Server (Early Access) from netlify/server/index.ts. Use this skill whenever someone wants to run an Express, Fastify, Hono or Koa app on Netlify as it is, add a backend or REST/GraphQL API that keeps database pools and caches warm, build real-time features such as chat, live dashboards or multiplayer with WebSockets or Server-Sent Events, or stream AI responses and run agent loops. It also covers background work after responding with waitUntil, startup and graceful shutdown hooks, load-aware health checks, edge caching of server responses, region/size/scale settings, local testing with netlify dev, reading server logs with netlify logs or log drains, and debugging a server that gets no requests, fails to start, drops database connections after a minute, or returns 429/500/501/502.",
"included_files": [],
"name": "netlify-server",
"skill_md_contents": "---\nname: netlify-server\ndescription: Build and deploy a long-lived Node.js backend on Netlify Server (Early Access) from netlify/server/index.ts. Use this skill whenever someone wants to run an Express, Fastify, Hono or Koa app on Netlify as it is, add a backend or REST/GraphQL API that keeps database pools and caches warm, build real-time features such as chat, live dashboards or multiplayer with WebSockets or Server-Sent Events, or stream AI responses and run agent loops. It also covers background work after responding with waitUntil, startup and graceful shutdown hooks, load-aware health checks, edge caching of server responses, region/size/scale settings, local testing with netlify dev, reading server logs with netlify logs or log drains, and debugging a server that gets no requests, fails to start, drops database connections after a minute, or returns 429/500/501/502.\n---\n\n# Netlify Server\n\nEarly 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.\n\nIt 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.**\n\n## Reach for this / avoid this\n\n```ts\n// ✅ netlify/server/index.ts — handler (same signature as Netlify Functions)\nimport type { Context, Config } from \"@netlify/server\";\nexport default async (req: Request, context: Context) =>\n new Response(`Hello from ${context.geo.city ?? \"somewhere\"}`);\nexport const config: Config = { path: \"/api/*\" };\n```\n\n```js\n// ✅ Fetchable app (Hono etc.): export as is\nexport default app;\n// ✅ Node request listener: wrap it, do NOT call listen(). WebSockets work.\nexport default createServer(handleRequest);\n// ✅ Framework that starts itself (Express/Fastify): listen on PORT within 10 s\napp.listen(process.env.PORT);\n```\n\n```js\n// ❌ export default (req, res) => {...} // two params = treated as a fetch handler, breaks\n// ❌ export default expressApp // works, but WebSocket upgrades get 501\n// ❌ server.close(() => process.exit(0)) // cuts off shutdown hooks and background work\n// ❌ setInterval / fire-and-forget promise // invisible to Netlify; the instance can stop mid-work\n```\n\nYou don't configure ports, add health endpoints, or install adapters. Install the package with `npm install @netlify/server`.\n\n## Entry file and detection\n\n- Use **one** server per project: `netlify/server/index.ts`, `.mts`, `.js`, or `.mjs`. **The build fails if more than one exists.**\n- Startup runs once per instance:\n 1. `PORT` is set.\n 2. The entry file is imported, running top-level code (top-level `await` is awaited).\n 3. `onStart` hooks run in order.\n 4. The default export is inspected.\n- No traffic arrives until all steps finish. Any throw fails the start.\n\nNetlify uses the **first matching row** for the default export:\n\n| Default export | Run as | WebSockets |\n|---|---|---|\n| `http.Server` without `listen()` | Requests sent to it | `upgrade` event (`ws`, Socket.IO) |\n| Object with `fetch` (Fetchable, e.g. Hono) | `fetch(request, context)` | `upgradeWebSocket` |\n| Express/Connect app, or a function with ≥3 params | Wrapped in its own HTTP server | **501** |\n| Any other function | `(request, context) => Response` | `upgradeWebSocket` |\n| Anything else / nothing | Waits for your code to listen | `upgrade` event |\n\n> ⚠️ **Self-started servers must listen within 10 s after start hooks finish.**\n> - If your code starts several servers, the one on `process.env.PORT` wins. If none listens on it, the start fails.\n> - Reserved ports are `53` and `15000–15099`.\n> - Only Node.js HTTP servers are supported, not raw TCP.\n\nCreate shared resources such as a DB pool at top level so they are reused across requests.\n\n> ⚠️ **Outbound connections are closed after 60 s without data in either direction.** TCP keepalives don't count.\n> - Set your pool's idle timeout **below 60 s** (e.g. `idleTimeoutMillis: 30_000`), or it hands out dead connections.\n> - 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`.\n\n## Examples\n\n```js\n// netlify/server/index.mjs — Express, self-started\nimport express from \"express\";\nimport { getContext } from \"@netlify/server\";\nconst app = express();\napp.get(\"/api/hello\", (req, res) => {\n const { geo } = getContext();\n res.json({ message: `Hello from ${geo.city ?? \"somewhere\"}` });\n});\napp.listen(process.env.PORT || 3000);\n```\n\n```js\n// Fastify\nconst app = Fastify();\napp.get(\"/api/hello\", async () => ({ message: `Hello from ${getContext().geo.city ?? \"somewhere\"}` }));\nawait app.listen({ port: Number(process.env.PORT) || 3000 });\n```\n\n### Background work after responding\n\n```ts\nexport default async (req: Request, context: Context) => {\n const order = await saveOrder(await req.json());\n context.waitUntil(sendConfirmationEmail(order)); // keeps the instance alive until settled\n return Response.json(order, { status: 201 });\n};\n// In frameworks: const { waitUntil } = getContext();\n```\n\nHow `waitUntil` behaves:\n- It is not bound by the request duration limit.\n- Rejections are logged.\n- On replacement, background work gets up to 90 s. Persist critical work to Netlify Database or Netlify Blobs.\n\n### WebSockets (handler/Fetchable)\n\n```ts\nimport { upgradeWebSocket } from \"@netlify/server\";\nexport default async (req: Request) => {\n if (req.headers.get(\"upgrade\") === \"websocket\") {\n const { socket, response } = upgradeWebSocket(req, { idleTimeout: 30 }); // pings off unless set\n socket.onmessage = (e) => socket.send(`Echo: ${e.data}`);\n return response; // return as is\n }\n return new Response(\"Connect with a WebSocket client\");\n};\n```\n\n### WebSockets (`ws` on a self-started server)\n\n```js\nconst server = app.listen(process.env.PORT);\nconst wss = new WebSocketServer({ server });\nwss.on(\"connection\", (ws) => ws.on(\"message\", (d) => ws.send(d)));\n// On shutdown, close wss.clients yourself. getWebSockets() doesn't include them.\n```\n\n### Server-Sent Events / streaming\n\n```ts\nexport default async () => {\n const enc = new TextEncoder(); let t: ReturnType<typeof setInterval>;\n const stream = new ReadableStream({\n start(c) { t = setInterval(() => c.enqueue(enc.encode(`data: ${new Date().toISOString()}\\n\\n`)), 1000); },\n cancel() { clearInterval(t); },\n });\n return new Response(stream, { headers: { \"content-type\": \"text/event-stream\" } });\n};\n```\n\n### Client reconnect\n\nBrowser `WebSocket` doesn't reconnect on its own; `EventSource` does.\n\n```js\nfunction connect() {\n const s = new WebSocket(\"wss://example.com/api/chat\");\n s.addEventListener(\"close\", (e) => setTimeout(connect, e.code === 1012 ? 0 : 1000));\n return s;\n}\n```\n\n### Lifecycle hooks\n\n```ts\nimport { onStart, onShutdown, onHealthCheck, getWebSockets } from \"@netlify/server\";\n\nonStart(async () => { await db.connect(); }); // in order; rejection = start fails\n\nonShutdown(async ({ drained }) => { // all hooks run in parallel\n queue.stop();\n for (const s of getWebSockets()) s.close(1012, \"Server restarting\");\n await drained; // never rejects\n await pool.end(); // close resources only after drained\n});\n\nonHealthCheck(() => ({ // load signal, not health\n utilization: { db_pool: (pool.totalCount - pool.idleCount) / pool.options.max }, // 0–1\n namedMetrics: { db_pool_waiting: pool.waitingCount }, // observability only\n}), { interval: 1000 }); // default and minimum 1000 ms\n```\n\nHook rules:\n- `onStart` must be called while the entry file loads. **Calling it later throws.**\n- `getContext()` **throws outside a request**, including at top level and inside hooks.\n- In health reports, `event_loop` and `memory` are reserved keys. `applicationUtilization` (0–1) overrides the max entry.\n- A health hook that throws never stops the instance. Health hooks don't run locally.\n\n### Edge caching\n\n**Responses are never cached unless you set headers.**\n\n```ts\nreturn Response.json(data, { headers: { \"Netlify-CDN-Cache-Control\": \"public, max-age=3600, durable\" } });\n// Express: res.set(...) Hono: c.header(...) Fastify: reply.header(...)\n```\n\nSupported features:\n- `stale-while-revalidate`\n- Cache keys varied by query, header, language, country, or cookie\n- Invalidation by site or cache tag\n\nEach deploy invalidates the previous cache.\n\n## Context (`context` arg or `getContext()`)\n\n- `geo`: `city`, `country{code,name}`, `subdivision{code,name}`, `latitude`, `longitude`, `postalCode`, `timezone`.\n- `ip` (same as `req.socket.remoteAddress` / `req.ip`), `url` (`URL`), `requestId`.\n- `cookies.get(name)` / `.set(options)` / `.delete(name|options)` follow CookieStore semantics.\n- `deploy`: `id`, `branch`, `context`, `published`, `skewProtectionToken`.\n- `site`: `id`, `name`, `url`. `account.id`. `server.region`.\n- `user`: `{ id, email, expiresAt }` on private projects or with team login protection, otherwise `undefined`.\n- `waitUntil(promise)`.\n\nTypes: `Config`, `Context`, `HealthReport`, `HealthCheckHook`, `HealthCheckOptions`, `LifecycleHook`, `ShutdownHook`, `ShutdownContext`, `ServerRegion`, `ServerSize`, `UpgradeWebSocketOptions`, `WebSocketUpgrade`.\n\n## Configuration\n\nSet 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**.\n\n```toml\n[server]\n region = \"fra\"\n size = \"medium\"\n[server.scale]\n max = 2\n```\n\n| Key | Values / default |\n|---|---|\n| `path` | One or more paths starting with `/`. Same syntax as [function paths](https://docs.netlify.com/build/functions/configuration/#routing). Default `/*` |\n| `excludedPath` | Paths handed back to the rest of the project, e.g. `[\"/legacy/*\", \"/status\"]` |\n| `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 |\n| `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 |\n| `scale` | `{ min, max }`. **`min` must be 0** in Early Access. `max` ≤ 3, or 1 on Free/Personal. Higher values fail the deploy |\n| `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()` |\n\nOther settings:\n- **Environment variables:** use `process.env` with variables scoped to **Functions**. Values are fixed at deploy time, so **redeploy after changes**.\n- **Filesystem:** read-only except `/tmp`, which is per-instance and wiped on stop.\n\n## Routing\n\nRequests are handled in this order:\n1. Edge functions\n2. Redirects/rewrites\n3. Static files\n4. Functions\n5. The server, which owns its own 404s\n\n> ⚠️ **Server gets no requests?** Check these causes:\n> - An SPA catch-all `/* /index.html 200` swallows everything. Scope it to frontend paths.\n> - A static file or function already occupies the same path. **Static files always win.**\n> - `path`/`excludedPath` excludes the path.\n> - `/.netlify/server/` is reserved.\n> - **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.\n\nChoosing between options:\n- Use a server for a new backend.\n- Use [scheduled functions](https://docs.netlify.com/build/functions/scheduled-functions/) for cron jobs and webhooks.\n- Use edge functions for logic close to visitors.\n- Functions are cheaper for rarely used backends, because instances idle for 5 min before stopping.\n\n## Instances and lifecycle\n\n**Assume multiple instances.** They overlap during deploys and are replaced every 8 h, and memory and `/tmp` are per-instance. Practical consequences:\n- In-memory state is a cache. Put shared data in Netlify Database or Netlify Blobs.\n- Each instance holds its own WebSocket connections.\n- Once-only work can run twice or never. Use a scheduled function and record completion.\n\nScaling and limits:\n- **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.\n- **Routing:** new requests go to the least-loaded instance, judged by event loop, memory, and health hooks.\n- **Scale to zero:** an instance stops after 5 min idle. Open requests, WS/SSE connections, and `waitUntil` work pause the timer; `setInterval` does not.\n- **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.\n\nShutdown sequence:\n1. New traffic stops.\n2. `SIGTERM` is sent.\n3. Your server stops accepting connections.\n4. Shutdown hooks start.\n5. In-flight work and connections get up to **90 s**.\n6. Hooks get up to **115 s** from their start (at least 25 s after work ends).\n7. Remaining connections are force-closed.\n\nClose sockets with code `1012` in `onShutdown` so clients move immediately.\n\n**Deploys:**\n- 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.\n- Rollback rolls back the server too.\n- 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.\n\n## Limits\n\n| Limit | Value |\n|---|---|\n| Response timeout | **20 s to send status + headers, else 502. Cold-start time is included.** Stream the body, or respond and finish with `waitUntil` |\n| Request duration (incl. WS/SSE) | 30 min; 2 h on Pro, Business, and Enterprise |\n| Outbound connections | Closed after 60 s idle; keepalives don't count |\n| Instance lifetime | 8 h |\n| Instances | 3 (credit-based Pro/Enterprise); 1 (Free/Personal) |\n\n## Errors\n\n| Status | Meaning / fix |\n|---|---|\n| 429 | All concurrency slots (32/64/128 by size) are full at max instances. Long SSE streams are often the cause |\n| 500 | The instance failed to start (top-level/start hook threw, or no listen on PORT within 10 s), or the handler threw |\n| 501 | WebSocket upgrade on a directly exported Express/Connect app. Use `listen()` or `createServer` |\n| 502 | No headers within 20 s (including cold start), or the instance crashed/OOM'd |\n\n## Local dev and logs\n\n**Local dev:**\n- Run `netlify dev` (CLI 27.17.0+). The **Netlify Vite plugin doesn't run the server.**\n- The CLI restarts the server on changes inside `netlify/server/` only. Restart the CLI for changes elsewhere.\n- Local differences from production:\n - Single instance.\n - `path`/`excludedPath` ignored.\n - No limits enforced.\n - 5 s shutdown.\n - No `SIGTERM` on Windows.\n - No health hooks.\n- For E2E tests, use `@netlify/dev`: `new NetlifyDev({ projectRoot, server: { enabled: true } })`, then `start()` / `stop()`.\n\n**Monitoring and logs:**\n- 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.\n - **Overview:** requests/errors, p95 latency, memory, CPU, and saturation.\n - **Instances table:** state, start reason, and failed-start warnings.\n - **Requests view:** cold start, queue wait, and **Open in Observability**.\n - **Logs view.**\n- Per-request views are also in [observability](https://docs.netlify.com/manage/monitoring/observability/overview/).\n- Use `console.*` inside a request to attach the `requestId`. Direct `process.stdout` writes aren't linked to requests.\n\n**CLI and log drains:**\n\n```bash\nnetlify logs # server + functions + edge functions, last 10 min\nnetlify logs --source server --since 30m # server only; --until ends the window\nnetlify logs --source server --follow # stream lines as written\n```\n\n- `--level` and `--json` work. **`--deploy-id` and `--url` don't work with server logs**, because they can't be filtered by deploy.\n- Long windows show only the most recent lines. Narrow `--since`/`--until` to see older ones.\n- For [log drains](https://docs.netlify.com/manage/monitoring/log-drains/#configure-a-log-drain), select **Server logs** as a log type.\n\n<!-- Gaps: instance cap, medium/large size availability, and scale.max default for Business plans are not documented. -->\n<!-- Exact per-instance WebSocket limit, netlify.toml spelling of excludedPath/includedFiles, and GA credit rates are unstated. -->\n\n<!-- system: agent-context/server/system.md — human-owned, merged by ctx-gen; edit system.md, not this section -->\n# Netlify house rules (server)\n\nThese are org conventions, not docs facts — they are merged into the rendered\nskill by ctx-gen and are never generated. Owned by the Netlify Server team.\n\n1. Never keep a server alive on purpose: no self-pings, no `setInterval` or\n scheduled function that calls the server, no `waitUntil` chain that\n schedules more work to stay running. Scale to zero is the design. If the\n user asks for an always-on server, explain this and build without it.\n2. Run scheduled work with a scheduled function that calls a server route,\n never with timers inside the server.\n3. An endpoint that fetches a URL the user supplies must resolve the hostname\n and refuse loopback, private, link-local and unique-local addresses\n (including 169.254.169.254), re-check after every redirect, and return only\n what the feature needs. Never build a generic `/proxy?url=` endpoint or\n forward the caller's method, headers or body — that is an open relay.\n4. Process memory is lost on every scale-to-zero, deploy and platform\n maintenance event. In-memory caches are fine; anything that must survive\n belongs in Netlify Blobs or Netlify Database.\n5. Don't detach child processes; they are killed on scale-to-zero. Keep work\n in-process with `waitUntil`, or use a background function.\n"
}SHA-256 of public snapshot: 0a733d36fa8723219c193e69f3a9dfe3cae25e55aeb2f4d0e3588e706a4136bd