@neon/skills 1.2.0 → 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.
@@ -0,0 +1,173 @@
1
+ # Managed Better Auth: implement login
2
+
3
+ Enabling `auth: true` is not implementing login. Follow the matching live quickstart, then verify sign-up, sign-in, sign-out, session, and a protected route.
4
+
5
+ - Overview: https://neon.com/docs/auth/overview.md
6
+ - Next.js (API methods): https://neon.com/docs/auth/quick-start/nextjs-api-only.md
7
+ - React (API methods, including React Router): https://neon.com/docs/auth/quick-start/react.md
8
+ - TanStack Router (UI components): https://neon.com/docs/auth/quick-start/tanstack-router.md
9
+
10
+ Keep Clerk, existing Better Auth, Supabase Auth, or another working provider. Do not migrate it unless the user asks. The `SKILL.md` Supabase case is that explicit login-migration request.
11
+
12
+ Framework-specific companion skills also live in [neondatabase/neon-js](https://github.com/neondatabase/neon-js) (`neon-auth-nextjs`, `neon-auth-react`, `neon-js-react`). Prefer the live Neon guides above; do not copy those SDK-local files into this repo.
13
+
14
+ ## Auth emails
15
+
16
+ Managed Auth sends verification, email OTP, magic-link, and password-reset messages. Getting started uses the shared SMTP provider (`auth@mail.myneon.app`). Implementing login does not require Resend, SendGrid, or other application email code.
17
+
18
+ Production requires custom SMTP. Verification codes work on shared or custom SMTP. Verification links require custom SMTP. Checklist: https://neon.com/docs/auth/production-checklist.md. Branding and webhook delivery: https://neon.com/docs/auth/guides/customize-emails.md.
19
+
20
+ SMS is separate: the Phone Number plugin needs an application `send.otp` webhook.
21
+
22
+ ## Packages
23
+
24
+ | Need | Package |
25
+ | --- | --- |
26
+ | Auth only | `@neondatabase/auth` |
27
+ | Already using the combined SDK | `@neondatabase/neon-js/auth` re-export |
28
+ | Pre-built UI | `@neondatabase/auth-ui` |
29
+
30
+ Keep an existing `SupabaseAuthAdapter()` caller on that API (`signInWithPassword`, `signInWithOAuth`). Do not mix those methods into default Better Auth examples. Password hashes do not migrate from Supabase; `updateUser()` cannot change email or password; email verification needs app UI. Guide: https://neon.com/docs/auth/migrate/from-supabase.md
31
+
32
+ The Managed client is Better Auth methods through Neon's wrapper. It is not interchangeable with bare `better-auth/client` while Auth is managed: the wrapper rejects extra plugins and implements Neon OAuth verifier / iframe popup / JWT extraction.
33
+
34
+ ## Environment
35
+
36
+ | Variable | Purpose |
37
+ | --- | --- |
38
+ | `NEON_AUTH_BASE_URL` | Branch Managed Auth URL (includes path). Next server; injected into Functions. |
39
+ | `NEON_AUTH_COOKIE_SECRET` | Next app secret for cached session cookies. Generate with `openssl rand -base64 32` (32+ characters). Not injected by Neon. |
40
+ | `VITE_NEON_AUTH_URL` | Public Auth URL for Vite / TanStack browser code. Assign the actual branch URL; env pull does not create this alias. |
41
+ | `NEON_AUTH_JWKS_URL` | Injected Functions JWKS. Verify tokens in `neon-functions`, not here. |
42
+
43
+ `neon env pull` / `neon deploy` write Managed `NEON_AUTH_BASE_URL` and `NEON_AUTH_JWKS_URL` when Auth is declared. The cookie secret and `VITE_*` name are application config.
44
+
45
+ ## Next.js
46
+
47
+ `createNeonAuth` from `@neondatabase/auth/next/server`. Optional Next peer on current `@neondatabase/auth` is `>=16.0.0`; check the installed package before changing an existing app's router file.
48
+
49
+ ```typescript
50
+ import { createNeonAuth } from "@neondatabase/auth/next/server";
51
+
52
+ export const auth = createNeonAuth({
53
+ baseUrl: process.env.NEON_AUTH_BASE_URL!,
54
+ cookies: { secret: process.env.NEON_AUTH_COOKIE_SECRET! },
55
+ });
56
+ ```
57
+
58
+ `app/api/auth/[...path]/route.ts`:
59
+
60
+ ```typescript
61
+ import { auth } from "@/lib/auth/server";
62
+
63
+ export const { GET, POST, PUT, DELETE, PATCH } = auth.handler();
64
+ ```
65
+
66
+ Those five methods are what the installed SDK returns. Existing apps that export only `GET`/`POST` keep serving GET/POST routes.
67
+
68
+ Browser client takes **no arguments** and talks to that same-origin proxy:
69
+
70
+ ```typescript
71
+ import { createAuthClient } from "@neondatabase/auth/next";
72
+
73
+ export const authClient = createAuthClient();
74
+ ```
75
+
76
+ Protect routes with `auth.middleware({ loginUrl: "/auth/sign-in" })` from `proxy.ts` on Next 16. Earlier Next apps may still use `middleware.ts`; match the installed SDK. Always set `config.matcher` to the protected pages. A matcher that covers every path redirects JavaScript and CSS for unauthenticated visitors, so the login page cannot load:
77
+
78
+ ```typescript
79
+ import { auth } from "@/lib/auth/server";
80
+
81
+ export default auth.middleware({ loginUrl: "/auth/sign-in" });
82
+
83
+ export const config = {
84
+ matcher: ["/account/:path*"],
85
+ };
86
+ ```
87
+
88
+ Replace `/account/:path*` with the app's protected routes. Keep login, registration, recovery, `/api/auth`, and static assets accessible without a session.
89
+
90
+ Before reading protected data or performing a mutation, check the session inside the Route Handler or Server Action and enforce the resource's authorization rules. Verify direct unauthenticated requests are denied, independently of page redirects:
91
+
92
+ ```typescript
93
+ const { data: session } = await auth.getSession();
94
+ if (!session?.user) {
95
+ return Response.json({ error: "Unauthorized" }, { status: 401 });
96
+ }
97
+ ```
98
+
99
+ Server session:
100
+
101
+ ```typescript
102
+ const { data: session, error } = await auth.getSession();
103
+ const user = session?.user;
104
+ ```
105
+
106
+ Do not destructure `{ user }` from the top-level result. Do not pass options into `createAuthClient()` from `/next`. Do not put `fetchOptions` on the Managed `createAuthClient` URL-style config; adapter factories accept fetch options inside `BetterAuthReactAdapter({ fetchOptions })` / `BetterAuthVanillaAdapter(...)`.
107
+
108
+ JWT: `const { data, error } = await auth.token();` then `data.token`. Do not call `getJWTToken()` on the public client.
109
+
110
+ **Phone OTP:** the browser client exposes `phoneNumber`. Existing users link a number, then sign in; there is no phone-first signup. Next.js `auth.handler()` forwards the catch-all path to Managed Auth, including phone OTP. A missing `auth.phoneNumber` server method is a missing typed helper, not a proxy rejection. SMS e2e needs a configured `send.otp` webhook and custom UI.
111
+
112
+ ## Organization invitations
113
+
114
+ `organization.inviteMember()` does not send email unless `send_invitation_email` is on (default `false`) and "Verify email at signup" is enabled. Accepting an emailed invite needs `/auth/accept-invitation?invitationId=` via `AuthView` or a custom flow that signs the recipient in and calls `organization.acceptInvitation({ invitationId })`. If email delivery stays off, use an in-app invitation list. https://neon.com/docs/auth/guides/plugins/organization.md
115
+
116
+ ## React / Vite
117
+
118
+ ```typescript
119
+ import { createAuthClient } from "@neondatabase/auth";
120
+ import { BetterAuthReactAdapter } from "@neondatabase/auth/react/adapters";
121
+
122
+ export const authClient = createAuthClient(import.meta.env.VITE_NEON_AUTH_URL, {
123
+ adapter: BetterAuthReactAdapter(),
124
+ });
125
+ ```
126
+
127
+ Call adapter factories with `()`. Omit the adapter for vanilla Better Auth methods without `useSession`.
128
+
129
+ Public calls: `signUp.email({ email, password, name })`, `signIn.email({ email, password })`, `signIn.social({ provider, callbackURL })`, `getSession()`, `signOut()`. Result shape is `{ data, error }`; user is `data.user`. Handle `error` and thrown HTTP errors, pending UI, and authenticated vs unauthenticated display.
130
+
131
+ JWT: `authClient.token()` then `data.token`.
132
+
133
+ ## UI
134
+
135
+ ```typescript
136
+ import "@neondatabase/auth-ui/css";
137
+ import { NeonAuthUIProvider, AuthView } from "@neondatabase/auth-ui";
138
+ ```
139
+
140
+ Choose one CSS import: `/css` or `/tailwind`, never both. Current `@neondatabase/auth-ui` uses `<AuthView path={path} />`. Check installed types before copying a `pathname` example from older docs.
141
+
142
+ UI flags (`emailOTP`, `magicLink`, social providers, organization) do not enable the Managed plugin. Configure the plugin on the branch, then the UI.
143
+
144
+ Preserve existing `@neondatabase/auth/react/ui` imports rather than forcing a drive-by migration. New snippets use `@neondatabase/auth-ui`.
145
+
146
+ ## Cross-subdomain vs bearer JWT
147
+
148
+ `cookies.domain` shares session cookies across subdomains of one parent domain (see the neon-js `cross-domain-cookies` example). That is not cookie sharing across unrelated frontend and backend hosts. A Neon Function authenticates with `Authorization: Bearer`. With Managed Auth, verify against the injected JWKS. With another identity, use that identity's token contract — see `neon-functions`. https://neon.com/docs/compute/functions/authentication.md and https://neon.com/docs/auth/guides/plugins/jwt.md.
149
+
150
+ ## Data API identity
151
+
152
+ Only when the app already uses PostgREST or a Supabase database client:
153
+
154
+ ```typescript
155
+ import { defineConfig } from "@neon/config/v1";
156
+
157
+ export default defineConfig({ auth: true, dataApi: true });
158
+ ```
159
+
160
+ Existing external IdP:
161
+
162
+ ```typescript
163
+ import { defineConfig } from "@neon/config/v1";
164
+
165
+ export default defineConfig({
166
+ dataApi: {
167
+ authProvider: "external",
168
+ jwksUrl: "https://your-idp/.well-known/jwks.json",
169
+ },
170
+ });
171
+ ```
172
+
173
+ Do not enable Auth merely to satisfy a `dataApi` type error in an app that never needed the Data API. External JWKS on a Claimable project is accepted only after claim. Combined SDK `createClient({ dataApi: { url, getToken } })` is a query client without `.auth`; confirm the installed `@neondatabase/neon-js` docs before introducing it.
@@ -0,0 +1,25 @@
1
+ # Self-managed Better Auth
2
+
3
+ Use this page only after `SKILL.md` routed here: a required feature is outside Managed Auth, and the installed Better Auth version documents that flow. If that check fails, keep the current identity.
4
+
5
+ ## Keep existing Better Auth
6
+
7
+ If the app already runs Better Auth, keep that server, its clients, users, and sessions. It works with Lakebase Postgres, Functions, Object Storage, and the AI Gateway. Do not migrate it to Managed Auth unless the user asks.
8
+
9
+ ## New self-managed server
10
+
11
+ Host it on the existing app (Vercel route handlers, or similar) when that host already serves `/api/auth`. Use a Neon Function when the auth server should sit next to Postgres, or when the Function itself must be an OAuth authorization server (MCP). Function hosting follows the `neon-functions` skill (region, claim, `neon.ts`, `neon deploy --env <file>`).
12
+
13
+ Keep Lakebase Postgres as the auth database. Use `better-auth` and `better-auth/client`. Fetch upstream docs for the **installed** version:
14
+
15
+ - https://better-auth.com/docs/installation
16
+ - https://better-auth.com/docs/concepts/client
17
+ - https://better-auth.com/docs/concepts/plugins
18
+
19
+ Do not pass `plugins` into `@neondatabase/auth`. Replacing only the client package while Managed Auth is still the backend does not add plugins.
20
+
21
+ MCP OAuth (Cursor, Claude, and similar clients self-authorizing) is `neon-functions` [references/mcp.md](https://neon.com/docs/ai/skills/neon-functions/references/mcp.md). That can sit beside existing Clerk or Managed login. Do not migrate the whole app's identity unless that was the request.
22
+
23
+ Function JWT verification, CORS, and direct browser calls: `neon-functions` and https://neon.com/docs/compute/functions/authentication.md.
24
+
25
+ There is no documented universal import from Managed `neon_auth` into a self-managed Better Auth schema. Inventory users, credentials, sessions, memberships, and application foreign keys before changing existing state. Agree a cutover plan with the owner. Do not promise drop-in session continuity.
@@ -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. Triggers include "serverless
11
- function", "deploy an API", "long-running function", "streaming agent",
12
- "SSE server", "WebSocket server", "webhook handler", "MCP server",
13
- "run code next to my database", "function that won't time out",
14
- "function logs", "Neon Functions", and "Neon Compute".
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
- npx skills add neondatabase/agent-skills --skill neon
28
+ neon skills -s neon -y
26
29
  ```
27
30
 
28
31
  # Neon Functions
29
32
 
30
- This is a public beta feature, currently available in `us-east-2` and `eu-central-1`.
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, a cron/background job that needs its own lifecycle and cancellation, or something that must run outside the supported regions (`us-east-2`, `eu-central-1`) today, this isn't the right tool yet (see [Timeouts and Runtime Limits](#timeouts-and-runtime-limits) and [Availability](#availability)).
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 a public beta feature currently available in `us-east-2` and `eu-central-1`. Confirm the user's Neon project is in one of these regions. Functions usage isn't billed during the public beta.
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 (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.)
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 `preview.functions`, keyed by **slug**:
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
- preview: {
79
- functions: {
80
- todos: {
81
- // slug: ^[a-z0-9]{1,20}$ — lowercase letters/digits, no hyphens
82
- name: "todo api", // display label only
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
  });
@@ -135,15 +141,15 @@ neon dev # serves every function in neon.ts with hot reload; injects DATABA
135
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
- Keep `.env` or `.env.local` up to date with every key under `preview.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.
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`.
141
147
 
142
- When `neon checkout` _creates_ a new branch and a `neon.ts` is present, it applies the policy automatically. That create-apply does not load `--env`. If Function env reads `process.env`, run `neon deploy --env <file>` after checkout (add `--update-existing` if checkout already created the branch). Checking out an existing branch does not re-deploy; run `neon deploy --env <file>` explicitly.
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).
143
149
 
144
150
  ## Neon Infrastructure as Code (`neon.ts`)
145
151
 
146
- The `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:
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:
147
153
 
148
154
  ```bash
149
155
  neon config status # print the branch's live config (deployed functions)
@@ -151,17 +157,15 @@ neon config plan # dry-run diff of what apply would change
151
157
  neon config apply --env <file> # bundle + deploy the declared functions (neon deploy is an alias; pass --env when Function env reads process.env)
152
158
  ```
153
159
 
154
- 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. That create-apply does not load `--env`. If Function env reads `process.env`, run `neon deploy --env <file>` after checkout. Checking out an _existing_ branch doesn't redeploy — run `neon deploy --env <file>` to apply changes.
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.
155
161
 
156
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:
157
163
 
158
164
  ```typescript
159
165
  export default defineConfig({
160
- preview: {
161
- functions: { todos: { name: "todo api", source: "src/index.ts" } },
162
- },
166
+ functions: { todos: { name: "todo api", source: "src/index.ts" } },
163
167
  branch: (branch) => ({
164
- preview: { functions: { todos: { runtime: "nodejs24" } } },
168
+ functions: { todos: { runtime: "nodejs24" } },
165
169
  }),
166
170
  });
167
171
  ```
@@ -176,6 +180,7 @@ Neon injects branch-scoped connection strings and service URLs at runtime — yo
176
180
  | `DATABASE_URL` | Pooled connection string. Use for most queries. Present only if the branch has Postgres. |
177
181
  | `DATABASE_URL_UNPOOLED` | Direct connection. Use for migrations, `LISTEN`/`NOTIFY`, multi-round-trip transactions. |
178
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. |
179
184
  | `NEON_DATA_API_URL` | Present when the Data API is enabled on the branch. |
180
185
 
181
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.
@@ -235,7 +240,7 @@ Functions are long-running but **still serverless** — they are a request/respo
235
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.
236
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.
237
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.
238
- - **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)).
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)).
239
244
 
