/netlify-skills:netlify-serverfrom netlify-skills
Build and deploy long-lived Node.js backends on Netlify Server (Early Access). Supports Express, Fastify, Hono, Koa apps, REST/GraphQL APIs, WebSockets, SSE, AI streaming, background work with waitUntil, health checks, edge caching, and debugging.
Ships in netlify-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
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.
// ✅ 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/*" };
// ✅ 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);
// ❌ 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.
netlify/server/index.ts, .mts, .js, or .mjs. The build fails if more than one exists.PORT is set.await is awaited).onStart hooks run in order.Netlify uses the first matching row for the default export:
| Default export | Run as | WebSockets |
|---|---|---|
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 params | Wrapped in its own HTTP server | 501 |
| Any other function | (request, context) => Response | upgradeWebSocket |
| Anything else / nothing | Waits 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.PORTwins. If none listens on it, the start fails.- Reserved ports are
53and15000–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
LISTENneed traffic at least every 60 s (e.g.SELECT 1), or must reconnect on close. The symptom isConnection terminated unexpectedly.
// 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);
// 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 });
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:
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");
};
ws on a self-started server)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.
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" } });
};
Browser WebSocket doesn't reconnect on its own; EventSource does.
function connect() {
const s = new WebSocket("wss://example.com/api/chat");
s.addEventListener("close", (e) => setTimeout(connect, e.code === 1012 ? 0 : 1000));
return s;
}
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.event_loop and memory are reserved keys. applicationUtilization (0–1) overrides the max entry.Responses are never cached unless you set headers.
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-revalidateEach deploy invalidates the previous cache.
context arg or 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.
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.
[server]
region = "fra"
size = "medium"
[server.scale]
max = 2
| Key | Values / 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:
process.env with variables scoped to Functions. Values are fixed at deploy time, so redeploy after changes./tmp, which is per-instance and wiped on stop.Requests are handled in this order:
⚠️ Server gets no requests? Check these causes:
- An SPA catch-all
/* /index.html 200swallows everything. Scope it to frontend paths.- A static file or function already occupies the same path. Static files always win.
path/excludedPathexcludes 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:
Assume multiple instances. They overlap during deploys and are replaced every 8 h, and memory and /tmp are per-instance. Practical consequences:
Scaling and limits:
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.waitUntil work pause the timer; setInterval does not.Shutdown sequence:
SIGTERM is sent.Close sockets with code 1012 in onShutdown so clients move immediately.
Deploys:
| Limit | Value |
|---|---|
| Response timeout | 20 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 connections | Closed after 60 s idle; keepalives don't count |
| Instance lifetime | 8 h |
| Instances | 3 (credit-based Pro/Enterprise); 1 (Free/Personal) |
| Status | Meaning / fix |
|---|---|
| 429 | All concurrency slots (32/64/128 by size) are full at max instances. Long SSE streams are often the cause |
| 500 | The instance failed to start (top-level/start hook threw, or no listen on PORT within 10 s), or the handler threw |
| 501 | WebSocket upgrade on a directly exported Express/Connect app. Use listen() or createServer |
| 502 | No headers within 20 s (including cold start), or the instance crashed/OOM'd |
Local dev:
netlify dev (CLI 27.17.0+). The Netlify Vite plugin doesn't run the server.netlify/server/ only. Restart the CLI for changes elsewhere.path/excludedPath ignored.SIGTERM on Windows.@netlify/dev: new NetlifyDev({ projectRoot, server: { enabled: true } }), then start() / stop().Monitoring and logs:
console.* inside a request to attach the requestId. Direct process.stdout writes aren't linked to requests.CLI and log drains:
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.--since/--until to see older ones.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.
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./proxy?url= endpoint or
forward the caller's method, headers or body — that is an open relay.waitUntil, or use a background function.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
netlify-server, serverless-backend, nodejs-backend, real-time, websocket
16 skills in this plugin
/netlify-access-controlPicks the right Netlify site-protection layer and disambiguates the three unrelated "auth" concepts users conflate — app-user login (Netlify Identity), site-load gating (Password Protection / project visibility), and dashboard SAML SSO. Use it when asked to password-protect a site or Deploy Preview, make a project private/public, restrict a site to your team, require SSO to view a site, set up company-wide or internal-app SSO, invite users to a private project, or know which team member made a request to a private site. Also use it for SSO-session symptoms on protected sites: "logged out mid-session", 401s after about an hour, or token expiry/refresh questions. Not for wiring auth code — route app-login setup to netlify-identity./netlify-agent-runnerRun AI agent tasks remotely on Netlify using Claude, Codex, or Gemini. Use when the user wants to run an AI agent on their site, get a second opinion from another model, or delegate development tasks to run remotely against their repo./netlify-ai-gatewayUse Netlify AI Gateway to call OpenAI, Anthropic Claude, Google Gemini, Meta, TypeSafe (Jev), or OpenRouter-hosted models (xAI/DeepSeek/Mistral/Qwen) from Netlify Functions or Edge Functions without managing provider accounts or API keys. Reach for this when adding an AI feature to a Netlify app — a chatbot, text summarizer, image generator, joke/content generator, form-submission routing or analysis, or any LLM call — or when wiring the OpenAI/Anthropic/Gemini/TypeSafe/OpenRouter SDK into a Netlify Function, choosing which env vars to use, streaming long generations, or debugging why gateway calls fail at build time or return 401./netlify-blobsStore and retrieve unstructured objects, files, and cache-like state on Netlify with the @netlify/blobs module. Use when persisting user file uploads (images/documents), caching computed output from functions or Background Functions, serving downloadable assets, storing JSON blobs keyed by ID, or seeding deploy-specific data. Reach for this for key/value or object storage from Functions, Edge Functions, or Build Plugins — not for per-user, transactional, or relational data (use Netlify DB for that). Triggers include "save an uploaded file", "cache API results", "store generated site map", "key/value store for a function", or "file uploads without a database"./netlify-cachingCache dynamic and static responses on Netlify's CDN from Functions, Edge Functions, Netlify Server, and proxies. Use when you add caching or cache-control headers to a function or server response, tune cache TTL or stale-while-revalidate, set up the durable cache, vary a cache key by query/header/cookie/country/language, purge or invalidate the cache by site or cache tag, use the programmatic Cache API (caches.open/match/put) or @netlify/cache helpers (fetchWithCache/cacheHeaders/getCacheStatus/purgeCache), speed up an expensive API call, add ISR or on-demand revalidation, or debug why a response is or isn't cached via the Cache-Status header./netlify-configConfigure Netlify builds and routing via netlify.toml, _redirects, and _headers. Use when setting a build command or publish directory, validating netlify.toml against its JSON schema, adding redirects/rewrites/proxies or an SPA fallback rewrite, or setting custom response headers or basic auth. Also use when managing environment variables and secrets, scoping vars per deploy context, marking a var as secret or disabling secret scanning, handling sensitive vars in fork Deploy Previews, configuring functions bundling or the Netlify Server region/size, ignoring builds, or wiring up a monorepo or JavaScript SPA on Netlify.Other plugins' skills for the same job
npx claudepluginhub netlify/context-and-tools --plugin netlify-skills