@neon/skills 1.1.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -1
- package/package.json +2 -2
- package/plugin.json +1 -1
- package/skills/neon/SKILL.md +206 -212
- package/skills/neon/references/auth.md +12 -0
- package/skills/neon/references/claimable-neon.md +10 -14
- package/skills/neon/references/function-triggers.md +53 -0
- package/skills/neon/references/logs-loki.md +61 -0
- package/skills/neon/references/parse-env.md +32 -0
- package/skills/neon/references/sdk.md +7 -0
- package/skills/neon-ai-gateway/SKILL.md +13 -15
- package/skills/neon-auth/SKILL.md +155 -0
- package/skills/neon-auth/references/managed-auth.md +173 -0
- package/skills/neon-auth/references/self-managed.md +25 -0
- package/skills/neon-functions/SKILL.md +146 -81
- package/skills/neon-functions/references/ai-sdk.md +4 -6
- package/skills/neon-functions/references/function-triggers.md +247 -0
- package/skills/neon-functions/references/mastra-studio.md +3 -3
- package/skills/neon-functions/references/mcp.md +1 -1
- package/skills/neon-functions/references/sse.md +8 -5
- package/skills/neon-object-storage/SKILL.md +10 -11
- package/skills/neon-postgres/SKILL.md +119 -17
- package/skills/neon-postgres/references/full-text-search.md +99 -0
- package/skills/neon-postgres/references/hybrid-search.md +90 -0
- package/skills/neon-postgres/references/vector-search.md +137 -0
- package/skills/neon-postgres-branches/SKILL.md +1 -1
- package/skills/neon-postgres-egress-optimizer/SKILL.md +1 -1
|
@@ -7,11 +7,14 @@ description: >-
|
|
|
7
7
|
streaming responses, a WebSocket or server-sent-events (SSE) server, a
|
|
8
8
|
webhook handler, a Discord bot, an MCP server, or any request/response
|
|
9
9
|
workload that risks timing out on short, lambda-style serverless functions —
|
|
10
|
-
and wants it to branch with their database.
|
|
11
|
-
|
|
12
|
-
"
|
|
13
|
-
"
|
|
14
|
-
"
|
|
10
|
+
and wants it to branch with their database. Also use for Function Triggers:
|
|
11
|
+
a cron or an object-storage event that POSTs to a function. Triggers include
|
|
12
|
+
"serverless function", "deploy an API", "long-running function",
|
|
13
|
+
"streaming agent", "SSE server", "WebSocket server", "webhook handler",
|
|
14
|
+
"MCP server", "cron", "function trigger", "scheduled function", "cron job",
|
|
15
|
+
"object storage trigger", "on upload", "run code next to my database",
|
|
16
|
+
"function that won't time out", "function logs", "Neon Functions", and
|
|
17
|
+
"Neon Compute".
|
|
15
18
|
metadata:
|
|
16
19
|
parent: neon
|
|
17
20
|
source: https://github.com/neondatabase/agent-skills/tree/main/skills/neon-functions
|
|
@@ -22,12 +25,12 @@ metadata:
|
|
|
22
25
|
If the `neon` skill is not installed, fetch it from https://neon.com/docs/ai/skills/neon/SKILL.md or install it with:
|
|
23
26
|
|
|
24
27
|
```bash
|
|
25
|
-
|
|
28
|
+
neon skills -s neon -y
|
|
26
29
|
```
|
|
27
30
|
|
|
28
31
|
# Neon Functions
|
|
29
32
|
|
|
30
|
-
|
|
33
|
+
Currently available in `aws-us-east-2`, `aws-us-east-1`, `aws-eu-central-1`, and `aws-ap-southeast-1`.
|
|
31
34
|
|
|
32
35
|
Neon 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.
|
|
33
36
|
|
|
@@ -41,9 +44,11 @@ Reach for Neon Functions when the workload is a request/response handler that be
|
|
|
41
44
|
- **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.
|
|
42
45
|
- **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.
|
|
43
46
|
- **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.
|
|
47
|
+
- **Query Postgres from the Function (or an existing framework handler).** Prefer that over the Data API. Use the Data API when the application already uses PostgREST or Supabase-js database calls, or is migrating that client.
|
|
44
48
|
- **Webhooks, bots, and post-response work.** Webhook handlers that fan out into multiple DB writes, Discord/WebSocket bots, and fire-and-forget follow-ups via `waitUntil` (analytics, audit logs) all fit.
|
|
49
|
+
- **Recurring HTTP work.** A Function Trigger POSTs to the function on a cron (`type: "schedule"`). Same `fetch` handler, same 15-minute time-to-first-byte limit. See [Function Triggers](#function-triggers).
|
|
45
50
|
|
|
46
|
-
If the workload is a pure static site,
|
|
51
|
+
If the workload is a pure static site, or something that must run outside the supported regions (`aws-us-east-2`, `aws-us-east-1`, `aws-eu-central-1`, and `aws-ap-southeast-1`) today, this isn't the right tool yet (see [Timeouts and Runtime Limits](#timeouts-and-runtime-limits) and [Availability](#availability)).
|
|
47
52
|
|
|
48
53
|
## What It Does
|
|
49
54
|
|
|
@@ -52,36 +57,37 @@ If the workload is a pure static site, a cron/background job that needs its own
|
|
|
52
57
|
- **Close to your database** — Runs in the branch's region; `DATABASE_URL` injected automatically when the branch has Postgres.
|
|
53
58
|
- **Branchable** — Each branch runs its own function version at its own URL against its own isolated state.
|
|
54
59
|
- **Same CLI/API** — Deploy and manage via `neon`, `neon.ts`, or the Neon API.
|
|
60
|
+
- **Function Triggers** — Neon POSTs to the function on a cron. See [Function Triggers](#function-triggers).
|
|
55
61
|
|
|
56
62
|
## Availability
|
|
57
63
|
|
|
58
|
-
Check this precondition before setting anything up: Neon Functions is
|
|
64
|
+
Check this precondition before setting anything up: Neon Functions is currently available in `aws-us-east-2`, `aws-us-east-1`, `aws-eu-central-1`, and `aws-ap-southeast-1`. Confirm the user's Neon project is in one of these regions.
|
|
59
65
|
|
|
60
66
|
## Architecture: Where Functions Fit
|
|
61
67
|
|
|
62
68
|
Neon (Functions included) is **backend primitives, not full-stack app hosting**. Host your app on **Vercel** (or Netlify, or another frontend/app 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:
|
|
63
69
|
|
|
64
|
-
- **Add a Function to a full-stack app.** Your Next.js / TanStack Start app on Vercel (or Netlify) owns UI, auth (
|
|
70
|
+
- **Add a Function to a full-stack app.** Your Next.js / TanStack Start app on Vercel (or Netlify) owns UI, auth (Managed Auth, Better Auth, Clerk, or another IdP), 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.)
|
|
65
71
|
- **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/response agents, host **MCP servers**, and run anything stateful or that belongs close to Postgres and Object Storage.
|
|
66
72
|
|
|
67
73
|
Either 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.
|
|
68
74
|
|
|
75
|
+
Prefer a Function, or an existing framework handler, that queries Postgres. Use Data API when the application already uses PostgREST/Supabase-js database calls or is migrating that client.
|
|
76
|
+
|
|
69
77
|
## Setup
|
|
70
78
|
|
|
71
|
-
Functions are declared in `neon.ts` (see the `neon` skill for the branch-first workflow and `neon.ts` basics). Add `@neon/config` and declare functions under `
|
|
79
|
+
Functions are declared in `neon.ts` (see the `neon` skill for the branch-first workflow and `neon.ts` basics). Add `@neon/config` and declare functions under `functions`, keyed by **slug**:
|
|
72
80
|
|
|
73
81
|
```typescript
|
|
74
82
|
// neon.ts
|
|
75
83
|
import { defineConfig } from "@neon/config/v1";
|
|
76
84
|
|
|
77
85
|
export default defineConfig({
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
source: "src/index.ts", // entry file, relative to neon.ts
|
|
84
|
-
},
|
|
86
|
+
functions: {
|
|
87
|
+
todos: {
|
|
88
|
+
// slug: ^[a-z0-9]{1,20}$ — lowercase letters/digits, no hyphens
|
|
89
|
+
name: "todo api", // display label only
|
|
90
|
+
source: "src/index.ts", // entry file, relative to neon.ts
|
|
85
91
|
},
|
|
86
92
|
},
|
|
87
93
|
});
|
|
@@ -132,34 +138,34 @@ attachDatabasePool(pool);
|
|
|
132
138
|
|
|
133
139
|
```bash
|
|
134
140
|
neon dev # serves every function in neon.ts with hot reload; injects DATABASE_URL & friends
|
|
135
|
-
neon deploy #
|
|
141
|
+
neon deploy --env <file> # preferred full deploy from neon.ts; --env is the file Function env is read from
|
|
136
142
|
```
|
|
137
143
|
|
|
138
|
-
|
|
144
|
+
Keep `.env` or `.env.local` up to date with every key under `functions.*.env`. `neon env pull` writes Neon-managed vars only; add Function secrets to that file, then pass it as `--env`. `neon deploy --env <file>` loads that file into `process.env` each time, then uploads those values. A missing value is `undefined` and `defineConfig` throws. Omit the key from `neon.ts` if you do not want to write it. Never coerce a missing `process.env` value to an empty string (that uploads `""` and deletes the live key). An empty assignment (`KEY=`) is also `""`. Use `process.env.X!` when TypeScript needs an assertion.
|
|
139
145
|
|
|
140
|
-
|
|
146
|
+
To deploy a single function without applying `neon.ts`: `neon functions deploy <slug> --src src/index.ts` (`--src` takes either the entry file or a directory containing `index.ts`, `index.mjs`, or `index.js`). That command's `--env` is `KEY=VALUE` (repeatable), not a file path. Use it for a targeted env update. Retrieve the public URL with `neon functions get <slug>` (the `invocation_url` field, of the form `https://<branch_id>-<slug>.compute.<cell>.us-east-2.aws.neon.tech`). Manage with `neon functions list|get|delete`.
|
|
147
|
+
|
|
148
|
+
When `neon checkout` _creates_ a new branch and a `neon.ts` is present, it applies the policy automatically. Pass `--env <file>` on that create so Function env that reads `process.env` resolves (`neon checkout feat --create --env .env.local`). Existing process env wins over the file. Checking out an existing branch never reconciles it — apply config changes with `neon deploy --env <file>` (add `--update-existing` only after reviewing those changes).
|
|
141
149
|
|
|
142
150
|
## Neon Infrastructure as Code (`neon.ts`)
|
|
143
151
|
|
|
144
|
-
The `
|
|
152
|
+
The `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:
|
|
145
153
|
|
|
146
154
|
```bash
|
|
147
155
|
neon config status # print the branch's live config (deployed functions)
|
|
148
156
|
neon config plan # dry-run diff of what apply would change
|
|
149
|
-
neon config apply
|
|
157
|
+
neon config apply --env <file> # bundle + deploy the declared functions (neon deploy is an alias; pass --env when Function env reads process.env)
|
|
150
158
|
```
|
|
151
159
|
|
|
152
|
-
Functions 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
|
|
160
|
+
Functions 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. Pass `--env <file>` on that create when Function env reads `process.env`. Checking out an _existing_ branch doesn't redeploy — run `neon deploy --env <file>` to apply changes.
|
|
153
161
|
|
|
154
162
|
Per-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:
|
|
155
163
|
|
|
156
164
|
```typescript
|
|
157
165
|
export default defineConfig({
|
|
158
|
-
|
|
159
|
-
functions: { todos: { name: "todo api", source: "src/index.ts" } },
|
|
160
|
-
},
|
|
166
|
+
functions: { todos: { name: "todo api", source: "src/index.ts" } },
|
|
161
167
|
branch: (branch) => ({
|
|
162
|
-
|
|
168
|
+
functions: { todos: { runtime: "nodejs24" } },
|
|
163
169
|
}),
|
|
164
170
|
});
|
|
165
171
|
```
|
|
@@ -174,13 +180,14 @@ Neon injects branch-scoped connection strings and service URLs at runtime — yo
|
|
|
174
180
|
| `DATABASE_URL` | Pooled connection string. Use for most queries. Present only if the branch has Postgres. |
|
|
175
181
|
| `DATABASE_URL_UNPOOLED` | Direct connection. Use for migrations, `LISTEN`/`NOTIFY`, multi-round-trip transactions. |
|
|
176
182
|
| `NEON_AUTH_BASE_URL` | Present when Neon Auth is enabled on the branch. |
|
|
183
|
+
| `NEON_AUTH_JWKS_URL` | Present when Neon Auth is enabled on the branch. JWKS for verifying Managed Auth JWTs. |
|
|
177
184
|
| `NEON_DATA_API_URL` | Present when the Data API is enabled on the branch. |
|
|
178
185
|
|
|
179
186
|
Object 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.
|
|
180
187
|
|
|
181
188
|
`neon env pull` / `neon-env run` / `neon dev` emit `NEON_BRANCH` (and the connection strings) into your local dev environment too, so local runs mirror the deployed runtime.
|
|
182
189
|
|
|
183
|
-
**Your own secrets** are per-deployment.
|
|
190
|
+
**Your own secrets** are per-deployment. Preferred path: declare them in `neon.ts` and run `neon deploy --env <file>`. `<file>` is the gitignored file env pull already writes (`.env` if that file exists, otherwise `.env.local`). Env pull writes Neon-managed vars only; add Function secrets to that file. All declared Function env keys must be present. Omit a key from `neon.ts` if you do not want to write it. `undefined` means you asked to write the key and the value is missing (`defineConfig` throws). Never coerce a missing `process.env` value to an empty string: that uploads `""` and deletes the live key. An empty assignment in the file (`KEY=`) is also `""`. If TypeScript needs an assertion, use `process.env.X!` and make sure the file has the value:
|
|
184
191
|
|
|
185
192
|
```typescript
|
|
186
193
|
functions: {
|
|
@@ -192,7 +199,9 @@ functions: {
|
|
|
192
199
|
}
|
|
193
200
|
```
|
|
194
201
|
|
|
195
|
-
|
|
202
|
+
`neon functions deploy --env KEY=VALUE` is the manual path (repeatable; `--env KEY=` deletes a key; unmentioned keys carry over). Use it for a targeted env update, not a full `neon.ts` apply.
|
|
203
|
+
|
|
204
|
+
Load Function secrets into the same file env pull wrote, then `neon deploy --env <file>`. Pull the branch's Neon-managed vars onto disk for local dev with `neon env pull` (`link`/`checkout` do this automatically; pass `--no-env-pull` to skip and use `neon-env run -- <cmd>` for runtime injection). Limits: ≤1,000 vars, ≤64 KiB total, and the `NEON_` prefix is reserved.
|
|
196
205
|
|
|
197
206
|
## Connecting to Postgres
|
|
198
207
|
|
|
@@ -231,7 +240,7 @@ Functions are long-running but **still serverless** — they are a request/respo
|
|
|
231
240
|
- **Heartbeat: 15 minutes.** Open WebSocket/SSE 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.
|
|
232
241
|
- **`waitUntil`: 15 minutes.** Work registered with `waitUntil` (from `@neon/functions`) 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. Off the Neon runtime (local `neon dev`, tests) it's a no-op: the promise still runs but isn't tracked.
|
|
233
242
|
- **Idle eviction.** With no active connections Neon shuts the function down; it may also evict/restart 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/SSE 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.
|
|
234
|
-
- **Runtime:** Node.js 24, memory fixed at 2048 MiB
|
|
243
|
+
- **Runtime:** Node.js 24, memory fixed at 2048 MiB. 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)).
|
|
235
244
|
|
|
236
245
|
## Functions as an Agent Backend (Next.js and Similar Frameworks)
|
|
237
246
|
|
|
@@ -246,20 +255,23 @@ Browser ──(Authorization: Bearer <JWT>)──▶ Neon Function (agent)
|
|
|
246
255
|
Browser ──▶ your app backend ──▶ Neon Function ❌ host cuts the stream
|
|
247
256
|
```
|
|
248
257
|
|
|
249
|
-
-
|
|
250
|
-
-
|
|
258
|
+
- Get a **short-lived bearer token** from the identity the app already uses. Do not switch Clerk, Better Auth, Auth.js, Supabase Auth, or Managed Auth in order to call a Function.
|
|
259
|
+
- Managed Auth, default client (`createAuthClient` / Next wrapper): `authClient.token()`, then `data.token`. Verify with injected `NEON_AUTH_JWKS_URL` and issuer `new URL(process.env.NEON_AUTH_BASE_URL!).origin`.
|
|
260
|
+
- Managed Auth with `SupabaseAuthAdapter()`: that client has no `.token()`. Use `getSession()`, then `data.session.access_token`. Same JWKS/issuer as above.
|
|
261
|
+
- Existing Better Auth / Auth.js / other signer that already publishes JWKS: use that JWKS URL, issuer, and audience. Inspect the installed contract; cookie or database sessions are not a JWKS.
|
|
262
|
+
- Cookie/database sessions only: mint a short token on the existing app backend (that call is fast and stays within host limits), then the browser calls the Function **directly** with `Authorization: Bearer`. The Function stream must not go through the app host.
|
|
263
|
+
- Hand the token to the client, e.g. with the Vercel AI SDK: `new DefaultChatTransport({ api: NEON_FUNCTION_URL, fetch })` where `fetch` attaches `Authorization: Bearer <token>`. Your app server is never in the path of the long stream.
|
|
251
264
|
- Add **CORS** so the browser can reach it (handle `OPTIONS`, set `Access-Control-Allow-Origin`/`-Headers`).
|
|
252
265
|
|
|
253
266
|
> [!WARNING]
|
|
254
|
-
> 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
|
|
267
|
+
> 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 against the caller's JWKS, check a shared secret / API key, or reject the request. Never deploy an unauthenticated agent.
|
|
255
268
|
|
|
256
269
|
```typescript
|
|
257
270
|
// src/index.ts — verify the caller before doing any work
|
|
258
271
|
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
259
272
|
|
|
260
|
-
const jwks = createRemoteJWKSet(
|
|
261
|
-
|
|
262
|
-
);
|
|
273
|
+
const jwks = createRemoteJWKSet(new URL(process.env.NEON_AUTH_JWKS_URL!));
|
|
274
|
+
const issuer = new URL(process.env.NEON_AUTH_BASE_URL!).origin;
|
|
263
275
|
|
|
264
276
|
export default {
|
|
265
277
|
async fetch(request: Request) {
|
|
@@ -273,30 +285,39 @@ export default {
|
|
|
273
285
|
headers: cors(request),
|
|
274
286
|
});
|
|
275
287
|
}
|
|
288
|
+
let userId: string;
|
|
276
289
|
try {
|
|
277
|
-
const { payload } = await jwtVerify(auth.slice(7), jwks, {
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
290
|
+
const { payload } = await jwtVerify(auth.slice(7), jwks, { issuer });
|
|
291
|
+
if (!payload.sub) {
|
|
292
|
+
return new Response("Unauthorized", {
|
|
293
|
+
status: 401,
|
|
294
|
+
headers: cors(request),
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
userId = payload.sub;
|
|
283
298
|
} catch {
|
|
284
299
|
return new Response("Unauthorized", {
|
|
285
300
|
status: 401,
|
|
286
301
|
headers: cors(request),
|
|
287
302
|
});
|
|
288
303
|
}
|
|
304
|
+
// Authorize resource access by userId, then run the agent scoped to that user.
|
|
305
|
+
// ... return result.toUIMessageStreamResponse({ headers: cors(request) })
|
|
289
306
|
},
|
|
290
307
|
};
|
|
291
308
|
```
|
|
292
309
|
|
|
293
|
-
|
|
310
|
+
That snippet is Managed Auth verification. Mint the bearer token with `.token()` (`data.token`) on the default client, or `getSession()` then `data.session.access_token` on `SupabaseAuthAdapter()`. For another identity, pass that app's JWKS URL and issuer through Function `env` (see [Environment Variables](#environment-variables)) and include `audience` only when that token contract requires it. https://neon.com/docs/compute/functions/authentication.md
|
|
311
|
+
|
|
312
|
+
A valid token is not permission to read another user's rows. Exercise two users: each can access their own data; cross-user access is denied. Repeat after restarting the Function against stored rows. A request-supplied owner id cannot grant access.
|
|
313
|
+
|
|
314
|
+
Persist anything you need to keep (generated images, history) in Postgres — module state doesn't survive eviction.
|
|
294
315
|
|
|
295
316
|
## WebSocket Servers
|
|
296
317
|
|
|
297
318
|
A 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)).
|
|
298
319
|
|
|
299
|
-
**Upgrade from inside `fetch`.** Call `upgradeWebSocket(request)` from [`@neon/functions`](https://www.npmjs.com/package/@neon/functions) and return the response it gives you. There is one entrypoint and no WebSocket dependency to install:
|
|
320
|
+
**Upgrade from inside `fetch`.** Call `upgradeWebSocket(request)` from [`@neon/functions`](https://www.npmjs.com/package/@neon/functions) and return the response it gives you. Hono apps use the same primitive via `@neon/functions/hono` (see [Hono](#hono) below). There is one entrypoint and no WebSocket dependency to install:
|
|
300
321
|
|
|
301
322
|
```typescript
|
|
302
323
|
import { upgradeWebSocket } from "@neon/functions";
|
|
@@ -319,7 +340,7 @@ export default {
|
|
|
319
340
|
Three rules that matter:
|
|
320
341
|
|
|
321
342
|
- **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.
|
|
322
|
-
- **Refuse a handshake by returning an ordinary `Response`.**
|
|
343
|
+
- **Refuse a handshake by returning an ordinary `Response`.** Return a `401`, `403`, or `404` from `fetch`, before you upgrade, to gate a socket. A browser client can't read why a handshake was refused; it sees only a generic connection failure, not your status or body. Refuse to keep clients out, but send any detail the client needs over a separate authenticated request.
|
|
323
344
|
- **`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`.
|
|
324
345
|
|
|
325
346
|
**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:
|
|
@@ -354,37 +375,52 @@ export default {
|
|
|
354
375
|
|
|
355
376
|
**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.
|
|
356
377
|
|
|
357
|
-
**Hono.**
|
|
378
|
+
**Hono.** Use `upgradeWebSocket` from `@neon/functions/hono` — the same primitive as Hono's own WebSocket helper, with no `ws` dependency and not the deprecated `@hono/node-ws`. Auth is ordinary middleware; gate upgrade requests before `next()`:
|
|
358
379
|
|
|
359
380
|
```typescript
|
|
360
381
|
// src/index.ts
|
|
361
382
|
import { Hono } from "hono";
|
|
362
|
-
import { upgradeWebSocket } from "@neon/functions";
|
|
383
|
+
import { upgradeWebSocket } from "@neon/functions/hono";
|
|
363
384
|
|
|
364
|
-
const
|
|
385
|
+
const clients = new Set<WebSocket>();
|
|
365
386
|
|
|
366
|
-
app
|
|
387
|
+
const app = new Hono<{ Variables: { userId: string } }>();
|
|
367
388
|
|
|
368
|
-
app.
|
|
389
|
+
app.use("/ws", async (c, next) => {
|
|
369
390
|
const identity = await verifyToken(c.req.query("token"));
|
|
370
391
|
if (!identity) return c.text("Unauthorized", 401);
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
socket.addEventListener("open", () => socket.send("welcome"));
|
|
374
|
-
socket.addEventListener("message", (event) =>
|
|
375
|
-
socket.send(`echo: ${event.data}`),
|
|
376
|
-
);
|
|
377
|
-
return response;
|
|
392
|
+
c.set("userId", identity.id);
|
|
393
|
+
await next();
|
|
378
394
|
});
|
|
379
395
|
|
|
380
|
-
|
|
396
|
+
app.get(
|
|
397
|
+
"/ws",
|
|
398
|
+
upgradeWebSocket((c) => ({
|
|
399
|
+
onOpen(_event, ws) {
|
|
400
|
+
clients.add(ws.raw);
|
|
401
|
+
ws.send("welcome");
|
|
402
|
+
},
|
|
403
|
+
onClose(_event, ws) {
|
|
404
|
+
clients.delete(ws.raw);
|
|
405
|
+
},
|
|
406
|
+
onMessage(event, ws) {
|
|
407
|
+
ws.send(`echo: ${event.data}`);
|
|
408
|
+
},
|
|
409
|
+
})),
|
|
410
|
+
);
|
|
411
|
+
|
|
412
|
+
export default app;
|
|
381
413
|
```
|
|
382
414
|
|
|
415
|
+
Connect from the browser with the function's `wss://` URL (from `neon functions get <slug>`), for example `new WebSocket("wss://<branch>-<slug>.compute.<region>.aws.neon.tech/ws?token=<jwt>")`. Reconnect on close — isolates are evictable and idle connections may be terminated after 15 minutes.
|
|
416
|
+
|
|
417
|
+
Do not put `cors()` on the upgrade route, and do not read `c.res` before `await next()` or call `c.header()` after it — both rebuild the `101` and break the upgrade. See `@neon/functions` README for the full middleware table.
|
|
418
|
+
|
|
383
419
|
### Heartbeat (keep the socket alive)
|
|
384
420
|
|
|
385
421
|
A 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 / 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.
|
|
386
422
|
|
|
387
|
-
The standard `WebSocket` interface has no `ping()`, so send an application-level message the client
|
|
423
|
+
The standard `WebSocket` interface has no `ping()`, so send an application-level message the client filters out:
|
|
388
424
|
|
|
389
425
|
```typescript
|
|
390
426
|
const HEARTBEAT_MS = 25_000; // comfortably under proxy idle timeouts
|
|
@@ -397,7 +433,7 @@ const beat = setInterval(() => {
|
|
|
397
433
|
beat.unref?.();
|
|
398
434
|
```
|
|
399
435
|
|
|
400
|
-
The client
|
|
436
|
+
The client skips these when handling messages. There is no protocol-level shortcut here: the standard `WebSocket` from `upgradeWebSocket` has no `ping()`, and a browser can't send ping frames from JavaScript, so an application-level message is the only keepalive a browser client can use. (A Node `ws` client can send ping frames, and the server auto-replies with a pong, but a browser can't.)
|
|
401
437
|
|
|
402
438
|
### Keeping clients in sync across isolates (do not skip this)
|
|
403
439
|
|
|
@@ -408,26 +444,44 @@ Module state doesn't survive eviction anyway, so **Postgres is the shared source
|
|
|
408
444
|
**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.
|
|
409
445
|
|
|
410
446
|
```typescript
|
|
411
|
-
let lastId = 0;
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
447
|
+
let lastId = "0"; // bigint id, so a string
|
|
448
|
+
let polling = false;
|
|
449
|
+
|
|
450
|
+
async function poll() {
|
|
451
|
+
if (polling || clients.size === 0) return; // guard overlap; no clients → no query → compute can scale to zero
|
|
452
|
+
polling = true;
|
|
453
|
+
try {
|
|
454
|
+
const { rows } = await pool.query(
|
|
455
|
+
"SELECT id, payload FROM events WHERE id > $1 ORDER BY id",
|
|
456
|
+
[lastId],
|
|
457
|
+
);
|
|
458
|
+
for (const { id, payload } of rows) {
|
|
459
|
+
lastId = id;
|
|
460
|
+
for (const socket of clients) {
|
|
461
|
+
if (socket.readyState === socket.OPEN) socket.send(payload);
|
|
462
|
+
}
|
|
422
463
|
}
|
|
464
|
+
} catch (err) {
|
|
465
|
+
console.error("[poll]", err);
|
|
466
|
+
} finally {
|
|
467
|
+
polling = false;
|
|
423
468
|
}
|
|
424
|
-
}
|
|
425
|
-
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// Seed from the latest id so a fresh isolate sends only new rows, not the whole table, then poll.
|
|
472
|
+
pool
|
|
473
|
+
.query("SELECT coalesce(max(id), 0)::text AS id FROM events")
|
|
474
|
+
.then((seed) => {
|
|
475
|
+
lastId = seed.rows[0].id;
|
|
476
|
+
})
|
|
477
|
+
.catch((err) => console.error("[seed]", err))
|
|
478
|
+
.finally(() => setInterval(poll, 1000).unref?.());
|
|
426
479
|
```
|
|
427
480
|
|
|
428
481
|
- **Latency:** up to the interval (~1s) — fine for counters, chat, and dashboards.
|
|
429
482
|
- **Scaling:** database load grows with the number of live isolates, not clients. Keep the cursor on an indexed `serial`/`bigserial` PK and the interval sane.
|
|
430
483
|
- **Scale to Zero:** ✅ preserved — polling stops when no clients are connected, so the compute suspends on its normal timer.
|
|
484
|
+
- **Ordering:** `WHERE id > cursor` can skip a row that commits out of sequence: a transaction that took a lower id but commits after a higher one is already behind the cursor, so the poll never returns it. For a broadcast feed occasional loss is usually fine; when you need every row, use `LISTEN`/`NOTIFY` or poll by `created_at` with a small overlap window and dedupe by id.
|
|
431
485
|
|
|
432
486
|
**2. `LISTEN`/`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://neon.com/docs/introduction/scale-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).
|
|
433
487
|
|
|
@@ -442,7 +496,7 @@ const CHANNEL = "chat_events";
|
|
|
442
496
|
// One dedicated DIRECT connection per isolate, just to receive events.
|
|
443
497
|
// Use DATABASE_URL_UNPOOLED — LISTEN needs a real session, not a pooled one.
|
|
444
498
|
// Don't call attachDatabasePool here: it would silence the idle drop that killed the feed.
|
|
445
|
-
//
|
|
499
|
+
// The error listener keeps the process alive; reconnect the client on error in production (omitted here).
|
|
446
500
|
const listener = new Client({
|
|
447
501
|
connectionString: process.env.DATABASE_URL_UNPOOLED,
|
|
448
502
|
});
|
|
@@ -508,16 +562,19 @@ When you only need **server → client** streaming (live counters, notifications
|
|
|
508
562
|
// src/index.ts — minimal SSE endpoint
|
|
509
563
|
const encoder = new TextEncoder();
|
|
510
564
|
export default {
|
|
511
|
-
fetch: () =>
|
|
512
|
-
|
|
565
|
+
fetch: () => {
|
|
566
|
+
let t: ReturnType<typeof setInterval>;
|
|
567
|
+
return new Response(
|
|
513
568
|
new ReadableStream<Uint8Array>({
|
|
514
569
|
start(controller) {
|
|
515
570
|
controller.enqueue(encoder.encode("data: hello\n\n"));
|
|
516
|
-
|
|
571
|
+
t = setInterval(
|
|
517
572
|
() => controller.enqueue(encoder.encode(": ping\n\n")),
|
|
518
573
|
25_000,
|
|
519
574
|
);
|
|
520
|
-
|
|
575
|
+
},
|
|
576
|
+
cancel() {
|
|
577
|
+
clearInterval(t); // fires when the client disconnects
|
|
521
578
|
},
|
|
522
579
|
}),
|
|
523
580
|
{
|
|
@@ -526,12 +583,19 @@ export default {
|
|
|
526
583
|
"Cache-Control": "no-cache, no-transform",
|
|
527
584
|
},
|
|
528
585
|
},
|
|
529
|
-
)
|
|
586
|
+
);
|
|
587
|
+
},
|
|
530
588
|
};
|
|
531
589
|
```
|
|
532
590
|
|
|
533
591
|
The 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/sse.md](https://neon.com/docs/ai/skills/neon-functions/references/sse.md) has the full pattern — Hono variant, cross-isolate fan-out, wire format, client, and caveats.
|
|
534
592
|
|
|
593
|
+
## Function Triggers
|
|
594
|
+
|
|
595
|
+
A Function Trigger POSTs JSON to your function on a cron. Declare it in `neon.ts`, apply with `neon deploy`, and authenticate the delivery with `parseTrigger` (Hono) or `parseTriggerInvocation` (a `fetch` handler). The only trigger type today is `schedule`. Prefer `neon.ts`; CLI and the Neon MCP trigger tools (`list_triggers`, `create_trigger`, …) are the backup.
|
|
596
|
+
|
|
597
|
+
Full field list, CLI, MCP, payload, inheritance, and both handler shapes: [references/function-triggers.md](references/function-triggers.md).
|
|
598
|
+
|
|
535
599
|
## MCP Servers
|
|
536
600
|
|
|
537
601
|
An [MCP](https://modelcontextprotocol.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`/`GET` on a single endpoint (conventionally `/mcp`), so it maps onto a function's `fetch` handler with no `upgrade` method or extra protocol.
|
|
@@ -577,4 +641,5 @@ The Neon documentation is the source of truth and Functions is evolving rapidly,
|
|
|
577
641
|
- https://neon.com/docs/compute/functions/environment-variables.md
|
|
578
642
|
- https://neon.com/docs/compute/functions/reference/neon-ts.md
|
|
579
643
|
- https://neon.com/docs/compute/functions/reference/runtime-limits.md
|
|
580
|
-
- https://neon.com/docs/
|
|
644
|
+
- https://neon.com/docs/cli/triggers.md
|
|
645
|
+
- [references/function-triggers.md](references/function-triggers.md)
|
|
@@ -15,12 +15,10 @@ The agent needs the AI Gateway (and, for the image example, an Object Storage bu
|
|
|
15
15
|
import { defineConfig } from "@neon/config/v1";
|
|
16
16
|
|
|
17
17
|
export default defineConfig({
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
agent: { name: "ai agent", source: "src/index.ts" },
|
|
23
|
-
},
|
|
18
|
+
aiGateway: true,
|
|
19
|
+
buckets: { images: {} },
|
|
20
|
+
functions: {
|
|
21
|
+
agent: { name: "ai agent", source: "src/index.ts" },
|
|
24
22
|
},
|
|
25
23
|
});
|
|
26
24
|
```
|