240
245
  ## Functions as an Agent Backend (Next.js and Similar Frameworks)
241
246
 
@@ -250,20 +255,23 @@ Browser ──(Authorization: Bearer <JWT>)──▶ Neon Function (agent)
250
255
  Browser ──▶ your app backend ──▶ Neon Function ❌ host cuts the stream
251
256
  ```
252
257
 
253
- - 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.
254
- - 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 <token>`. Your app server is never in the path of the long stream.
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.
255
264
  - Add **CORS** so the browser can reach it (handle `OPTIONS`, set `Access-Control-Allow-Origin`/`-Headers`).
256
265
 
257
266
  > [!WARNING]
258
- > 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 / API key, or validate a session token at the top of the handler and reject anything else. Never deploy an unauthenticated agent.
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.
259
268
 
260
269
  ```typescript
261
270
  // src/index.ts — verify the caller before doing any work
262
271
  import { createRemoteJWKSet, jwtVerify } from "jose";
263
272
 
264
- const jwks = createRemoteJWKSet(
265
- new URL(`${process.env.AUTH_BASE_URL}/api/auth/jwks`),
266
- );
273
+ const jwks = createRemoteJWKSet(new URL(process.env.NEON_AUTH_JWKS_URL!));
274
+ const issuer = new URL(process.env.NEON_AUTH_BASE_URL!).origin;
267
275
 
268
276
  export default {
269
277
  async fetch(request: Request) {
@@ -277,24 +285,33 @@ export default {
277
285
  headers: cors(request),
278
286
  });
279
287
  }
288
+ let userId: string;
280
289
  try {
281
- const { payload } = await jwtVerify(auth.slice(7), jwks, {
282
- issuer: process.env.AUTH_BASE_URL,
283
- audience: process.env.AUTH_BASE_URL,
284
- });
285
- const userId = payload.sub; // scope the agent to this user
286
- // ... run the agent, return result.toUIMessageStreamResponse({ headers: cors(request) })
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;
287
298
  } catch {
288
299
  return new Response("Unauthorized", {
289
300
  status: 401,
290
301
  headers: cors(request),
291
302
  });
292
303
  }
304
+ // Authorize resource access by userId, then run the agent scoped to that user.
305
+ // ... return result.toUIMessageStreamResponse({ headers: cors(request) })
293
306
  },
294
307
  };
295
308
  ```
