@neon/skills 1.2.0 → 2.1.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 +6 -0
- package/assets/neon-logomark-dark.svg +10 -0
- package/assets/neon-logomark-light.svg +10 -0
- package/package.json +2 -1
- package/plugin.json +27 -2
- package/skills/neon/SKILL.md +201 -217
- 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 +14 -16
- 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 +92 -45
- package/skills/neon-functions/references/ai-sdk.md +4 -6
- package/skills/neon-functions/references/function-triggers.md +249 -0
- package/skills/neon-functions/references/mastra-studio.md +1 -1
- package/skills/neon-functions/references/mcp.md +1 -1
- package/skills/neon-functions/references/native-binaries.md +188 -0
- package/skills/neon-functions/references/production-hardening.md +340 -0
- package/skills/neon-object-storage/SKILL.md +10 -11
- package/skills/neon-postgres/SKILL.md +106 -19
- package/skills/neon-postgres/references/lakebase-search-drizzle.md +172 -0
- package/skills/neon-postgres-branches/SKILL.md +3 -3
- package/skills/neon-postgres-egress-optimizer/SKILL.md +1 -1
|
@@ -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,15 @@ 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",
|
|
17
|
+
"Neon Compute", "DDoS protection", "rate limiting", and
|
|
18
|
+
"production hardening".
|
|
15
19
|
metadata:
|
|
16
20
|
parent: neon
|
|
17
21
|
source: https://github.com/neondatabase/agent-skills/tree/main/skills/neon-functions
|
|
@@ -22,12 +26,12 @@ metadata:
|
|
|
22
26
|
If the `neon` skill is not installed, fetch it from https://neon.com/docs/ai/skills/neon/SKILL.md or install it with:
|
|
23
27
|
|
|
24
28
|
```bash
|
|
25
|
-
|
|
29
|
+
neon skills -s neon -y
|
|
26
30
|
```
|
|
27
31
|
|
|
28
32
|
# Neon Functions
|
|
29
33
|
|
|
30
|
-
|
|
34
|
+
Currently available in `aws-us-east-2`, `aws-us-east-1`, `aws-eu-central-1`, and `aws-ap-southeast-1`.
|
|
31
35
|
|
|
32
36
|
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
37
|
|
|
@@ -41,9 +45,11 @@ Reach for Neon Functions when the workload is a request/response handler that be
|
|
|
41
45
|
- **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
46
|
- **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
47
|
- **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.
|
|
48
|
+
- **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
49
|
- **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.
|
|
50
|
+
- **Recurring HTTP work.** A Function Trigger POSTs to the function on a cron (`type: "schedule"`) or when an object is created in Object Storage (`type: "storage_object_created"`). Same `fetch` handler, same 15-minute time-to-first-byte limit. See [Function Triggers](#function-triggers).
|
|
45
51
|
|
|
46
|
-
If the workload is a pure static site,
|
|
52
|
+
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
53
|
|
|
48
54
|
## What It Does
|
|
49
55
|
|
|
@@ -52,36 +58,43 @@ If the workload is a pure static site, a cron/background job that needs its own
|
|
|
52
58
|
- **Close to your database** — Runs in the branch's region; `DATABASE_URL` injected automatically when the branch has Postgres.
|
|
53
59
|
- **Branchable** — Each branch runs its own function version at its own URL against its own isolated state.
|
|
54
60
|
- **Same CLI/API** — Deploy and manage via `neon`, `neon.ts`, or the Neon API.
|
|
61
|
+
- **Function Triggers** — Neon POSTs to the function on a cron or an object-storage upload. See [Function Triggers](#function-triggers).
|
|
55
62
|
|
|
56
63
|
## Availability
|
|
57
64
|
|
|
58
|
-
Check this precondition before setting anything up: Neon Functions is
|
|
65
|
+
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
66
|
|
|
60
67
|
## Architecture: Where Functions Fit
|
|
61
68
|
|
|
62
69
|
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
70
|
|
|
64
|
-
- **Add a Function to a full-stack app.** Your Next.js / TanStack Start app on Vercel (or Netlify) owns UI, auth (
|
|
71
|
+
- **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. Add a Function as a Hono API layer for the web app and other clients, or for one job next to the data: Object Storage uploads, AI agents, Discord bots, WebSocket or SSE servers. (See [Functions as an Agent Backend](#functions-as-an-agent-backend-nextjs-and-similar-frameworks) for the client-direct pattern.)
|
|
65
72
|
- **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
73
|
|
|
67
|
-
Either way,
|
|
74
|
+
Either way, authenticate by caller: JWT or API key for app and public HTTP (see the WARNING under [Functions as an Agent Backend](#functions-as-an-agent-backend-nextjs-and-similar-frameworks)); `parseTriggerDelivery` for Function Trigger routes; production hardening in [Production hardening](references/production-hardening.md). 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.
|
|
75
|
+
|
|
76
|
+
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.
|
|
77
|
+
|
|
78
|
+
## Production hardening
|
|
79
|
+
|
|
80
|
+
Before exposing production routes, read [Production hardening](references/production-hardening.md).
|
|
81
|
+
|
|
82
|
+
Pick by caller: trusted app server, Function Trigger, or public consumer. Keep long browser streams on the client-direct JWT path unless a verified streaming-compatible proxy is required. Authentication rejects application work; requests to the native URL still reach the Function.
|
|
68
83
|
|
|
69
84
|
## Setup
|
|
70
85
|
|
|
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 `
|
|
86
|
+
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
87
|
|
|
73
88
|
```typescript
|
|
74
89
|
// neon.ts
|
|
75
90
|
import { defineConfig } from "@neon/config/v1";
|
|
76
91
|
|
|
77
92
|
export default defineConfig({
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
source: "src/index.ts", // entry file, relative to neon.ts
|
|
84
|
-
},
|
|
93
|
+
functions: {
|
|
94
|
+
todos: {
|
|
95
|
+
// slug: ^[a-z0-9]{1,20}$ — lowercase letters/digits, no hyphens
|
|
96
|
+
name: "todo api", // display label only
|
|
97
|
+
source: "src/index.ts", // entry file, relative to neon.ts
|
|
85
98
|
},
|
|
86
99
|
},
|
|
87
100
|
});
|
|
@@ -135,15 +148,25 @@ neon dev # serves every function in neon.ts with hot reload; injects DATABA
|
|
|
135
148
|
neon deploy --env <file> # preferred full deploy from neon.ts; --env is the file Function env is read from
|
|
136
149
|
```
|
|
137
150
|
|
|
138
|
-
Keep `.env` or `.env.local` up to date with every key under `
|
|
151
|
+
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
152
|
|
|
140
153
|
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
154
|
|
|
142
|
-
When `neon checkout` _creates_ a new branch and a `neon.ts` is present, it applies the policy automatically.
|
|
155
|
+
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).
|
|
156
|
+
|
|
157
|
+
### Native binaries and custom builds
|
|
158
|
+
|
|
159
|
+
The default deploy bundles `source` into one `index.mjs`, which cannot hold a compiled binary. Ship one as a separate archive file:
|
|
160
|
+
|
|
161
|
+
- npm package with a Node addon (`sharp`): `externalPackages: ["sharp"]`. The deploy installs its linux-arm64 glibc build and copies the files in.
|
|
162
|
+
- Your own build output (`.node`, `.so`, `.wasm`, data files): `bundler: "none"` with a prebuilt directory, or an inline `bundler: async (fn) => ({ "index.mjs": …, "bin/tool": … })`.
|
|
163
|
+
- A standalone executable you spawn: ship it as above, then copy it to `/run` and `chmod 755` it at startup. Files in `/opt/function` arrive as mode `644` on a read-only filesystem, and `/tmp` is `noexec`.
|
|
164
|
+
|
|
165
|
+
Runtime target, pros and cons, working snippets, and size limits: [references/native-binaries.md](references/native-binaries.md).
|
|
143
166
|
|
|
144
167
|
## Neon Infrastructure as Code (`neon.ts`)
|
|
145
168
|
|
|
146
|
-
The `
|
|
169
|
+
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
170
|
|
|
148
171
|
```bash
|
|
149
172
|
neon config status # print the branch's live config (deployed functions)
|
|
@@ -151,17 +174,15 @@ neon config plan # dry-run diff of what apply would change
|
|
|
151
174
|
neon config apply --env <file> # bundle + deploy the declared functions (neon deploy is an alias; pass --env when Function env reads process.env)
|
|
152
175
|
```
|
|
153
176
|
|
|
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.
|
|
177
|
+
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
178
|
|
|
156
179
|
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
180
|
|
|
158
181
|
```typescript
|
|
159
182
|
export default defineConfig({
|
|
160
|
-
|
|
161
|
-
functions: { todos: { name: "todo api", source: "src/index.ts" } },
|
|
162
|
-
},
|
|
183
|
+
functions: { todos: { name: "todo api", source: "src/index.ts" } },
|
|
163
184
|
branch: (branch) => ({
|
|
164
|
-
|
|
185
|
+
functions: { todos: { runtime: "nodejs24" } },
|
|
165
186
|
}),
|
|
166
187
|
});
|
|
167
188
|
```
|
|
@@ -176,6 +197,7 @@ Neon injects branch-scoped connection strings and service URLs at runtime — yo
|
|
|
176
197
|
| `DATABASE_URL` | Pooled connection string. Use for most queries. Present only if the branch has Postgres. |
|
|
177
198
|
| `DATABASE_URL_UNPOOLED` | Direct connection. Use for migrations, `LISTEN`/`NOTIFY`, multi-round-trip transactions. |
|
|
178
199
|
| `NEON_AUTH_BASE_URL` | Present when Neon Auth is enabled on the branch. |
|
|
200
|
+
| `NEON_AUTH_JWKS_URL` | Present when Neon Auth is enabled on the branch. JWKS for verifying Managed Auth JWTs. |
|
|
179
201
|
| `NEON_DATA_API_URL` | Present when the Data API is enabled on the branch. |
|
|
180
202
|
|
|
181
203
|
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,11 +257,11 @@ Functions are long-running but **still serverless** — they are a request/respo
|
|
|
235
257
|
- **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
258
|
- **`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
259
|
- **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
|
|
260
|
+
- **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
261
|
|
|
240
262
|
## Functions as an Agent Backend (Next.js and Similar Frameworks)
|
|
241
263
|
|
|
242
|
-
A 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)).
|
|
264
|
+
A 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)). Proxying that stream through a Next.js route handler, Remix/SvelteKit/Nuxt action, or similar hosted on Vercel, Netlify, and the like **cuts the stream when it exceeds that host's configured duration or transport limits**, even though the Function would keep going. Keep the client-direct JWT path below as the default. A streaming-compatible proxy (HTTP-triggered Cloudflare Worker, after you verify the stream) is the public-consumer exception in [Production hardening](references/production-hardening.md).
|
|
243
265
|
|
|
244
266
|
**Building the agent itself.** The [Vercel AI SDK](https://ai-sdk.dev) and [Mastra](https://mastra.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/ai-sdk.md](https://neon.com/docs/ai/skills/neon-functions/references/ai-sdk.md); for the Mastra equivalent with built-in tracing, see [references/mastra-studio.md](https://neon.com/docs/ai/skills/neon-functions/references/mastra-studio.md).
|
|
245
267
|
|
|
@@ -250,20 +272,23 @@ Browser ──(Authorization: Bearer <JWT>)──▶ Neon Function (agent)
|
|
|
250
272
|
Browser ──▶ your app backend ──▶ Neon Function ❌ host cuts the stream
|
|
251
273
|
```
|
|
252
274
|
|
|
253
|
-
-
|
|
254
|
-
-
|
|
275
|
+
- 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.
|
|
276
|
+
- 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`.
|
|
277
|
+
- Managed Auth with `SupabaseAuthAdapter()`: that client has no `.token()`. Use `getSession()`, then `data.session.access_token`. Same JWKS/issuer as above.
|
|
278
|
+
- 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.
|
|
279
|
+
- 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.
|
|
280
|
+
- 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
281
|
- Add **CORS** so the browser can reach it (handle `OPTIONS`, set `Access-Control-Allow-Origin`/`-Headers`).
|
|
256
282
|
|
|
257
283
|
> [!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
|
|
284
|
+
> 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. Browser callers use short-lived user tokens. Server or proxy origin secrets (`X-Secret`) stay server-side; see [Production hardening](references/production-hardening.md).
|
|
259
285
|
|
|
260
286
|
```typescript
|
|
261
287
|
// src/index.ts — verify the caller before doing any work
|
|
262
288
|
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
263
289
|
|
|
264
|
-
const jwks = createRemoteJWKSet(
|
|
265
|
-
|
|
266
|
-
);
|
|
290
|
+
const jwks = createRemoteJWKSet(new URL(process.env.NEON_AUTH_JWKS_URL!));
|
|
291
|
+
const issuer = new URL(process.env.NEON_AUTH_BASE_URL!).origin;
|
|
267
292
|
|
|
268
293
|
export default {
|
|
269
294
|
async fetch(request: Request) {
|
|
@@ -277,24 +302,33 @@ export default {
|
|
|
277
302
|
headers: cors(request),
|
|
278
303
|
});
|
|
279
304
|
}
|
|
305
|
+
let userId: string;
|
|
280
306
|
try {
|
|
281
|
-
const { payload } = await jwtVerify(auth.slice(7), jwks, {
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
307
|
+
const { payload } = await jwtVerify(auth.slice(7), jwks, { issuer });
|
|
308
|
+
if (!payload.sub) {
|
|
309
|
+
return new Response("Unauthorized", {
|
|
310
|
+
status: 401,
|
|
311
|
+
headers: cors(request),
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
userId = payload.sub;
|
|
287
315
|
} catch {
|
|
288
316
|
return new Response("Unauthorized", {
|
|
289
317
|
status: 401,
|
|
290
318
|
headers: cors(request),
|
|
291
319
|
});
|
|
292
320
|
}
|
|
321
|
+
// Authorize resource access by userId, then run the agent scoped to that user.
|
|
322
|
+
// ... return result.toUIMessageStreamResponse({ headers: cors(request) })
|
|
293
323
|
},
|
|
294
324
|
};
|
|
295
325
|
```
|
|
296
326
|
|
|
297
|
-
|
|
327
|
+
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
|
|
328
|
+
|
|
329
|
+
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.
|
|
330
|
+
|
|
331
|
+
Persist anything you need to keep (generated images, history) in Postgres — module state doesn't survive eviction.
|
|
298
332
|
|
|
299
333
|
## WebSocket Servers
|
|
300
334
|
|
|
@@ -454,7 +488,9 @@ async function poll() {
|
|
|
454
488
|
// Seed from the latest id so a fresh isolate sends only new rows, not the whole table, then poll.
|
|
455
489
|
pool
|
|
456
490
|
.query("SELECT coalesce(max(id), 0)::text AS id FROM events")
|
|
457
|
-
.then((seed) => {
|
|
491
|
+
.then((seed) => {
|
|
492
|
+
lastId = seed.rows[0].id;
|
|
493
|
+
})
|
|
458
494
|
.catch((err) => console.error("[seed]", err))
|
|
459
495
|
.finally(() => setInterval(poll, 1000).unref?.());
|
|
460
496
|
```
|
|
@@ -571,6 +607,12 @@ export default {
|
|
|
571
607
|
|
|
572
608
|
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
609
|
|
|
610
|
+
## Function Triggers
|
|
611
|
+
|
|
612
|
+
A Function Trigger POSTs JSON to your function on a cron (`schedule`) or when an object is created in Object Storage (`storage_object_created`). Declare it in `neon.ts`, apply with `neon deploy`, and authenticate the delivery with `parseTriggerDelivery` (`@neon/functions/triggers`). `parseTrigger` (Hono) and `parseTriggerInvocation` stay schedule-only. Prefer `neon.ts`; CLI and the Neon MCP trigger tools (`list_triggers`, `create_trigger`, …) are the backup.
|
|
613
|
+
|
|
614
|
+
Trigger routes must not require a user JWT or `X-Secret`; Neon POSTs to the native URL without those. Production caller shapes: [references/production-hardening.md](references/production-hardening.md). Full field list, CLI, MCP, payload, inheritance, and both handler shapes: [references/function-triggers.md](references/function-triggers.md).
|
|
615
|
+
|
|
574
616
|
## MCP Servers
|
|
575
617
|
|
|
576
618
|
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.
|
|
@@ -585,7 +627,7 @@ app.all("/mcp", async (c) => {
|
|
|
585
627
|
});
|
|
586
628
|
```
|
|
587
629
|
|
|
588
|
-
Because the function's URL is public, **authenticate before connecting the transport** — [Better Auth](https://better-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 / session-JWT check for your own callers. [references/mcp.md](https://neon.com/docs/ai/skills/neon-functions/references/mcp.md) has the full pattern — server with Postgres-backed tools via Drizzle, both Better Auth auth options, and testing with `mcporter` / `add-mcp`.
|
|
630
|
+
Because the function's URL is public, **authenticate before connecting the transport** — [Better Auth](https://better-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 / session-JWT check for your own callers. Public-consumer edge protection: [references/production-hardening.md](references/production-hardening.md). [references/mcp.md](https://neon.com/docs/ai/skills/neon-functions/references/mcp.md) has the full pattern — server with Postgres-backed tools via Drizzle, both Better Auth auth options, and testing with `mcporter` / `add-mcp`.
|
|
589
631
|
|
|
590
632
|
## Integrations and Observability
|
|
591
633
|
|
|
@@ -616,4 +658,9 @@ The Neon documentation is the source of truth and Functions is evolving rapidly,
|
|
|
616
658
|
- https://neon.com/docs/compute/functions/environment-variables.md
|
|
617
659
|
- https://neon.com/docs/compute/functions/reference/neon-ts.md
|
|
618
660
|
- https://neon.com/docs/compute/functions/reference/runtime-limits.md
|
|
619
|
-
- https://neon.com/docs/compute/functions/
|
|
661
|
+
- https://neon.com/docs/compute/functions/authentication.md
|
|
662
|
+
- https://neon.com/docs/compute/functions/custom-domains.md
|
|
663
|
+
- https://neon.com/docs/cli/triggers.md
|
|
664
|
+
- [references/function-triggers.md](references/function-triggers.md)
|
|
665
|
+
- [references/native-binaries.md](references/native-binaries.md)
|
|
666
|
+
- [references/production-hardening.md](references/production-hardening.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
|
```
|