[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77TVDH8WMP6KS8K56Z9316A":3,"skill-same:01M77TVDH8WMP6KS8K56Z9316A":71},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":27,"commitSha":28,"skillDirectory":29,"forksCount":30,"repositoryHtmlUrl":31,"repositoryHomepageUrl":6,"ownerHtmlUrl":32,"ownerBlogUrl":33,"ownerDescription":6,"updatedAt":34,"install":35,"resources":48},"01M77TVDH8WMP6KS8K56Z9316A","neon-functions",null,"Long-running, serverless Node.js HTTP functions deployed onto your Neon branch, with DATABASE_URL injected automatically and compute that runs next to your data. Use when a user wants to host an API, an AI agent with long streaming responses, a WebSocket or server-sent-events (SSE) server, a webhook handler, a Discord bot, an MCP server, or any request\u002Fresponse workload that risks timing out on short, lambda-style serverless functions — and wants it to branch with their database. Triggers include \"serverless function\", \"deploy an API\", \"long-running function\", \"streaming agent\", \"SSE server\", \"WebSocket server\", \"webhook handler\", \"MCP server\", \"run code next to my database\", \"function that won't time out\", \"function logs\", \"Neon Functions\", and \"Neon Compute\".","Reihantt6\u002Fsns-myagent","Reihantt6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F219822095?v=4","01M77KK94PV8B7C2D9XWXNS8DJ","Mohamad Reihan tegar prasetya","01M77KK958QFMTHYXGXFV7KZ79",2,"MIT","https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fneon-functions\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\ndescription: \"Long-running, serverless Node.js HTTP functions deployed onto your Neon branch, with DATABASE_URL injected automatically and compute that runs next to your data. Use when a user wants to host an API, an AI agent with long streaming responses, a WebSocket or server-sent-events (SSE) server, a webhook handler, a Discord bot, an MCP server, or any request\u002Fresponse workload that risks timing out on short, lambda-style serverless functions — and wants it to branch with their database. Triggers include \\\"serverless function\\\", \\\"deploy an API\\\", \\\"long-running function\\\", \\\"streaming agent\\\", \\\"SSE server\\\", \\\"WebSocket server\\\", \\\"webhook handler\\\", \\\"MCP server\\\", \\\"run code next to my database\\\", \\\"function that won't time out\\\", \\\"function logs\\\", \\\"Neon Functions\\\", and \\\"Neon Compute\\\".\"\nmetadata: {\"parent\":\"neon\",\"source\":\"https:\u002F\u002Fgithub.com\u002Fneondatabase\u002Fagent-skills\u002Ftree\u002Fmain\u002Fskills\u002Fneon-functions\"}\n---\n**FIRST**: Use the parent `neon` skill for a Neon overview, getting started with Neon, Neon development best practices, and more.\n\nIf the `neon` skill is not installed, fetch it from https:\u002F\u002Fneon.com\u002Fdocs\u002Fai\u002Fskills\u002Fneon\u002FSKILL.md or install it with:\n\n```bash\nnpx skills add neondatabase\u002Fagent-skills --skill neon\n```\n\n# Neon Functions\n\nThis is a public beta feature and only available in `us-east-2`.\n\nNeon Functions are long-running Node.js HTTP handlers deployed onto a Neon branch. Each function gets a public HTTPS URL, runs in the same region as your database, and — if the branch has Postgres — gets `DATABASE_URL` injected automatically. You deploy and manage them through the same Neon CLI, `neon.ts`, and API you already use.\n\nUse this skill to help the user define, run locally, deploy, and manage functions next to their database. Deliver a deployed function with its invocation URL, a working local `neon dev` loop, or a precise answer from the official Neon docs.\n\n## When to Use\n\nReach for Neon Functions when the workload is a request\u002Fresponse handler that benefits from staying alive and staying close to the data:\n\n- **Long-running request\u002Fresponse flows that outlast lambda-style limits.** Agents that make several LLM calls and tool invocations per request, or image\u002Fvideo generation, routinely blow past the ~10–60s execution caps and short streaming windows of traditional serverless functions. Neon Functions are long-running: the handler just needs to _start_ responding within 15 minutes, and an open stream stays alive as long as bytes keep flowing. That's enough headroom for real agent workloads.\n- **Stateful streaming without bolting on Redis.** Because a function stays alive across a request, it can host an SSE endpoint or a WebSocket server and hold the connection open in-process — no external state store (Redis, etc.) needed just to keep a stream coherent. Module-scope state (a `pg` pool, an in-memory counter) persists across requests on the same isolate.\n- **Compute that must sit next to Postgres.** The function runs in the same region as the branch's database, so there are no cross-region round trips on every query. `DATABASE_URL` is injected for you.\n- **A backend that branches with your data.** Each branch runs its own version of the function at its own URL, against its own isolated database (and storage, and gateway) state. Preview deployments, CI, and dev environments each get a self-contained backend — deploying to a child never affects the parent.\n- **Webhooks, bots, and post-response work.** Webhook handlers that fan out into multiple DB writes, Discord\u002FWebSocket bots, and fire-and-forget follow-ups via `waitUntil` (analytics, audit logs) all fit.\n\nIf the workload is a pure static site, a cron\u002Fbackground job that needs its own lifecycle and cancellation, or something that must run outside `us-east-2` today, this isn't the right tool yet (see [Timeouts and Runtime Limits](#timeouts-and-runtime-limits) and [Availability](#availability)).\n\n## What It Does\n\n- **Long-running & serverless** — Built for WebSocket servers (see [WebSocket Servers](#websocket-servers)), SSE endpoints (see [Server-Sent Events (SSE)](#server-sent-events-sse)), long agent HTTP streams, and APIs. Still scales to zero when idle.\n- **Web-standard handler** — A function is any default export with a `fetch(request)` method returning a `Response` (Workers\u002FWinterTC-compatible). A Hono app exports exactly that shape, so `export default app` just works. Runs on Node.js 24, so all Node APIs are available.\n- **Close to your database** — Runs in the branch's region; `DATABASE_URL` injected automatically when the branch has Postgres.\n- **Branchable** — Each branch runs its own function version at its own URL against its own isolated state.\n- **Same CLI\u002FAPI** — Deploy and manage via `neon`, `neon.ts`, or the Neon API.\n\n## Availability\n\nCheck this precondition before setting anything up: Neon Functions is a public beta feature available only on new projects in the `us-east-2` region. Confirm the user's Neon project is a new project in `us-east-2`; it can't be enabled on existing projects. Functions usage isn't billed during the public beta.\n\n## Architecture: Where Functions Fit\n\nNeon (Functions included) is **backend primitives, not full-stack app hosting**. Host your app on **Vercel** (or Netlify, or another frontend\u002Fapp host); Functions are the long-running, stateful slice of your backend that lives next to your data. They compose with that platform in two ways:\n\n- **Add a Function to a full-stack app.** Your Next.js \u002F TanStack Start app on Vercel (or Netlify) owns UI, auth (e.g. Neon Auth), and talks directly to Lakebase Postgres and Object Storage. When one workload outgrows the host's short serverless limits — a WebSocket or SSE server, or a long-running agent that would time out — move just that piece onto a Neon Function. (See [Functions as an Agent Backend](#functions-as-an-agent-backend-nextjs-and-similar-frameworks) for the client-direct pattern.)\n- **Run the whole backend control plane on Functions.** Especially when the frontend is **client-only** — TanStack Router, React Router in client mode, and similar SPAs hosted on Vercel or Netlify — the client calls Functions **directly**. Build REST APIs and request\u002Fresponse agents, host **MCP servers**, and run anything stateful or that belongs close to Postgres and Object Storage.\n\nEither way, secure a Function like any standalone REST API: verify a JWT or API key at the top of the handler (see the WARNING under [Functions as an Agent Backend](#functions-as-an-agent-backend-nextjs-and-similar-frameworks)). Because a Function is just your backend, you can **move pieces between your host and Neon** — relocate an agent or a stateful WebSocket server onto a Function when it needs more runtime, and back if needed.\n\n## Setup\n\nFunctions are declared in `neon.ts` (see the `neon` skill for the branch-first workflow and `neon.ts` basics). Add `@neon\u002Fconfig` and declare functions under `preview.functions`, keyed by **slug**:\n\n```typescript\n\u002F\u002F neon.ts\nimport { defineConfig } from \"@neon\u002Fconfig\u002Fv1\";\n\nexport default defineConfig({\n  preview: {\n    functions: {\n      todos: {\n        \u002F\u002F slug: ^[a-z0-9]{1,20}$ — lowercase letters\u002Fdigits, no hyphens\n        name: \"todo api\", \u002F\u002F display label only\n        source: \"src\u002Findex.ts\", \u002F\u002F entry file, relative to neon.ts\n      },\n    },\n  },\n});\n```\n\nThe slug is the function's permanent identity (it appears in the invocation URL and CLI commands) and can't be changed after the first deploy. Use `name` for a human-readable label.\n\nA minimal function — a Hono app that queries the branch's Postgres via the injected `DATABASE_URL`:\n\n```typescript\n\u002F\u002F src\u002Findex.ts\nimport { Hono } from \"hono\";\nimport { drizzle } from \"drizzle-orm\u002Fnode-postgres\";\nimport { Pool } from \"pg\";\nimport { parseEnv } from \"@neon\u002Fenv\";\nimport config from \"..\u002Fneon\";\nimport { todos } from \".\u002Fdb\u002Fschema\";\n\nconst env = parseEnv(config);\nconst pool = new Pool({ connectionString: env.postgres.databaseUrl, max: 5 });\nconst db = drizzle(pool);\n\nconst app = new Hono();\napp.get(\"\u002F\", (c) => c.text(\"Neon + Hono + Drizzle\"));\napp.post(\"\u002Ftodos\", async (c) => {\n  const { text } = await c.req.json\u003C{ text: string }>();\n  const [row] = await db.insert(todos).values({ text }).returning();\n  return c.json(row, 201);\n});\napp.get(\"\u002Ftodos\", async (c) => c.json(await db.select().from(todos)));\n\nexport default app;\n```\n\nCreate the `pg` pool at module scope (reused across requests on the same isolate) and keep `max` small (e.g. 5), since each isolate keeps its own pool.\n\n`parseEnv(config)` requires _every_ variable the config implies. A function that only talks to Postgres over the pooled URL can scope it to just that key — `parseEnv` then validates and returns only what you asked for (the keys autocomplete from your `neon.ts`):\n\n```typescript\nconst { postgres } = parseEnv(config, [\"DATABASE_URL\"]); \u002F\u002F not the unpooled URL, auth, etc.\nconst pool = new Pool({ connectionString: postgres.databaseUrl, max: 5 });\n```\n\n## Develop Locally and Deploy\n\n```bash\nneon dev      # serves every function in neon.ts with hot reload; injects DATABASE_URL & friends\nneon deploy   # bundles with esbuild, uploads, and applies neon.ts to the linked branch\n```\n\nTo deploy a single function without `neon.ts`: `neon functions deploy \u003Cslug> --src src\u002Findex.ts` (`--src` takes either the entry file or a directory containing `index.ts`, `index.mjs`, or `index.js`). Retrieve the public URL with `neon functions get \u003Cslug>` (the `invocation_url` field, of the form `https:\u002F\u002F\u003Cbranch_id>-\u003Cslug>.compute.c-1.us-east-2.aws.neon.tech`). Manage with `neon functions list|get|delete`.\n\nWhen `neon checkout` _creates_ a new branch and a `neon.ts` is present, it applies the policy automatically — deploying the function to the fresh branch. Checking out an existing branch does not re-deploy; run `neon deploy` explicitly.\n\n## Neon Infrastructure as Code (`neon.ts`)\n\nThe `preview.functions` block from [Setup](#setup) is part of `neon.ts`, Neon's infrastructure-as-code file — one TypeScript file declares every function (its `source`, display `name`, and `env`) alongside any other branch services, in version control (see the `neon` skill for the full reference). Treat it like Terraform for your branch:\n\n```bash\nneon config status   # print the branch's live config (deployed functions)\nneon config plan     # dry-run diff of what apply would change\nneon config apply    # bundle + deploy the declared functions  (neon deploy is an alias)\n```\n\nFunctions are **branch-scoped**: each branch runs its own deployment at its own URL. When a `neon.ts` is present, `neon checkout` applies the policy as it _creates_ a branch, so a fresh preview\u002FCI branch comes up with the function already deployed. Checking out an _existing_ branch doesn't redeploy — run `neon deploy` to apply changes.\n\nPer-branch deploy tuning (e.g. `runtime`) lives in the `branch` closure, keyed by slug, so it can vary by branch without changing which functions exist:\n\n```typescript\nexport default defineConfig({\n  preview: {\n    functions: { todos: { name: \"todo api\", source: \"src\u002Findex.ts\" } },\n  },\n  branch: (branch) => ({\n    preview: { functions: { todos: { runtime: \"nodejs24\" } } },\n  }),\n});\n```\n\n## Environment Variables\n\nNeon injects branch-scoped connection strings and service URLs at runtime — you don't declare these or pass them at deploy time:\n\n| Variable                | Notes                                                                                    |\n| ----------------------- | ---------------------------------------------------------------------------------------- |\n| `NEON_BRANCH`           | The branch **name** (e.g. `main`, `preview\u002Ffoo`). Injected on every branch, including the default. |\n| `DATABASE_URL`          | Pooled connection string. Use for most queries. Present only if the branch has Postgres. |\n| `DATABASE_URL_UNPOOLED` | Direct connection. Use for migrations, `LISTEN`\u002F`NOTIFY`, multi-round-trip transactions. |\n| `NEON_AUTH_BASE_URL`    | Present when Neon Auth is enabled on the branch.                                         |\n| `NEON_DATA_API_URL`     | Present when the Data API is enabled on the branch.                                      |\n\nObject storage (`AWS_*`) and AI Gateway (`NEON_AI_GATEWAY_*`) vars are also injected when those services are declared — see the `neon-object-storage` and `neon-ai-gateway` skills.\n\n`neon env pull` \u002F `neon-env run` \u002F `neon dev` emit `NEON_BRANCH` (and the connection strings) into your local dev environment too, so local runs mirror the deployed runtime.\n\n**Your own secrets** are per-deployment. Set them with `--env KEY=VALUE` on `neon functions deploy` (repeatable; `--env KEY=` deletes a key, unmentioned keys carry over), or declare them in `neon.ts` under the function's `env` (resolved at deploy time, so read from `process.env` to avoid hardcoding):\n\n```typescript\nfunctions: {\n  todos: {\n    name: \"todo api\",\n    source: \"src\u002Findex.ts\",\n    env: { RESEND_API_KEY: process.env.RESEND_API_KEY! },\n  },\n}\n```\n\nLoad a `.env` before deploy with `neon deploy --env .env.production`. Pull the branch's Neon-managed vars onto disk for local dev with `neon env pull` (`link`\u002F`checkout` do this automatically; pass `--no-env-pull` to skip and use `neon-env run -- \u003Ccmd>` for runtime injection). Limits: ≤1,000 vars, ≤64 KiB total, and the `NEON_` prefix is reserved.\n\n## Connecting to Postgres\n\nWhen the branch has Postgres, Neon **injects the connection strings at runtime** — you don't declare them, pass them at deploy time, or hardcode anything. The two you'll use:\n\n- `DATABASE_URL` — **pooled** connection string (routed through Neon's connection pooler). Use it for normal request\u002Fresponse query traffic. Kept un-prefixed because every Postgres ORM (Drizzle, Prisma, Knex, …) reads `DATABASE_URL` by default.\n- `DATABASE_URL_UNPOOLED` — **direct** connection string to the same database. Use it for migrations, `LISTEN`\u002F`NOTIFY`, and long multi-statement transactions.\n\n**Use Drizzle (or another ORM) on top of node-postgres (`pg`)** for queries and schema management — not Neon's serverless driver. Functions are long-running and reuse an isolate across many requests, so a persistent `pg` pool is the right fit; the serverless driver's HTTP transport is meant for fully isolated, lambda-style runtimes.\n\nCreate the connection pool **once at module scope** and reuse it across requests — don't open a connection per request:\n\n```typescript\nimport { drizzle } from \"drizzle-orm\u002Fnode-postgres\";\nimport { Pool } from \"pg\";\n\n\u002F\u002F Created once per isolate; reused by every request that isolate handles.\nconst pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });\nconst db = drizzle(pool);\n```\n\n**Pooling is recommended because an isolate is reused across many requests** (and several requests can be in flight on the same isolate at once — see [Timeouts and Runtime Limits](#timeouts-and-runtime-limits)). A module-scope pool is opened once on cold start and then shared by every subsequent request that isolate serves, so you amortize connection setup instead of paying it on every request and you avoid exhausting Postgres connections under load.\n\nKeep `max` small (e.g. `5`): each isolate keeps its own pool, so total connections to Postgres scale with the number of live isolates. You don't need to close the pool on shutdown — when the runtime evicts an isolate it sends `SIGINT`\u002F`SIGTERM`, and Neon's pooler reclaims those connections for you, so an explicit drain handler is redundant.\n\n> Reading `process.env.DATABASE_URL` directly works everywhere. The function in [Setup](#setup) instead uses `@neon\u002Fenv`'s `parseEnv(config)` to read the same value in a typed, validated way — either is fine.\n\n## Timeouts and Runtime Limits\n\nFunctions are long-running but **still serverless** — they are a request\u002Fresponse runtime, not a background job runner. The hard limits:\n\n- **Time to first byte: 15 minutes.** Your handler must _begin_ returning a response within 15 minutes of receiving a request. Most handlers finish in seconds; the 15-minute ceiling exists so agent workloads like image\u002Fvideo generation have room.\n- **Heartbeat: 15 minutes.** Open WebSocket\u002FSSE connections stay alive as long as data flows. The timeout only fires when a connection goes silent — send at least one byte every 15 minutes to keep a quiet stream alive.\n- **`waitUntil`: 15 minutes.** Work registered with `waitUntil` keeps the invocation alive after the response is sent, up to 15 minutes — for cleanup like analytics writes and audit logs, **not** a background job runner. (`waitUntil` from `@neon\u002Ffunctions` is currently a stub during the preview.)\n- **Idle eviction.** With no active connections Neon shuts the function down; it may also evict\u002Frestart for operational reasons — e.g. maintenance, or moving the function to a different compute node (active functions can run for hours first). Treat eviction like a process restart — WebSocket\u002FSSE clients must reconnect. Neon sends `SIGINT` before evicting, so a `process.on(\"SIGINT\", ...)` handler lets you detect that the function is about to be evicted and run any last-minute cleanup. You don't need one just to close Postgres connections — Neon's pooler reclaims those on its own.\n- **Runtime:** Node.js 24, memory fixed at 2048 MiB during the preview. Slugs must match `^[a-z0-9]{1,20}$`. **An isolate is reused across many requests** — multiple requests can be in flight on the same isolate at once (interleaved on Node's single-threaded event loop), and under load the runtime runs several isolates in parallel, each with its own copy of module state. State held in module scope is therefore per-isolate (shared by every request that isolate handles) and in-memory only — persist anything that must survive eviction in Postgres. This reuse is exactly why you create a connection pool once at module scope rather than per request (see [Connecting to Postgres](#connecting-to-postgres)).\n\n## Functions as an Agent Backend (Next.js and Similar Frameworks)\n\nA Neon Function is a great home for an AI agent precisely because it **doesn't time out** the way lambda-style serverless does (15-minute budget, see [Timeouts and Runtime Limits](#timeouts-and-runtime-limits)). But that advantage disappears the moment you **proxy the agent stream through your web app's backend** — a Next.js route handler, Remix\u002FSvelteKit\u002FNuxt action, etc. hosted on Vercel, Netlify, Cloudflare, and the like. Those platforms cap serverless\u002Fedge execution at short windows (often ~10–60s, sometimes up to ~300s), so a long agent or image\u002Fvideo generation stream gets cut off mid-response even though the Neon Function would happily keep going.\n\n**Building the agent itself.** The [Vercel AI SDK](https:\u002F\u002Fai-sdk.dev) and [Mastra](https:\u002F\u002Fmastra.ai) are the recommended ways to build the agent — point either at the Neon AI Gateway (see the `neon-ai-gateway` skill) for one credential across every model, with no extra provider keys. For a complete AI SDK agent running as a Function (streaming `toUIMessageStreamResponse`, multi-step tool calling next to Postgres, and persisting generated images to Object Storage), see [references\u002Fai-sdk.md](https:\u002F\u002Fneon.com\u002Fdocs\u002Fai\u002Fskills\u002Fneon-functions\u002Freferences\u002Fai-sdk.md); for the Mastra equivalent with built-in tracing, see [references\u002Fmastra-studio.md](https:\u002F\u002Fneon.com\u002Fdocs\u002Fai\u002Fskills\u002Fneon-functions\u002Freferences\u002Fmastra-studio.md).\n\n**The fix: call the function directly from the client.** Don't route the long request through your app server.\n\n```\nBrowser ──(Authorization: Bearer \u003CJWT>)──▶  Neon Function (agent)   ✅ no host timeout\nBrowser ──▶ your app backend ──▶ Neon Function                       ❌ host cuts the stream\n```\n\n- Mint a **short-lived JWT** on your app backend (e.g. better-auth's `jwt` plugin, NextAuth, or your own signer) — that call is fast and well within host limits.\n- Hand the token to the client and have it call the Neon Function **directly** (cross-origin), e.g. with the Vercel AI SDK: `new DefaultChatTransport({ api: NEON_FUNCTION_URL, fetch })` where `fetch` attaches `Authorization: Bearer \u003Ctoken>`. Your app server is never in the path of the long stream.\n- Add **CORS** so the browser can reach it (handle `OPTIONS`, set `Access-Control-Allow-Origin`\u002F`-Headers`).\n\n> [!WARNING]\n> A Neon Function has a **public HTTPS URL — it is reachable by anyone.** A direct client→function call means there is no app backend in front of it to gate access, so **you must authenticate the function yourself.** Verify a JWT (e.g. against your app's JWKS), check a shared secret \u002F API key, or validate a session token at the top of the handler and reject anything else. Never deploy an unauthenticated agent.\n\n```typescript\n\u002F\u002F src\u002Findex.ts — verify the caller before doing any work\nimport { createRemoteJWKSet, jwtVerify } from \"jose\";\n\nconst jwks = createRemoteJWKSet(new URL(`${process.env.AUTH_BASE_URL}\u002Fapi\u002Fauth\u002Fjwks`));\n\nexport default {\n  async fetch(request: Request) {\n    if (request.method === \"OPTIONS\") return new Response(null, { status: 204, headers: cors(request) });\n\n    const auth = request.headers.get(\"authorization\");\n    if (!auth?.toLowerCase().startsWith(\"bearer \")) {\n      return new Response(\"Unauthorized\", { status: 401, headers: cors(request) });\n    }\n    try {\n      const { payload } = await jwtVerify(auth.slice(7), jwks, {\n        issuer: process.env.AUTH_BASE_URL,\n        audience: process.env.AUTH_BASE_URL,\n      });\n      const userId = payload.sub; \u002F\u002F scope the agent to this user\n      \u002F\u002F ... run the agent, return result.toUIMessageStreamResponse({ headers: cors(request) })\n    } catch {\n      return new Response(\"Unauthorized\", { status: 401, headers: cors(request) });\n    }\n  },\n};\n```\n\nPass the JWKS\u002Fissuer URL to the function via its `env` (see [Environment Variables](#environment-variables)). Persist anything you need to keep (generated images, history) in Postgres — module state doesn't survive eviction.\n\n## WebSocket Servers\n\nA WebSocket server is the canonical Functions workload: a long-running handler holds connections open in-process, with no external state store needed to keep a stream coherent. The connection stays alive as long as bytes flow (15-minute heartbeat, see [Timeouts](#timeouts-and-runtime-limits)).\n\n**Upgrade from inside `fetch`.** Call `upgradeWebSocket(request)` from [`@neon\u002Ffunctions`](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@neon\u002Ffunctions) and return the response it gives you. There is one entrypoint and no WebSocket dependency to install:\n\n```typescript\nimport { upgradeWebSocket } from \"@neon\u002Ffunctions\";\n\nexport default {\n  async fetch(req: Request): Promise\u003CResponse> {\n    if (req.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\") {\n      return new Response(\"expected a websocket upgrade\", { status: 426 });\n    }\n\n    const { socket, response } = upgradeWebSocket(req);\n    socket.addEventListener(\"message\", (event) => socket.send(event.data));\n    return response;\n  },\n};\n```\n\n`socket` is a standard [`WebSocket`](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FAPI\u002FWebSocket), so `addEventListener` and the `onopen`\u002F`onmessage`\u002F`onclose`\u002F`onerror` properties both work. It is still `CONNECTING` when you get it — the runtime writes the `101` only once your handler returns `response`, and the socket opens then.\n\nThree rules that matter:\n\n- **Return `response` unchanged.** A `101` can't be built as a plain `Response` (the fetch spec caps constructed responses at 200–599), so the runtime hands back an object carrying the pending upgrade. `clone()`, or rebuilding it with `new Response(res.body, res)` as response-rewriting middleware does, discards the upgrade and fails the request.\n- **Refuse a handshake by returning an ordinary `Response`.** A `401`, `403` or `404` is relayed to the client as-is. That is how you gate a socket.\n- **`binaryType` defaults to `\"arraybuffer\"`**, not the browser's `\"blob\"`. `event.data` is a `string` for text frames and an `ArrayBuffer` for binary ones, so branch on `typeof`.\n\n**With auth.** Browsers can't set headers on a WebSocket, so authenticate with a `?token=` query param (verify it the same way as the [agent backend](#functions-as-an-agent-backend-nextjs-and-similar-frameworks): `jwtVerify` against your JWKS) and refuse before upgrading:\n\n```typescript\n\u002F\u002F src\u002Findex.ts\nimport { upgradeWebSocket } from \"@neon\u002Ffunctions\";\n\nconst clients = new Set\u003CWebSocket>();\n\nexport default {\n  async fetch(request: Request): Promise\u003CResponse> {\n    if (request.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\") {\n      return new Response(\"WebSocket endpoint — connect with ?token=\u003Cjwt>\");\n    }\n\n    const url = new URL(request.url);\n    const identity = await verifyToken(url.searchParams.get(\"token\"));\n    if (!identity) return new Response(\"unauthorized\", { status: 401 });\n\n    const { socket, response } = upgradeWebSocket(request);\n    clients.add(socket);\n    socket.addEventListener(\"close\", () => clients.delete(socket));\n    socket.addEventListener(\"message\", (event) => {\n      if (typeof event.data !== \"string\") return;\n      persist(identity.id, event.data); \u002F\u002F fan out to every isolate — see below\n    });\n    return response;\n  },\n};\n```\n\n**Subprotocols.** Pass `{ protocol }` to select one the client offered; it is echoed in `Sec-WebSocket-Protocol` and exposed as `socket.protocol`. Selecting one the client did not offer throws a `TypeError`. Omit it and no protocol is negotiated. No extensions are negotiated either — `socket.extensions` is always `\"\"` and `permessage-deflate` is not available.\n\n**Hono.** Nothing special is needed: `upgradeWebSocket` takes a `Request`, so call it inside a route with `c.req.raw` and return the response. Auth and everything else is ordinary middleware.\n\n```typescript\n\u002F\u002F src\u002Findex.ts\nimport { Hono } from \"hono\";\nimport { upgradeWebSocket } from \"@neon\u002Ffunctions\";\n\nconst app = new Hono();\n\napp.get(\"\u002F\", (c) => c.text(\"ok\"));\n\napp.get(\"\u002Fws\", async (c) => {\n  const identity = await verifyToken(c.req.query(\"token\"));\n  if (!identity) return c.text(\"Unauthorized\", 401);\n\n  const { socket, response } = upgradeWebSocket(c.req.raw);\n  socket.addEventListener(\"open\", () => socket.send(\"welcome\"));\n  socket.addEventListener(\"message\", (event) => socket.send(`echo: ${event.data}`));\n  return response;\n});\n\nexport default { fetch: (request: Request) => app.fetch(request) };\n```\n\n### Heartbeat (keep the socket alive)\n\nA connection stays open **only while bytes flow**: Neon evicts a silent stream after 15 minutes ([Timeouts and Runtime Limits](#timeouts-and-runtime-limits)), and intermediary proxies \u002F load balancers are usually far stricter (often tens of seconds). Don't rely on the app being chatty enough — send a periodic keepalive from the server so the socket never goes quiet.\n\nThe standard `WebSocket` interface has no `ping()`, so send an application-level message the client ignores:\n\n```typescript\nconst HEARTBEAT_MS = 25_000; \u002F\u002F comfortably under proxy idle timeouts\n\nconst beat = setInterval(() => {\n  for (const socket of clients) {\n    if (socket.readyState === socket.OPEN) socket.send('{\"type\":\"ping\"}');\n  }\n}, HEARTBEAT_MS);\nbeat.unref?.();\n```\n\nThe client should skip these when handling messages. The server does answer a client-sent ping frame with a pong automatically, so a browser client can drive the heartbeat instead if you'd rather not filter messages.\n\n### Keeping clients in sync across isolates (do not skip this)\n\nUnder load the runtime runs **several isolates in parallel, each with its own copy of module state** — so each isolate has its own `clients` set. Broadcasting only to that local set means a client on isolate A never sees an event produced on isolate B, and the feed silently fractures. It's easy to miss: `neon dev` runs a single process (one isolate), so in-process broadcast always _looks_ fine locally but breaks in production, where concurrent connections spread across many isolates.\n\nModule state doesn't survive eviction anyway, so **Postgres is the shared source of truth**. Pick a fan-out strategy. In every snippet below, `pool` is a pooled `pg` client and `clients` is this isolate's `Set` of live connections.\n\n**1. Poll Postgres — the default, and the only option that keeps Scale to Zero.** Each isolate re-reads the shared state (or rows past a cursor) on a short interval and pushes changes to its own clients. One query per isolate per tick (not per client), and none when the isolate has no clients — so an idle compute still suspends.\n\n```typescript\nlet lastId = 0;\nconst poller = setInterval(async () => {\n  if (clients.size === 0) return; \u002F\u002F no clients here → no query → compute can scale to zero\n  const { rows } = await pool.query(\n    \"SELECT id, payload FROM events WHERE id > $1 ORDER BY id\",\n    [lastId],\n  );\n  for (const { id, payload } of rows) {\n    lastId = id;\n    for (const socket of clients) {\n      if (socket.readyState === socket.OPEN) socket.send(payload);\n    }\n  }\n}, 1000);\npoller.unref?.();\n```\n\n- **Latency:** up to the interval (~1s) — fine for counters, chat, and dashboards.\n- **Scaling:** database load grows with the number of live isolates, not clients. Keep the cursor on an indexed `serial`\u002F`bigserial` PK and the interval sane.\n- **Scale to Zero:** ✅ preserved — polling stops when no clients are connected, so the compute suspends on its normal timer.\n\n**2. `LISTEN`\u002F`NOTIFY` — lowest latency, but requires disabling Scale to Zero.** Each isolate `LISTEN`s on a channel over a dedicated **unpooled** connection; broadcasting is `NOTIFY`, so every isolate (including the sender's) re-pushes to its sockets. Near-instant — but the listener holds an idle connection that **does not count as active**, so [Scale to Zero](https:\u002F\u002Fneon.com\u002Fdocs\u002Fintroduction\u002Fscale-to-zero) suspends the compute and drops it, silently killing the feed. Only use it on an **always-on** compute (Scale to Zero disabled — a paid-plan setting).\n\n```typescript\nimport { Pool, Client } from \"pg\";\n\nconst pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });\nconst CHANNEL = \"chat_events\";\n\n\u002F\u002F One dedicated DIRECT connection per isolate, just to receive events.\n\u002F\u002F Use DATABASE_URL_UNPOOLED — LISTEN needs a real session, not a pooled one.\nconst listener = new Client({ connectionString: process.env.DATABASE_URL_UNPOOLED });\nlistener.connect().then(() => listener.query(`LISTEN ${CHANNEL}`));\nlistener.on(\"notification\", (msg) => {\n  if (!msg.payload) return;\n  for (const socket of clients) {\n    if (socket.readyState === socket.OPEN) socket.send(msg.payload);\n  }\n});\n\n\u002F\u002F Broadcast by NOTIFYing through the pool — every isolate's listener fires.\nfunction broadcast(event: unknown) {\n  return pool.query(\"SELECT pg_notify($1, $2)\", [CHANNEL, JSON.stringify(event)]);\n}\n```\n\n**3. External pub\u002Fsub (e.g. [Upstash](https:\u002F\u002Fupstash.com) Redis) — best at scale.** For high fan-out, sub-second latency at large connection counts, or multi-region, publish\u002Fsubscribe through a dedicated broker. Highest throughput, and it doesn't touch Postgres or block Scale to Zero — at the cost of another service to run.\n\n**Rule of thumb:** start with **polling** (works with Scale to Zero, no extra infra); switch to `LISTEN`\u002F`NOTIFY` only on always-on compute that needs sub-second latency; move to Redis when fan-out outgrows Postgres.\n\n### Client must reconnect\n\nIdle functions are evicted (and isolates restart for operational reasons), so a client's socket **will** drop — treat reconnection as normal, not exceptional. Reconnect with exponential backoff, capped, and **re-mint a fresh token on every attempt** (tokens are short-lived, so a stale one fails the `upgrade` auth check):\n\n```typescript\nlet closed = false, retry = 0, timer: ReturnType\u003Ctypeof setTimeout>;\n\nasync function connect() {\n  if (closed) return;\n  const token = await getToken(); \u002F\u002F re-mint each attempt; short-lived\n  const ws = new WebSocket(`${WS_URL}?token=${encodeURIComponent(token)}`);\n  ws.onopen = () => { retry = 0; };          \u002F\u002F reset backoff on success\n  ws.onmessage = (e) => { \u002F* apply the event *\u002F };\n  ws.onclose = () => {\n    if (!closed) timer = setTimeout(connect, Math.min(1000 * 2 ** retry++, 15000));\n  };\n  ws.onerror = () => ws.close();             \u002F\u002F let onclose drive the retry\n}\nconnect();\n```\n\nTogether — `upgradeWebSocket` inside `fetch`, JWT auth over `?token=`, cross-isolate fan-out, and client backoff — these compose into a complete realtime chat backend on a single function.\n\n## Server-Sent Events (SSE)\n\nWhen you only need **server → client** streaming (live counters, notifications, progress, token streams), SSE is simpler than a WebSocket and needs no upgrade at all: a plain `fetch` handler returns a `Response` whose body is a `ReadableStream` with `Content-Type: text\u002Fevent-stream`, and the runtime holds it open as long as bytes flow. The browser consumes it with `EventSource`, which **reconnects on its own** — so there's no client backoff to write.\n\n```typescript\n\u002F\u002F src\u002Findex.ts — minimal SSE endpoint\nconst encoder = new TextEncoder();\nexport default {\n  fetch: () =>\n    new Response(\n      new ReadableStream\u003CUint8Array>({\n        start(controller) {\n          controller.enqueue(encoder.encode(\"data: hello\\n\\n\"));\n          const t = setInterval(() => controller.enqueue(encoder.encode(\": ping\\n\\n\")), 25_000);\n          return () => clearInterval(t); \u002F\u002F fires when the client disconnects\n        },\n      }),\n      { headers: { \"Content-Type\": \"text\u002Fevent-stream\", \"Cache-Control\": \"no-cache, no-transform\" } },\n    ),\n};\n```\n\nThe same rules as WebSockets apply. **Heartbeat:** a stream stays open only while bytes flow — Neon's window is 15 minutes ([Timeouts and Runtime Limits](#timeouts-and-runtime-limits)) but proxies are usually far stricter, so emit a `: ping\\n\\n` comment every ~25–30s (shown above) to keep idle streams from being dropped. Keep state in Postgres, and fan out across isolates using one of the [sync strategies](#keeping-clients-in-sync-across-isolates-do-not-skip-this) (hold a `Set` of stream controllers and `enqueue` to each). `EventSource` is GET-only and can't set headers, so authenticate with a `?token=` query param or cookie, exactly like the WebSocket case. [references\u002Fsse.md](https:\u002F\u002Fneon.com\u002Fdocs\u002Fai\u002Fskills\u002Fneon-functions\u002Freferences\u002Fsse.md) has the full pattern — Hono variant, cross-isolate fan-out, wire format, client, and caveats.\n\n## MCP Servers\n\nAn [MCP](https:\u002F\u002Fmodelcontextprotocol.io) server is a natural Functions workload: a long-running HTTP handler that exposes tools to AI clients (Cursor, Claude, ChatGPT, agents), with those tools reading and writing the branch's Postgres right next to the compute. MCP's **streamable HTTP transport** is a plain `POST`\u002F`GET` on a single endpoint (conventionally `\u002Fmcp`), so it maps onto a function's `fetch` handler with no `upgrade` method or extra protocol.\n\nThe simplest host is a Hono app using the official [`@modelcontextprotocol\u002Fsdk`](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Ftypescript-sdk) plus [`@hono\u002Fmcp`](https:\u002F\u002Fgithub.com\u002Fhonojs\u002Fmiddleware\u002Ftree\u002Fmain\u002Fpackages\u002Fmcp), which bridges the transport to a route. Build the server, register its tools, and create the transport once at module scope, then hand every `\u002Fmcp` request to it:\n\n```typescript\nconst transport = new StreamableHTTPTransport();\napp.all(\"\u002Fmcp\", async (c) => {\n  if (!mcpServer.isConnected()) await mcpServer.connect(transport);\n  return transport.handleRequest(c);\n});\n```\n\nBecause the function's URL is public, **authenticate before connecting the transport** — [Better Auth](https:\u002F\u002Fbetter-auth.com) covers both OAuth (its MCP plugin makes your app the authorization server so third-party clients self-authorize per the MCP spec) and a simpler API-key \u002F session-JWT check for your own callers. [references\u002Fmcp.md](https:\u002F\u002Fneon.com\u002Fdocs\u002Fai\u002Fskills\u002Fneon-functions\u002Freferences\u002Fmcp.md) has the full pattern — server with Postgres-backed tools via Drizzle, both Better Auth auth options, and testing with `mcporter` \u002F `add-mcp`.\n\n## Integrations and Observability\n\n### Built-in branch logs\n\n```bash\nneon logs query --branch production --source function --since 1h\n```\n\nFunctions is one of the two sources branch logs cover today, alongside Object Storage. Logs are scoped to a single branch, so pass `--branch` when the deployed function isn't on the branch you're checked out on. Everything else about logs — the required CLI version, filters, the SDK, and the Loki-compatible read API — is in the parent `neon` skill's **Observability** section.\n\n### Application instrumentation\n\nA function is a long-lived Node.js process running a web-standard request\u002Fresponse handler, so standard Node integration SDKs work unchanged. Initialize them once at module load, gated on an env var so local dev and unconfigured branches stay a no-op, and pass secrets via `--env` or `neon.ts` `env`.\n\n- **Sentry** — error monitoring across the HTTP framework, the function runtime, and an agent's own caught\u002Ffallback failures (the long-running case Functions target): see [references\u002Fsentry.md](https:\u002F\u002Fneon.com\u002Fdocs\u002Fai\u002Fskills\u002Fneon-functions\u002Freferences\u002Fsentry.md).\n- **Mastra Studio (Mastra Cloud)** — run a Mastra agent on a function and ship its traces to a Studio project for observability: see [references\u002Fmastra-studio.md](https:\u002F\u002Fneon.com\u002Fdocs\u002Fai\u002Fskills\u002Fneon-functions\u002Freferences\u002Fmastra-studio.md).\n\n## Neon Documentation\n\nThe Neon documentation is the source of truth and Functions is evolving rapidly, so always verify against the official docs. Any doc page can be fetched as markdown by appending `.md` to the URL or by requesting `Accept: text\u002Fmarkdown`. Find the right page from the docs index (https:\u002F\u002Fneon.com\u002Fdocs\u002Fllms.txt) and the changelog announcements.\n\n## Further Reading\n\n- https:\u002F\u002Fneon.com\u002Fdocs\u002Fcompute\u002Ffunctions\u002Foverview.md\n- https:\u002F\u002Fneon.com\u002Fdocs\u002Fcompute\u002Ffunctions\u002Fget-started.md\n- https:\u002F\u002Fneon.com\u002Fdocs\u002Fcompute\u002Ffunctions\u002Fdeploy.md\n- https:\u002F\u002Fneon.com\u002Fdocs\u002Fcompute\u002Ffunctions\u002Fenvironment-variables.md\n- https:\u002F\u002Fneon.com\u002Fdocs\u002Fcompute\u002Ffunctions\u002Freference\u002Fneon-ts.md\n- https:\u002F\u002Fneon.com\u002Fdocs\u002Fcompute\u002Ffunctions\u002Freference\u002Fruntime-limits.md\n- https:\u002F\u002Fneon.com\u002Fdocs\u002Fcompute\u002Ffunctions\u002Fpreview-access.md\n","**FIRST**: Use the parent `neon` skill for a Neon overview, getting started with Neon, Neon development best practices, and more.\n\nIf the `neon` skill is not installed, fetch it from https:\u002F\u002Fneon.com\u002Fdocs\u002Fai\u002Fskills\u002Fneon\u002FSKILL.md or install it with:\n\n```bash\nnpx skills add neondatabase\u002Fagent-skills --skill neon\n```\n\n# Neon Functions\n\nThis is a public beta feature and only available in `us-east-2`.\n\nNeon Functions are long-running Node.js HTTP handlers deployed onto a Neon branch. Each function gets a public HTTPS URL, runs in the same region as your database, and — if the branch has Postgres — gets `DATABASE_URL` injected automatically. You deploy and manage them through the same Neon CLI, `neon.ts`, and API you already use.\n\nUse this skill to help the user define, run locally, deploy, and manage functions next to their database. Deliver a deployed function with its invocation URL, a working local `neon dev` loop, or a precise answer from the official Neon docs.\n\n## When to Use\n\nReach for Neon Functions when the workload is a request\u002Fresponse handler that benefits from staying alive and staying close to the data:\n\n- **Long-running request\u002Fresponse flows that outlast lambda-style limits.** Agents that make several LLM calls and tool invocations per request, or image\u002Fvideo generation, routinely blow past the ~10–60s execution caps and short streaming windows of traditional serverless functions. Neon Functions are long-running: the handler just needs to _start_ responding within 15 minutes, and an open stream stays alive as long as bytes keep flowing. That's enough headroom for real agent workloads.\n- **Stateful streaming without bolting on Redis.** Because a function stays alive across a request, it can host an SSE endpoint or a WebSocket server and hold the connection open in-process — no external state store (Redis, etc.) needed just to keep a stream coherent. Module-scope state (a `pg` pool, an in-memory counter) persists across requests on the same isolate.\n- **Compute that must sit next to Postgres.** The function runs in the same region as the branch's database, so there are no cross-region round trips on every query. `DATABASE_URL` is injected for you.\n- **A backend that branches with your data.** Each branch runs its own version of the function at its own URL, against its own isolated database (and storage, and gateway) state. Preview deployments, CI, and dev environments each get a self-contained backend — deploying to a child never affects the parent.\n- **Webhooks, bots, and post-response work.** Webhook handlers that fan out into multiple DB writes, Discord\u002FWebSocket bots, and fire-and-forget follow-ups via `waitUntil` (analytics, audit logs) all fit.\n\nIf the workload is a pure static site, a cron\u002Fbackground job that needs its own lifecycle and cancellation, or something that must run outside `us-east-2` today, this isn't the right tool yet (see [Timeouts and Runtime Limits](#timeouts-and-runtime-limits) and [Availability](#availability)).\n\n## What It Does\n\n- **Long-running & serverless** — Built for WebSocket servers (see [WebSocket Servers](#websocket-servers)), SSE endpoints (see [Server-Sent Events (SSE)](#server-sent-events-sse)), long agent HTTP streams, and APIs. Still scales to zero when idle.\n- **Web-standard handler** — A function is any default export with a `fetch(request)` method returning a `Response` (Workers\u002FWinterTC-compatible). A Hono app exports exactly that shape, so `export default app` just works. Runs on Node.js 24, so all Node APIs are available.\n- **Close to your database** — Runs in the branch's region; `DATABASE_URL` injected automatically when the branch has Postgres.\n- **Branchable** — Each branch runs its own function version at its own URL against its own isolated state.\n- **Same CLI\u002FAPI** — Deploy and manage via `neon`, `neon.ts`, or the Neon API.\n\n## Availability\n\nCheck this precondition before setting anything up: Neon Functions is a public beta feature available only on new projects in the `us-east-2` region. Confirm the user's Neon project is a new project in `us-east-2`; it can't be enabled on existing projects. Functions usage isn't billed during the public beta.\n\n## Architecture: Where Functions Fit\n\nNeon (Functions included) is **backend primitives, not full-stack app hosting**. Host your app on **Vercel** (or Netlify, or another frontend\u002Fapp host); Functions are the long-running, stateful slice of your backend that lives next to your data. They compose with that platform in two ways:\n\n- **Add a Function to a full-stack app.** Your Next.js \u002F TanStack Start app on Vercel (or Netlify) owns UI, auth (e.g. Neon Auth), and talks directly to Lakebase Postgres and Object Storage. When one workload outgrows the host's short serverless limits — a WebSocket or SSE server, or a long-running agent that would time out — move just that piece onto a Neon Function. (See [Functions as an Agent Backend](#functions-as-an-agent-backend-nextjs-and-similar-frameworks) for the client-direct pattern.)\n- **Run the whole backend control plane on Functions.** Especially when the frontend is **client-only** — TanStack Router, React Router in client mode, and similar SPAs hosted on Vercel or Netlify — the client calls Functions **directly**. Build REST APIs and request\u002Fresponse agents, host **MCP servers**, and run anything stateful or that belongs close to Postgres and Object Storage.\n\nEither way, secure a Function like any standalone REST API: verify a JWT or API key at the top of the handler (see the WARNING under [Functions as an Agent Backend](#functions-as-an-agent-backend-nextjs-and-similar-frameworks)). Because a Function is just your backend, you can **move pieces between your host and Neon** — relocate an agent or a stateful WebSocket server onto a Function when it needs more runtime, and back if needed.\n\n## Setup\n\nFunctions are declared in `neon.ts` (see the `neon` skill for the branch-first workflow and `neon.ts` basics). Add `@neon\u002Fconfig` and declare functions under `preview.functions`, keyed by **slug**:\n\n```typescript\n\u002F\u002F neon.ts\nimport { defineConfig } from \"@neon\u002Fconfig\u002Fv1\";\n\nexport default defineConfig({\n  preview: {\n    functions: {\n      todos: {\n        \u002F\u002F slug: ^[a-z0-9]{1,20}$ — lowercase letters\u002Fdigits, no hyphens\n        name: \"todo api\", \u002F\u002F display label only\n        source: \"src\u002Findex.ts\", \u002F\u002F entry file, relative to neon.ts\n      },\n    },\n  },\n});\n```\n\nThe slug is the function's permanent identity (it appears in the invocation URL and CLI commands) and can't be changed after the first deploy. Use `name` for a human-readable label.\n\nA minimal function — a Hono app that queries the branch's Postgres via the injected `DATABASE_URL`:\n\n```typescript\n\u002F\u002F src\u002Findex.ts\nimport { Hono } from \"hono\";\nimport { drizzle } from \"drizzle-orm\u002Fnode-postgres\";\nimport { Pool } from \"pg\";\nimport { parseEnv } from \"@neon\u002Fenv\";\nimport config from \"..\u002Fneon\";\nimport { todos } from \".\u002Fdb\u002Fschema\";\n\nconst env = parseEnv(config);\nconst pool = new Pool({ connectionString: env.postgres.databaseUrl, max: 5 });\nconst db = drizzle(pool);\n\nconst app = new Hono();\napp.get(\"\u002F\", (c) => c.text(\"Neon + Hono + Drizzle\"));\napp.post(\"\u002Ftodos\", async (c) => {\n  const { text } = await c.req.json\u003C{ text: string }>();\n  const [row] = await db.insert(todos).values({ text }).returning();\n  return c.json(row, 201);\n});\napp.get(\"\u002Ftodos\", async (c) => c.json(await db.select().from(todos)));\n\nexport default app;\n```\n\nCreate the `pg` pool at module scope (reused across requests on the same isolate) and keep `max` small (e.g. 5), since each isolate keeps its own pool.\n\n`parseEnv(config)` requires _every_ variable the config implies. A function that only talks to Postgres over the pooled URL can scope it to just that key — `parseEnv` then validates and returns only what you asked for (the keys autocomplete from your `neon.ts`):\n\n```typescript\nconst { postgres } = parseEnv(config, [\"DATABASE_URL\"]); \u002F\u002F not the unpooled URL, auth, etc.\nconst pool = new Pool({ connectionString: postgres.databaseUrl, max: 5 });\n```\n\n## Develop Locally and Deploy\n\n```bash\nneon dev      # serves every function in neon.ts with hot reload; injects DATABASE_URL & friends\nneon deploy   # bundles with esbuild, uploads, and applies neon.ts to the linked branch\n```\n\nTo deploy a single function without `neon.ts`: `neon functions deploy \u003Cslug> --src src\u002Findex.ts` (`--src` takes either the entry file or a directory containing `index.ts`, `index.mjs`, or `index.js`). Retrieve the public URL with `neon functions get \u003Cslug>` (the `invocation_url` field, of the form `https:\u002F\u002F\u003Cbranch_id>-\u003Cslug>.compute.c-1.us-east-2.aws.neon.tech`). Manage with `neon functions list|get|delete`.\n\nWhen `neon checkout` _creates_ a new branch and a `neon.ts` is present, it applies the policy automatically — deploying the function to the fresh branch. Checking out an existing branch does not re-deploy; run `neon deploy` explicitly.\n\n## Neon Infrastructure as Code (`neon.ts`)\n\nThe `preview.functions` block from [Setup](#setup) is part of `neon.ts`, Neon's infrastructure-as-code file — one TypeScript file declares every function (its `source`, display `name`, and `env`) alongside any other branch services, in version control (see the `neon` skill for the full reference). Treat it like Terraform for your branch:\n\n```bash\nneon config status   # print the branch's live config (deployed functions)\nneon config plan     # dry-run diff of what apply would change\nneon config apply    # bundle + deploy the declared functions  (neon deploy is an alias)\n```\n\nFunctions are **branch-scoped**: each branch runs its own deployment at its own URL. When a `neon.ts` is present, `neon checkout` applies the policy as it _creates_ a branch, so a fresh preview\u002FCI branch comes up with the function already deployed. Checking out an _existing_ branch doesn't redeploy — run `neon deploy` to apply changes.\n\nPer-branch deploy tuning (e.g. `runtime`) lives in the `branch` closure, keyed by slug, so it can vary by branch without changing which functions exist:\n\n```typescript\nexport default defineConfig({\n  preview: {\n    functions: { todos: { name: \"todo api\", source: \"src\u002Findex.ts\" } },\n  },\n  branch: (branch) => ({\n    preview: { functions: { todos: { runtime: \"nodejs24\" } } },\n  }),\n});\n```\n\n## Environment Variables\n\nNeon injects branch-scoped connection strings and service URLs at runtime — you don't declare these or pass them at deploy time:\n\n| Variable                | Notes                                                                                    |\n| ----------------------- | ---------------------------------------------------------------------------------------- |\n| `NEON_BRANCH`           | The branch **name** (e.g. `main`, `preview\u002Ffoo`). Injected on every branch, including the default. |\n| `DATABASE_URL`          | Pooled connection string. Use for most queries. Present only if the branch has Postgres. |\n| `DATABASE_URL_UNPOOLED` | Direct connection. Use for migrations, `LISTEN`\u002F`NOTIFY`, multi-round-trip transactions. |\n| `NEON_AUTH_BASE_URL`    | Present when Neon Auth is enabled on the branch.                                         |\n| `NEON_DATA_API_URL`     | Present when the Data API is enabled on the branch.                                      |\n\nObject storage (`AWS_*`) and AI Gateway (`NEON_AI_GATEWAY_*`) vars are also injected when those services are declared — see the `neon-object-storage` and `neon-ai-gateway` skills.\n\n`neon env pull` \u002F `neon-env run` \u002F `neon dev` emit `NEON_BRANCH` (and the connection strings) into your local dev environment too, so local runs mirror the deployed runtime.\n\n**Your own secrets** are per-deployment. Set them with `--env KEY=VALUE` on `neon functions deploy` (repeatable; `--env KEY=` deletes a key, unmentioned keys carry over), or declare them in `neon.ts` under the function's `env` (resolved at deploy time, so read from `process.env` to avoid hardcoding):\n\n```typescript\nfunctions: {\n  todos: {\n    name: \"todo api\",\n    source: \"src\u002Findex.ts\",\n    env: { RESEND_API_KEY: process.env.RESEND_API_KEY! },\n  },\n}\n```\n\nLoad a `.env` before deploy with `neon deploy --env .env.production`. Pull the branch's Neon-managed vars onto disk for local dev with `neon env pull` (`link`\u002F`checkout` do this automatically; pass `--no-env-pull` to skip and use `neon-env run -- \u003Ccmd>` for runtime injection). Limits: ≤1,000 vars, ≤64 KiB total, and the `NEON_` prefix is reserved.\n\n## Connecting to Postgres\n\nWhen the branch has Postgres, Neon **injects the connection strings at runtime** — you don't declare them, pass them at deploy time, or hardcode anything. The two you'll use:\n\n- `DATABASE_URL` — **pooled** connection string (routed through Neon's connection pooler). Use it for normal request\u002Fresponse query traffic. Kept un-prefixed because every Postgres ORM (Drizzle, Prisma, Knex, …) reads `DATABASE_URL` by default.\n- `DATABASE_URL_UNPOOLED` — **direct** connection string to the same database. Use it for migrations, `LISTEN`\u002F`NOTIFY`, and long multi-statement transactions.\n\n**Use Drizzle (or another ORM) on top of node-postgres (`pg`)** for queries and schema management — not Neon's serverless driver. Functions are long-running and reuse an isolate across many requests, so a persistent `pg` pool is the right fit; the serverless driver's HTTP transport is meant for fully isolated, lambda-style runtimes.\n\nCreate the connection pool **once at module scope** and reuse it across requests — don't open a connection per request:\n\n```typescript\nimport { drizzle } from \"drizzle-orm\u002Fnode-postgres\";\nimport { Pool } from \"pg\";\n\n\u002F\u002F Created once per isolate; reused by every request that isolate handles.\nconst pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });\nconst db = drizzle(pool);\n```\n\n**Pooling is recommended because an isolate is reused across many requests** (and several requests can be in flight on the same isolate at once — see [Timeouts and Runtime Limits](#timeouts-and-runtime-limits)). A module-scope pool is opened once on cold start and then shared by every subsequent request that isolate serves, so you amortize connection setup instead of paying it on every request and you avoid exhausting Postgres connections under load.\n\nKeep `max` small (e.g. `5`): each isolate keeps its own pool, so total connections to Postgres scale with the number of live isolates. You don't need to close the pool on shutdown — when the runtime evicts an isolate it sends `SIGINT`\u002F`SIGTERM`, and Neon's pooler reclaims those connections for you, so an explicit drain handler is redundant.\n\n> Reading `process.env.DATABASE_URL` directly works everywhere. The function in [Setup](#setup) instead uses `@neon\u002Fenv`'s `parseEnv(config)` to read the same value in a typed, validated way — either is fine.\n\n## Timeouts and Runtime Limits\n\nFunctions are long-running but **still serverless** — they are a request\u002Fresponse runtime, not a background job runner. The hard limits:\n\n- **Time to first byte: 15 minutes.** Your handler must _begin_ returning a response within 15 minutes of receiving a request. Most handlers finish in seconds; the 15-minute ceiling exists so agent workloads like image\u002Fvideo generation have room.\n- **Heartbeat: 15 minutes.** Open WebSocket\u002FSSE connections stay alive as long as data flows. The timeout only fires when a connection goes silent — send at least one byte every 15 minutes to keep a quiet stream alive.\n- **`waitUntil`: 15 minutes.** Work registered with `waitUntil` keeps the invocation alive after the response is sent, up to 15 minutes — for cleanup like analytics writes and audit logs, **not** a background job runner. (`waitUntil` from `@neon\u002Ffunctions` is currently a stub during the preview.)\n- **Idle eviction.** With no active connections Neon shuts the function down; it may also evict\u002Frestart for operational reasons — e.g. maintenance, or moving the function to a different compute node (active functions can run for hours first). Treat eviction like a process restart — WebSocket\u002FSSE clients must reconnect. Neon sends `SIGINT` before evicting, so a `process.on(\"SIGINT\", ...)` handler lets you detect that the function is about to be evicted and run any last-minute cleanup. You don't need one just to close Postgres connections — Neon's pooler reclaims those on its own.\n- **Runtime:** Node.js 24, memory fixed at 2048 MiB during the preview. Slugs must match `^[a-z0-9]{1,20}$`. **An isolate is reused across many requests** — multiple requests can be in flight on the same isolate at once (interleaved on Node's single-threaded event loop), and under load the runtime runs several isolates in parallel, each with its own copy of module state. State held in module scope is therefore per-isolate (shared by every request that isolate handles) and in-memory only — persist anything that must survive eviction in Postgres. This reuse is exactly why you create a connection pool once at module scope rather than per request (see [Connecting to Postgres](#connecting-to-postgres)).\n\n## Functions as an Agent Backend (Next.js and Similar Frameworks)\n\nA Neon Function is a great home for an AI agent precisely because it **doesn't time out** the way lambda-style serverless does (15-minute budget, see [Timeouts and Runtime Limits](#timeouts-and-runtime-limits)). But that advantage disappears the moment you **proxy the agent stream through your web app's backend** — a Next.js route handler, Remix\u002FSvelteKit\u002FNuxt action, etc. hosted on Vercel, Netlify, Cloudflare, and the like. Those platforms cap serverless\u002Fedge execution at short windows (often ~10–60s, sometimes up to ~300s), so a long agent or image\u002Fvideo generation stream gets cut off mid-response even though the Neon Function would happily keep going.\n\n**Building the agent itself.** The [Vercel AI SDK](https:\u002F\u002Fai-sdk.dev) and [Mastra](https:\u002F\u002Fmastra.ai) are the recommended ways to build the agent — point either at the Neon AI Gateway (see the `neon-ai-gateway` skill) for one credential across every model, with no extra provider keys. For a complete AI SDK agent running as a Function (streaming `toUIMessageStreamResponse`, multi-step tool calling next to Postgres, and persisting generated images to Object Storage), see [references\u002Fai-sdk.md](https:\u002F\u002Fneon.com\u002Fdocs\u002Fai\u002Fskills\u002Fneon-functions\u002Freferences\u002Fai-sdk.md); for the Mastra equivalent with built-in tracing, see [references\u002Fmastra-studio.md](https:\u002F\u002Fneon.com\u002Fdocs\u002Fai\u002Fskills\u002Fneon-functions\u002Freferences\u002Fmastra-studio.md).\n\n**The fix: call the function directly from the client.** Don't route the long request through your app server.\n\n```\nBrowser ──(Authorization: Bearer \u003CJWT>)──▶  Neon Function (agent)   ✅ no host timeout\nBrowser ──▶ your app backend ──▶ Neon Function                       ❌ host cuts the stream\n```\n\n- Mint a **short-lived JWT** on your app backend (e.g. better-auth's `jwt` plugin, NextAuth, or your own signer) — that call is fast and well within host limits.\n- Hand the token to the client and have it call the Neon Function **directly** (cross-origin), e.g. with the Vercel AI SDK: `new DefaultChatTransport({ api: NEON_FUNCTION_URL, fetch })` where `fetch` attaches `Authorization: Bearer \u003Ctoken>`. Your app server is never in the path of the long stream.\n- Add **CORS** so the browser can reach it (handle `OPTIONS`, set `Access-Control-Allow-Origin`\u002F`-Headers`).\n\n> [!WARNING]\n> A Neon Function has a **public HTTPS URL — it is reachable by anyone.** A direct client→function call means there is no app backend in front of it to gate access, so **you must authenticate the function yourself.** Verify a JWT (e.g. against your app's JWKS), check a shared secret \u002F API key, or validate a session token at the top of the handler and reject anything else. Never deploy an unauthenticated agent.\n\n```typescript\n\u002F\u002F src\u002Findex.ts — verify the caller before doing any work\nimport { createRemoteJWKSet, jwtVerify } from \"jose\";\n\nconst jwks = createRemoteJWKSet(new URL(`${process.env.AUTH_BASE_URL}\u002Fapi\u002Fauth\u002Fjwks`));\n\nexport default {\n  async fetch(request: Request) {\n    if (request.method === \"OPTIONS\") return new Response(null, { status: 204, headers: cors(request) });\n\n    const auth = request.headers.get(\"authorization\");\n    if (!auth?.toLowerCase().startsWith(\"bearer \")) {\n      return new Response(\"Unauthorized\", { status: 401, headers: cors(request) });\n    }\n    try {\n      const { payload } = await jwtVerify(auth.slice(7), jwks, {\n        issuer: process.env.AUTH_BASE_URL,\n        audience: process.env.AUTH_BASE_URL,\n      });\n      const userId = payload.sub; \u002F\u002F scope the agent to this user\n      \u002F\u002F ... run the agent, return result.toUIMessageStreamResponse({ headers: cors(request) })\n    } catch {\n      return new Response(\"Unauthorized\", { status: 401, headers: cors(request) });\n    }\n  },\n};\n```\n\nPass the JWKS\u002Fissuer URL to the function via its `env` (see [Environment Variables](#environment-variables)). Persist anything you need to keep (generated images, history) in Postgres — module state doesn't survive eviction.\n\n## WebSocket Servers\n\nA WebSocket server is the canonical Functions workload: a long-running handler holds connections open in-process, with no external state store needed to keep a stream coherent. The connection stays alive as long as bytes flow (15-minute heartbeat, see [Timeouts](#timeouts-and-runtime-limits)).\n\n**Upgrade from inside `fetch`.** Call `upgradeWebSocket(request)` from [`@neon\u002Ffunctions`](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@neon\u002Ffunctions) and return the response it gives you. There is one entrypoint and no WebSocket dependency to install:\n\n```typescript\nimport { upgradeWebSocket } from \"@neon\u002Ffunctions\";\n\nexport default {\n  async fetch(req: Request): Promise\u003CResponse> {\n    if (req.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\") {\n      return new Response(\"expected a websocket upgrade\", { status: 426 });\n    }\n\n    const { socket, response } = upgradeWebSocket(req);\n    socket.addEventListener(\"message\", (event) => socket.send(event.data));\n    return response;\n  },\n};\n```\n\n`socket` is a standard [`WebSocket`](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FAPI\u002FWebSocket), so `addEventListener` and the `onopen`\u002F`onmessage`\u002F`onclose`\u002F`onerror` properties both work. It is still `CONNECTING` when you get it — the runtime writes the `101` only once your handler returns `response`, and the socket opens then.\n\nThree rules that matter:\n\n- **Return `response` unchanged.** A `101` can't be built as a plain `Response` (the fetch spec caps constructed responses at 200–599), so the runtime hands back an object carrying the pending upgrade. `clone()`, or rebuilding it with `new Response(res.body, res)` as response-rewriting middleware does, discards the upgrade and fails the request.\n- **Refuse a handshake by returning an ordinary `Response`.** A `401`, `403` or `404` is relayed to the client as-is. That is how you gate a socket.\n- **`binaryType` defaults to `\"arraybuffer\"`**, not the browser's `\"blob\"`. `event.data` is a `string` for text frames and an `ArrayBuffer` for binary ones, so branch on `typeof`.\n\n**With auth.** Browsers can't set headers on a WebSocket, so authenticate with a `?token=` query param (verify it the same way as the [agent backend](#functions-as-an-agent-backend-nextjs-and-similar-frameworks): `jwtVerify` against your JWKS) and refuse before upgrading:\n\n```typescript\n\u002F\u002F src\u002Findex.ts\nimport { upgradeWebSocket } from \"@neon\u002Ffunctions\";\n\nconst clients = new Set\u003CWebSocket>();\n\nexport default {\n  async fetch(request: Request): Promise\u003CResponse> {\n    if (request.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\") {\n      return new Response(\"WebSocket endpoint — connect with ?token=\u003Cjwt>\");\n    }\n\n    const url = new URL(request.url);\n    const identity = await verifyToken(url.searchParams.get(\"token\"));\n    if (!identity) return new Response(\"unauthorized\", { status: 401 });\n\n    const { socket, response } = upgradeWebSocket(request);\n    clients.add(socket);\n    socket.addEventListener(\"close\", () => clients.delete(socket));\n    socket.addEventListener(\"message\", (event) => {\n      if (typeof event.data !== \"string\") return;\n      persist(identity.id, event.data); \u002F\u002F fan out to every isolate — see below\n    });\n    return response;\n  },\n};\n```\n\n**Subprotocols.** Pass `{ protocol }` to select one the client offered; it is echoed in `Sec-WebSocket-Protocol` and exposed as `socket.protocol`. Selecting one the client did not offer throws a `TypeError`. Omit it and no protocol is negotiated. No extensions are negotiated either — `socket.extensions` is always `\"\"` and `permessage-deflate` is not available.\n\n**Hono.** Nothing special is needed: `upgradeWebSocket` takes a `Request`, so call it inside a route with `c.req.raw` and return the response. Auth and everything else is ordinary middleware.\n\n```typescript\n\u002F\u002F src\u002Findex.ts\nimport { Hono } from \"hono\";\nimport { upgradeWebSocket } from \"@neon\u002Ffunctions\";\n\nconst app = new Hono();\n\napp.get(\"\u002F\", (c) => c.text(\"ok\"));\n\napp.get(\"\u002Fws\", async (c) => {\n  const identity = await verifyToken(c.req.query(\"token\"));\n  if (!identity) return c.text(\"Unauthorized\", 401);\n\n  const { socket, response } = upgradeWebSocket(c.req.raw);\n  socket.addEventListener(\"open\", () => socket.send(\"welcome\"));\n  socket.addEventListener(\"message\", (event) => socket.send(`echo: ${event.data}`));\n  return response;\n});\n\nexport default { fetch: (request: Request) => app.fetch(request) };\n```\n\n### Heartbeat (keep the socket alive)\n\nA connection stays open **only while bytes flow**: Neon evicts a silent stream after 15 minutes ([Timeouts and Runtime Limits](#timeouts-and-runtime-limits)), and intermediary proxies \u002F load balancers are usually far stricter (often tens of seconds). Don't rely on the app being chatty enough — send a periodic keepalive from the server so the socket never goes quiet.\n\nThe standard `WebSocket` interface has no `ping()`, so send an application-level message the client ignores:\n\n```typescript\nconst HEARTBEAT_MS = 25_000; \u002F\u002F comfortably under proxy idle timeouts\n\nconst beat = setInterval(() => {\n  for (const socket of clients) {\n    if (socket.readyState === socket.OPEN) socket.send('{\"type\":\"ping\"}');\n  }\n}, HEARTBEAT_MS);\nbeat.unref?.();\n```\n\nThe client should skip these when handling messages. The server does answer a client-sent ping frame with a pong automatically, so a browser client can drive the heartbeat instead if you'd rather not filter messages.\n\n### Keeping clients in sync across isolates (do not skip this)\n\nUnder load the runtime runs **several isolates in parallel, each with its own copy of module state** — so each isolate has its own `clients` set. Broadcasting only to that local set means a client on isolate A never sees an event produced on isolate B, and the feed silently fractures. It's easy to miss: `neon dev` runs a single process (one isolate), so in-process broadcast always _looks_ fine locally but breaks in production, where concurrent connections spread across many isolates.\n\nModule state doesn't survive eviction anyway, so **Postgres is the shared source of truth**. Pick a fan-out strategy. In every snippet below, `pool` is a pooled `pg` client and `clients` is this isolate's `Set` of live connections.\n\n**1. Poll Postgres — the default, and the only option that keeps Scale to Zero.** Each isolate re-reads the shared state (or rows past a cursor) on a short interval and pushes changes to its own clients. One query per isolate per tick (not per client), and none when the isolate has no clients — so an idle compute still suspends.\n\n```typescript\nlet lastId = 0;\nconst poller = setInterval(async () => {\n  if (clients.size === 0) return; \u002F\u002F no clients here → no query → compute can scale to zero\n  const { rows } = await pool.query(\n    \"SELECT id, payload FROM events WHERE id > $1 ORDER BY id\",\n    [lastId],\n  );\n  for (const { id, payload } of rows) {\n    lastId = id;\n    for (const socket of clients) {\n      if (socket.readyState === socket.OPEN) socket.send(payload);\n    }\n  }\n}, 1000);\npoller.unref?.();\n```\n\n- **Latency:** up to the interval (~1s) — fine for counters, chat, and dashboards.\n- **Scaling:** database load grows with the number of live isolates, not clients. Keep the cursor on an indexed `serial`\u002F`bigserial` PK and the interval sane.\n- **Scale to Zero:** ✅ preserved — polling stops when no clients are connected, so the compute suspends on its normal timer.\n\n**2. `LISTEN`\u002F`NOTIFY` — lowest latency, but requires disabling Scale to Zero.** Each isolate `LISTEN`s on a channel over a dedicated **unpooled** connection; broadcasting is `NOTIFY`, so every isolate (including the sender's) re-pushes to its sockets. Near-instant — but the listener holds an idle connection that **does not count as active**, so [Scale to Zero](https:\u002F\u002Fneon.com\u002Fdocs\u002Fintroduction\u002Fscale-to-zero) suspends the compute and drops it, silently killing the feed. Only use it on an **always-on** compute (Scale to Zero disabled — a paid-plan setting).\n\n```typescript\nimport { Pool, Client } from \"pg\";\n\nconst pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });\nconst CHANNEL = \"chat_events\";\n\n\u002F\u002F One dedicated DIRECT connection per isolate, just to receive events.\n\u002F\u002F Use DATABASE_URL_UNPOOLED — LISTEN needs a real session, not a pooled one.\nconst listener = new Client({ connectionString: process.env.DATABASE_URL_UNPOOLED });\nlistener.connect().then(() => listener.query(`LISTEN ${CHANNEL}`));\nlistener.on(\"notification\", (msg) => {\n  if (!msg.payload) return;\n  for (const socket of clients) {\n    if (socket.readyState === socket.OPEN) socket.send(msg.payload);\n  }\n});\n\n\u002F\u002F Broadcast by NOTIFYing through the pool — every isolate's listener fires.\nfunction broadcast(event: unknown) {\n  return pool.query(\"SELECT pg_notify($1, $2)\", [CHANNEL, JSON.stringify(event)]);\n}\n```\n\n**3. External pub\u002Fsub (e.g. [Upstash](https:\u002F\u002Fupstash.com) Redis) — best at scale.** For high fan-out, sub-second latency at large connection counts, or multi-region, publish\u002Fsubscribe through a dedicated broker. Highest throughput, and it doesn't touch Postgres or block Scale to Zero — at the cost of another service to run.\n\n**Rule of thumb:** start with **polling** (works with Scale to Zero, no extra infra); switch to `LISTEN`\u002F`NOTIFY` only on always-on compute that needs sub-second latency; move to Redis when fan-out outgrows Postgres.\n\n### Client must reconnect\n\nIdle functions are evicted (and isolates restart for operational reasons), so a client's socket **will** drop — treat reconnection as normal, not exceptional. Reconnect with exponential backoff, capped, and **re-mint a fresh token on every attempt** (tokens are short-lived, so a stale one fails the `upgrade` auth check):\n\n```typescript\nlet closed = false, retry = 0, timer: ReturnType\u003Ctypeof setTimeout>;\n\nasync function connect() {\n  if (closed) return;\n  const token = await getToken(); \u002F\u002F re-mint each attempt; short-lived\n  const ws = new WebSocket(`${WS_URL}?token=${encodeURIComponent(token)}`);\n  ws.onopen = () => { retry = 0; };          \u002F\u002F reset backoff on success\n  ws.onmessage = (e) => { \u002F* apply the event *\u002F };\n  ws.onclose = () => {\n    if (!closed) timer = setTimeout(connect, Math.min(1000 * 2 ** retry++, 15000));\n  };\n  ws.onerror = () => ws.close();             \u002F\u002F let onclose drive the retry\n}\nconnect();\n```\n\nTogether — `upgradeWebSocket` inside `fetch`, JWT auth over `?token=`, cross-isolate fan-out, and client backoff — these compose into a complete realtime chat backend on a single function.\n\n## Server-Sent Events (SSE)\n\nWhen you only need **server → client** streaming (live counters, notifications, progress, token streams), SSE is simpler than a WebSocket and needs no upgrade at all: a plain `fetch` handler returns a `Response` whose body is a `ReadableStream` with `Content-Type: text\u002Fevent-stream`, and the runtime holds it open as long as bytes flow. The browser consumes it with `EventSource`, which **reconnects on its own** — so there's no client backoff to write.\n\n```typescript\n\u002F\u002F src\u002Findex.ts — minimal SSE endpoint\nconst encoder = new TextEncoder();\nexport default {\n  fetch: () =>\n    new Response(\n      new ReadableStream\u003CUint8Array>({\n        start(controller) {\n          controller.enqueue(encoder.encode(\"data: hello\\n\\n\"));\n          const t = setInterval(() => controller.enqueue(encoder.encode(\": ping\\n\\n\")), 25_000);\n          return () => clearInterval(t); \u002F\u002F fires when the client disconnects\n        },\n      }),\n      { headers: { \"Content-Type\": \"text\u002Fevent-stream\", \"Cache-Control\": \"no-cache, no-transform\" } },\n    ),\n};\n```\n\nThe same rules as WebSockets apply. **Heartbeat:** a stream stays open only while bytes flow — Neon's window is 15 minutes ([Timeouts and Runtime Limits](#timeouts-and-runtime-limits)) but proxies are usually far stricter, so emit a `: ping\\n\\n` comment every ~25–30s (shown above) to keep idle streams from being dropped. Keep state in Postgres, and fan out across isolates using one of the [sync strategies](#keeping-clients-in-sync-across-isolates-do-not-skip-this) (hold a `Set` of stream controllers and `enqueue` to each). `EventSource` is GET-only and can't set headers, so authenticate with a `?token=` query param or cookie, exactly like the WebSocket case. [references\u002Fsse.md](https:\u002F\u002Fneon.com\u002Fdocs\u002Fai\u002Fskills\u002Fneon-functions\u002Freferences\u002Fsse.md) has the full pattern — Hono variant, cross-isolate fan-out, wire format, client, and caveats.\n\n## MCP Servers\n\nAn [MCP](https:\u002F\u002Fmodelcontextprotocol.io) server is a natural Functions workload: a long-running HTTP handler that exposes tools to AI clients (Cursor, Claude, ChatGPT, agents), with those tools reading and writing the branch's Postgres right next to the compute. MCP's **streamable HTTP transport** is a plain `POST`\u002F`GET` on a single endpoint (conventionally `\u002Fmcp`), so it maps onto a function's `fetch` handler with no `upgrade` method or extra protocol.\n\nThe simplest host is a Hono app using the official [`@modelcontextprotocol\u002Fsdk`](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Ftypescript-sdk) plus [`@hono\u002Fmcp`](https:\u002F\u002Fgithub.com\u002Fhonojs\u002Fmiddleware\u002Ftree\u002Fmain\u002Fpackages\u002Fmcp), which bridges the transport to a route. Build the server, register its tools, and create the transport once at module scope, then hand every `\u002Fmcp` request to it:\n\n```typescript\nconst transport = new StreamableHTTPTransport();\napp.all(\"\u002Fmcp\", async (c) => {\n  if (!mcpServer.isConnected()) await mcpServer.connect(transport);\n  return transport.handleRequest(c);\n});\n```\n\nBecause the function's URL is public, **authenticate before connecting the transport** — [Better Auth](https:\u002F\u002Fbetter-auth.com) covers both OAuth (its MCP plugin makes your app the authorization server so third-party clients self-authorize per the MCP spec) and a simpler API-key \u002F session-JWT check for your own callers. [references\u002Fmcp.md](https:\u002F\u002Fneon.com\u002Fdocs\u002Fai\u002Fskills\u002Fneon-functions\u002Freferences\u002Fmcp.md) has the full pattern — server with Postgres-backed tools via Drizzle, both Better Auth auth options, and testing with `mcporter` \u002F `add-mcp`.\n\n## Integrations and Observability\n\n### Built-in branch logs\n\n```bash\nneon logs query --branch production --source function --since 1h\n```\n\nFunctions is one of the two sources branch logs cover today, alongside Object Storage. Logs are scoped to a single branch, so pass `--branch` when the deployed function isn't on the branch you're checked out on. Everything else about logs — the required CLI version, filters, the SDK, and the Loki-compatible read API — is in the parent `neon` skill's **Observability** section.\n\n### Application instrumentation\n\nA function is a long-lived Node.js process running a web-standard request\u002Fresponse handler, so standard Node integration SDKs work unchanged. Initialize them once at module load, gated on an env var so local dev and unconfigured branches stay a no-op, and pass secrets via `--env` or `neon.ts` `env`.\n\n- **Sentry** — error monitoring across the HTTP framework, the function runtime, and an agent's own caught\u002Ffallback failures (the long-running case Functions target): see [references\u002Fsentry.md](https:\u002F\u002Fneon.com\u002Fdocs\u002Fai\u002Fskills\u002Fneon-functions\u002Freferences\u002Fsentry.md).\n- **Mastra Studio (Mastra Cloud)** — run a Mastra agent on a function and ship its traces to a Studio project for observability: see [references\u002Fmastra-studio.md](https:\u002F\u002Fneon.com\u002Fdocs\u002Fai\u002Fskills\u002Fneon-functions\u002Freferences\u002Fmastra-studio.md).\n\n## Neon Documentation\n\nThe Neon documentation is the source of truth and Functions is evolving rapidly, so always verify against the official docs. Any doc page can be fetched as markdown by appending `.md` to the URL or by requesting `Accept: text\u002Fmarkdown`. Find the right page from the docs index (https:\u002F\u002Fneon.com\u002Fdocs\u002Fllms.txt) and the changelog announcements.\n\n## Further Reading\n\n- https:\u002F\u002Fneon.com\u002Fdocs\u002Fcompute\u002Ffunctions\u002Foverview.md\n- https:\u002F\u002Fneon.com\u002Fdocs\u002Fcompute\u002Ffunctions\u002Fget-started.md\n- https:\u002F\u002Fneon.com\u002Fdocs\u002Fcompute\u002Ffunctions\u002Fdeploy.md\n- https:\u002F\u002Fneon.com\u002Fdocs\u002Fcompute\u002Ffunctions\u002Fenvironment-variables.md\n- https:\u002F\u002Fneon.com\u002Fdocs\u002Fcompute\u002Ffunctions\u002Freference\u002Fneon-ts.md\n- https:\u002F\u002Fneon.com\u002Fdocs\u002Fcompute\u002Ffunctions\u002Freference\u002Fruntime-limits.md\n- https:\u002F\u002Fneon.com\u002Fdocs\u002Fcompute\u002Ffunctions\u002Fpreview-access.md\n",{"metadata":24,"description":7},{"parent":25,"source":26},"neon","https:\u002F\u002Fgithub.com\u002Fneondatabase\u002Fagent-skills\u002Ftree\u002Fmain\u002Fskills\u002Fneon-functions","main","58843b159d7a4050d6b785a98b908cce505c0b92","agent\u002Fskills\u002Fneon-functions",0,"https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent","https:\u002F\u002Fgithub.com\u002FReihantt6","reihsns.web.id","2026-08-19 20:08:18",{"source":8,"skillName":5,"commands":36,"prompt":46,"zipAvailable":47},[37,40,43],{"tool":38,"command":39},"npx","npx skills add Reihantt6\u002Fsns-myagent --skill neon-functions",{"tool":41,"command":42},"bunx","bunx skills add Reihantt6\u002Fsns-myagent --skill neon-functions",{"tool":44,"command":45},"pnpm","pnpm dlx skills add Reihantt6\u002Fsns-myagent --skill neon-functions","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fneon-functions\u002FSKILL.md",true,[49,55,59,63,67],{"path":50,"resourceType":51,"resourceTypeDesc":52,"sizeBytes":53,"sourceHtmlUrl":54},"references\u002Fai-sdk.md","REFERENCE","参考文档",6669,"https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fneon-functions\u002Freferences\u002Fai-sdk.md",{"path":56,"resourceType":51,"resourceTypeDesc":52,"sizeBytes":57,"sourceHtmlUrl":58},"references\u002Fmastra-studio.md",6365,"https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fneon-functions\u002Freferences\u002Fmastra-studio.md",{"path":60,"resourceType":51,"resourceTypeDesc":52,"sizeBytes":61,"sourceHtmlUrl":62},"references\u002Fmcp.md",9068,"https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fneon-functions\u002Freferences\u002Fmcp.md",{"path":64,"resourceType":51,"resourceTypeDesc":52,"sizeBytes":65,"sourceHtmlUrl":66},"references\u002Fsentry.md",14368,"https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fneon-functions\u002Freferences\u002Fsentry.md",{"path":68,"resourceType":51,"resourceTypeDesc":52,"sizeBytes":69,"sourceHtmlUrl":70},"references\u002Fsse.md",7879,"https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fneon-functions\u002Freferences\u002Fsse.md",[72,79,86,93,100,107],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":19},"01M77XDCYZ407XYMF2T4P6F7VT","youtube-transcript","Extract transcripts from YouTube videos. Use when the user asks for a transcript, subtitles, or captions of a YouTube video and provides a YouTube URL (youtube.com\u002Fwatch?v=, youtu.be\u002F, or similar). Supports output with or without timestamps.","https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fyoutube-transcript\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":19},"01M77XD7PBC98J6MXGJJ2TJ8DX","youtube-thumbnail-design","YouTube thumbnail design with specific dimensions, contrast rules, and mobile preview optimization. Covers safe zones, text placement, face expression psychology, and A\u002FB testing. Use for: YouTube thumbnails, video cover images, click-through optimization. Triggers: youtube thumbnail, thumbnail design, video thumbnail, click through rate, ctr optimization, youtube cover, video cover image, thumbnail maker, thumbnail tips, youtube design, video preview image","https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fyoutube-thumbnail-design\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M77XD2541C8HXJ6RHYZP4NGJ","youtube-short-maker","Make YouTube Shorts that hold attention with Pexo — vertical 9:16, fast-paced, hook in the first 3 seconds. Describe your topic and Pexo writes the script, generates the shots, picks the models, and assembles a finished Short with music and captions. Use for YouTube Shorts: \"youtube short\", \"make a youtube short\", \"shorts video\", \"short-form video\". NOT for long-form or landscape video.","https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fyoutube-short-maker\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M77XCXKVSYK7KTZ3PQBVVGFD","xcode-project-setup","Safely modifies Xcode projects (.pbxproj) to add Swift Packages and link files. Use this skill whenever an iOS project needs dependencies installed (e.g. Firebase, Alamofire).","https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fxcode-project-setup\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":19},"01M77XCR1DV8ZQK2NHWKVY4EWX","x402","Set up Browser Use Cloud payments with x402 — pay per request from a crypto wallet (USDC on Base mainnet), no signup or API key. Two setups it works out up front — \"just use it\" (set up a wallet so you or Claude Code can run cloud browser tasks paid from the wallet — Claude writes and runs throwaway scripts, nothing touches your codebase) or \"build it in\" (install the SDK and write the key + code into your project). Walks through wallet setup, funding, .env, and a ~$1 test run. Use when the user asks about x402, pay-per-use, USDC payments, or wants Browser Use Cloud without an API key. For the free-tier signup (reverse-CAPTCHA → API key), use `browser-use cloud signup` or the `cloud` skill instead.","https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fx402\u002FSKILL.md",[],[],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":19},"01M77XCMD3R3ZBZQQSW6E0793B","x-twitter-scraper","Build GitHub Copilot workflows with Xquik X API SDKs, REST endpoints, hosted Apify Actor runs, MCP tools, TweetClaw OpenClaw plugin installs, signed webhooks, tweet search, user lookup, follower exports, media actions, and agent automation.","https:\u002F\u002Fgithub.com\u002FReihantt6\u002Fsns-myagent\u002Fblob\u002Fmain\u002Fagent\u002Fskills\u002Fx-twitter-scraper\u002FSKILL.md",[],[]]