296
309
 
297
- Pass the JWKS/issuer 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.
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.
298
315
 
299
316
  ## WebSocket Servers
300
317
 
@@ -454,7 +471,9 @@ async function poll() {
454
471
  // Seed from the latest id so a fresh isolate sends only new rows, not the whole table, then poll.
455
472
  pool
456
473
  .query("SELECT coalesce(max(id), 0)::text AS id FROM events")
457
- .then((seed) => { lastId = seed.rows[0].id; })
474
+ .then((seed) => {
475
+ lastId = seed.rows[0].id;
476
+ })
458
477
  .catch((err) => console.error("[seed]", err))
459
478
  .finally(() => setInterval(poll, 1000).unref?.());
460
479
  ```
@@ -571,6 +590,12 @@ export default {
571
590
 
572
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.
573
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
+
574
599
  ## MCP Servers
575
600
 
576
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.
@@ -616,4 +641,5 @@ The Neon documentation is the source of truth and Functions is evolving rapidly,
616
641
  - https://neon.com/docs/compute/functions/environment-variables.md
617
642
  - https://neon.com/docs/compute/functions/reference/neon-ts.md
618
643
  - https://neon.com/docs/compute/functions/reference/runtime-limits.md
619
- - https://neon.com/docs/compute/functions/preview-access.md
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
- preview: {
19
- aiGateway: true,
20
- buckets: { images: {} },
21
- functions: {
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
  ```