@neon/skills 3.0.8 → 3.0.11
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/package.json +1 -1
- package/plugin.json +1 -1
- package/skills/neon/SKILL.md +12 -10
- package/skills/neon-ai-gateway/SKILL.md +4 -4
- package/skills/neon-auth/SKILL.md +8 -6
- package/skills/neon-auth/references/oauth-server.md +2 -2
- package/skills/neon-realtime/SKILL.md +3 -2
- package/skills/neon-realtime/references/mutations.md +8 -6
- package/skills/neon-realtime/references/queries.md +12 -8
- package/skills/neon-realtime/references/reactivity.md +11 -9
- package/skills/neon-realtime/references/ssr.md +4 -2
- package/skills/neon-realtime/references/subscribing.md +35 -31
package/package.json
CHANGED
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
|
|
3
3
|
"name": "neon-postgres",
|
|
4
|
-
"version": "3.0.
|
|
4
|
+
"version": "3.0.11",
|
|
5
5
|
"description": "Manage your Neon backend with the Neon agent skills and the Neon MCP Server: Lakebase Postgres, Managed Better Auth, Realtime, Object Storage, Functions, the Data API, and AI Gateway",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Neon",
|
package/skills/neon/SKILL.md
CHANGED
|
@@ -206,10 +206,10 @@ pnpm add -g neon # pnpm
|
|
|
206
206
|
|
|
207
207
|
For full CLI installation options, see https://neon.com/docs/cli/install.md
|
|
208
208
|
|
|
209
|
-
Then inspect credentials without printing secrets. `NEON_API_KEY
|
|
209
|
+
Then inspect credentials without printing secrets. `NEON_API_KEY`, or the active `neon profile list -o json` row (`active: "*"`) with an `account` other than `-`, is an account. A `DEFAULT` row with `account: "-"` and `file: "missing"` is not.
|
|
210
210
|
|
|
211
211
|
- Credentials already available: reuse them. Do not launch a browser.
|
|
212
|
-
- A human needs to sign in: they run `neon login` (`neon auth` is an alias). An unattended agent must not launch browser authentication.
|
|
212
|
+
- A human needs to sign in: they run `neon login` (`neon auth` is an alias). An unattended agent must not launch browser authentication; with no credentials and nobody to finish a browser sign-in, it takes the Claimable Neon path below.
|
|
213
213
|
- No account yet: follow [Starting without a Neon account](#starting-without-a-neon-account) for the Claimable Neon path.
|
|
214
214
|
|
|
215
215
|
### Combined setup: `neon init`
|
|
@@ -311,7 +311,9 @@ neon bootstrap
|
|
|
311
311
|
|
|
312
312
|
## Starting without a Neon account
|
|
313
313
|
|
|
314
|
-
If the Getting Started account check found credentials, use them. If
|
|
314
|
+
If the Getting Started account check found credentials, use them. If those credentials fail to authenticate, stop and ask the user to sign in (`neon auth`). Do not create a Claimable project as a substitute for a failed existing account.
|
|
315
|
+
|
|
316
|
+
If the check found no credentials and nobody can finish a browser sign-in (an unattended run, or a command waits on `Awaiting authentication in web browser`), stop waiting and create the database with `npx neon@latest claim create`. It needs no Neon account, and the user claims the project later from the claim link; the next paragraph and its reference cover the flow. Use a Neon API key instead only when the user says they already have one; they set it as `NEON_API_KEY` in the session environment rather than pasting it into chat.
|
|
315
317
|
|
|
316
318
|
If there is no Neon account yet, follow [references/claimable-neon.md](https://neon.com/docs/ai/skills/neon/references/claimable-neon.md). Do not run `neon init --agent` or `neon auth` on this path; those need a human Neon account. If `neon claim` is missing, the reference has the REST fallback. Unclaimed projects expire at `project_expires_at` (72 hours today). Claim codes expire in `expires_in` (15 minutes today). Functions, Object Storage, and AI Gateway report `requires_claim` before a human claims the project; report that and keep the denied capabilities. Add Auth with `neon.ts` and `neon deploy` when login is requested and no existing provider should be preserved. Add the Data API only for PostgREST / Supabase database-client compatibility or a migration that already depends on it.
|
|
317
319
|
|
|
@@ -370,7 +372,7 @@ neon config plan # dry-run diff of what apply would change (read-only)
|
|
|
370
372
|
neon deploy --env <file> # apply neon.ts. Pass --env when Function env reads process.env. Alias for `neon config apply`
|
|
371
373
|
```
|
|
372
374
|
|
|
373
|
-
`apply` / `deploy` provision the declared services **and then pull the branch's env into your local `.env.local
|
|
375
|
+
`apply` / `deploy` provision the declared services **and then pull the branch's env into your local env file** (`.env` if it exists, otherwise `.env.local`) (e.g. `Pulled 5 Neon variables into .env.local: DATABASE_URL, …`), so your local env always matches what's deployed.
|
|
374
376
|
|
|
375
377
|
### Function env and `neon deploy`
|
|
376
378
|
|
|
@@ -460,7 +462,7 @@ Neon branches enable a branch-first development flow, which we recommend when us
|
|
|
460
462
|
Create a Neon branch any time you would create a git branch. Use the following commands if you have CLI access:
|
|
461
463
|
|
|
462
464
|
- `neon checkout <branch-name>` — Pins an existing branch by updating only the branch pointer in `.neon`. Pass `--create` to create a missing **name** (`neon checkout dev --create`). Run without a name for an interactive picker. It does not touch code or local Postgres.
|
|
463
|
-
- `neon env pull` — Fetches the current branch's Neon environment variables into your `.env`. **`link` and `checkout` run this for you by default**, so you rarely call it directly.
|
|
465
|
+
- `neon env pull` — Fetches the current branch's Neon environment variables into your local env file (`.env` if it exists, otherwise `.env.local`). **`link` and `checkout` run this for you by default**, so you rarely call it directly.
|
|
464
466
|
- `neon diff` — Shows the schema diff between the child branch and its parent. Run this to see what changes have been made to the schema since the last branch was created and before you commit your changes.
|
|
465
467
|
|
|
466
468
|
```bash
|
|
@@ -468,7 +470,7 @@ neon link # once; also pulls the linked branch's env
|
|
|
468
470
|
neon checkout dev-add-search --create # per feature; also pulls the branch's env
|
|
469
471
|
```
|
|
470
472
|
|
|
471
|
-
Because `link` and `checkout` pull env by default, the branch's `DATABASE_URL` lands in your local
|
|
473
|
+
Because `link` and `checkout` pull env by default, the branch's `DATABASE_URL` lands in your local env file automatically — build against it, then `checkout` the next branch and repeat. As the agent, drive this loop yourself: run `checkout` between tasks.
|
|
472
474
|
|
|
473
475
|
### How checkout composes with neon.ts
|
|
474
476
|
|
|
@@ -510,14 +512,14 @@ Enroll in the [Neon Agent Program](https://neon.com/programs/agents.md) only whe
|
|
|
510
512
|
|
|
511
513
|
Report issues that Neon can fix upstream, such as incorrect guidance, broken templates, missing instructions, or defects in Neon tooling and APIs. Do not report errors caused only by the user's code, environment, permissions, or configuration unless Neon guidance or these agent skills caused the issue or failed to explain it.
|
|
512
514
|
|
|
513
|
-
Diagnose the issue and fully help the user first.
|
|
515
|
+
Diagnose the issue and fully help the user first. Feedback must not delay or replace helping the user. After the task is complete, draft one report with the cause and workaround when known, show it to the user, and ask whether to send it to Neon. Send it only if they say yes.
|
|
516
|
+
|
|
517
|
+
After a yes, run `neon feedback --help`. If it succeeds, send the report with:
|
|
514
518
|
|
|
515
519
|
```bash
|
|
516
520
|
neon feedback --message "Describe what failed, including the command and sanitized error message."
|
|
517
521
|
```
|
|
518
522
|
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
The goal is to improve the user's experience without interrupting or getting in the way of their current work. If submission fails, do not retry. Finish the user's task normally.
|
|
523
|
+
Otherwise use the Neon MCP `send_feedback` tool when it is present. If neither is available, skip feedback. Do not install, upgrade, authenticate, or configure tooling only to send feedback. If submission fails, do not retry.
|
|
522
524
|
|
|
523
525
|
**Never send secrets or sensitive data.** Remove credentials, tokens, API keys, passwords, personal or customer data, and confidential project details from the report. Send only the issue report described above; do not collect or infer analytics.
|
|
@@ -65,7 +65,7 @@ The AI Gateway is available on every Neon plan, including Free, and draws down p
|
|
|
65
65
|
|
|
66
66
|
### Enabling the gateway: credits and model access
|
|
67
67
|
|
|
68
|
-
The AI Gateway is credential-gated rather than a provisioning step. `neon
|
|
68
|
+
The AI Gateway is credential-gated rather than a provisioning step. On every plan, `neon env pull` resolves the branch credential and writes `NEON_AI_GATEWAY_BASE_URL` and `NEON_AI_GATEWAY_TOKEN` when `neon.ts` declares `aiGateway` or there is no `neon.ts`. With `aiGateway` declared, `neon config apply` / `deploy`, `neon link`, and `neon checkout` write them too. Whether the account can serve a model is decided per request:
|
|
69
69
|
|
|
70
70
|
- **No card and credits yet → no model is enabled.** An account that hasn't added a card and bought AI Gateway credits, which includes every new Free account, gets every catalog model from `GET /v1/models` with `enabled: false`, `unavailable_reason: "paid_plan_required"`, and a `recovery_url` pointing at the organization's Billing page, and a request returns `403` with the same `unavailable_reason`. Despite the name, the fix is adding a card and buying credits, not upgrading the plan. `neon env pull` (and the env pull bundled into `apply` / `deploy` / `checkout`) warns when no model is enabled, names the reason, and links the `recovery_url`.
|
|
71
71
|
- **Locked models.** `neon env pull` also warns when some models are enabled but no flagship model (e.g. Anthropic Opus, OpenAI Codex / `*-pro`) is among them, and links to the branch's AI Gateway page in the Neon Console (`https://console.neon.tech/app/projects/<project-id>/branches/<branch-id>/ai-gateway`). That page lists locked models under **Some models are restricted**, grouped by reason, each with its fix: **Add a card** and buy credits, **Add credits** for prepaid credits, or Support for an account restriction or a model not available to the account. After the user buys credits, models unlock once Neon confirms access. No CLI warning does not mean every model is enabled; check the model's `enabled` value. See https://neon.com/docs/ai-gateway/troubleshooting.md.
|
|
@@ -98,7 +98,7 @@ neon config plan # dry-run diff of what apply would change
|
|
|
98
98
|
neon config apply # enable the gateway on the branch (neon deploy is an alias)
|
|
99
99
|
```
|
|
100
100
|
|
|
101
|
-
The gateway is **branch-scoped**: each branch gets its own gateway host. When a `neon.ts` is present, `neon checkout` applies the policy as it _creates_ a branch, so a fresh preview/CI branch comes up with the gateway already enabled. Checking out an _existing_ branch doesn't reconcile it — run `neon deploy` to apply changes.
|
|
101
|
+
The gateway is **branch-scoped**: each branch gets its own gateway host. When a `neon.ts` is present, `neon checkout` applies the policy as it _creates_ a branch, so a fresh preview/CI branch comes up with the gateway already enabled. Checking out an _existing_ branch doesn't reconcile it — run `neon deploy` to apply changes. When `neon.ts` declares `aiGateway`, provisioning (`config apply` / `deploy`), `link`, and `checkout` also pull the branch's gateway credentials into your local env file (`.env` if it exists, otherwise `.env.local`), so local runs hit the same branch gateway as the deployed function (no manual `env pull` needed).
|
|
102
102
|
|
|
103
103
|
## Environment Variables
|
|
104
104
|
|
|
@@ -315,8 +315,8 @@ curl "$NEON_AI_GATEWAY_BASE_URL/v1/models" \
|
|
|
315
315
|
|
|
316
316
|
**Getting the credentials for the request.** Both values come from the same branch-scoped Neon credential the gateway uses everywhere else — you never manage a provider key:
|
|
317
317
|
|
|
318
|
-
- **Provision via `neon.ts` (recommended).** Enable `aiGateway` in `neon.ts` and run `neon deploy` (or `neon config apply`). Provisioning, `neon link`, and `neon checkout` pull `NEON_AI_GATEWAY_TOKEN` + `NEON_AI_GATEWAY_BASE_URL` into your local `.env.local
|
|
319
|
-
- **Pull into the environment via CLI.** `neon env pull` writes the two vars to `.env`/`.env.local`, or `neon-env run -- <cmd>` injects
|
|
318
|
+
- **Provision via `neon.ts` (recommended).** Enable `aiGateway` in `neon.ts` and run `neon deploy` (or `neon config apply`). Provisioning, `neon link`, and `neon checkout` pull `NEON_AI_GATEWAY_TOKEN` + `NEON_AI_GATEWAY_BASE_URL` into your local env file (`.env` if it exists, otherwise `.env.local`); inside a deployed Neon Function they're injected automatically. See **Setup** and **Environment Variables** above.
|
|
319
|
+
- **Pull into the environment via CLI.** `neon env pull` writes the two vars to `.env`/`.env.local`. With a `neon.ts`, a bare `neon env pull` includes them only when `aiGateway` is declared. Without a `neon.ts`, a bare `neon env pull` includes them, but the pulls bundled into `init`, `link`, and `checkout` leave them out and remove ones an earlier pull wrote, so run `neon env pull` again after those commands, or declare `aiGateway` in `neon.ts` so every pull keeps them. `neon-env run -- <cmd>` injects the vars at runtime without a file and needs a `neon.ts` that declares `aiGateway`.
|
|
320
320
|
- **Provision via the Console UI.** Enable the AI Gateway on the branch in the Neon Console and copy the branch's gateway base URL and a Neon credential (token) from the project's connection/credentials view.
|
|
321
321
|
|
|
322
322
|
Any Neon credential (`nt_live_...`) valid for the branch works as the bearer token; `NEON_AI_GATEWAY_BASE_URL` is the bare branch host (no path).
|
|
@@ -42,7 +42,7 @@ Inspect existing identity and the required login features before provisioning. A
|
|
|
42
42
|
| User asked to migrate from Supabase Auth | Managed Better Auth. [Supabase Auth](#supabase-auth). Moving only Postgres or adding a Function keeps Supabase Auth. |
|
|
43
43
|
| Clerk, Auth.js, Supabase Auth, or another working IdP | Keep it unless the user asks to migrate. |
|
|
44
44
|
|
|
45
|
-
Google, GitHub, Microsoft, Vercel, and
|
|
45
|
+
Google, GitHub, Microsoft, Vercel, Apple, and Discord social OAuth are offered on Managed Auth. They are not a reason to leave Managed Auth. Microsoft, Apple, and Discord need your own credentials: [Apple, Microsoft, and Discord OAuth](#apple-microsoft-and-discord-oauth). Making Neon Auth the OAuth server for your own MCP server or third-party OAuth clients is supported: [references/oauth-server.md](references/oauth-server.md). Other OAuth providers, generic OAuth, MFA, passkeys, API keys, SSO, custom plugins, hooks, and custom JWT claims are the [plugin matrix](#plugin-support) check.
|
|
46
46
|
|
|
47
47
|
Before enabling Managed Auth, confirm the project is on AWS and does not use IP Allow or Private Networking. Leave those protections in place.
|
|
48
48
|
|
|
@@ -107,14 +107,14 @@ A required plugin on the self-managed path is verified in that app's Better Auth
|
|
|
107
107
|
|
|
108
108
|
## Plugin support
|
|
109
109
|
|
|
110
|
-
Checked 2026-10-30 against https://neon.com/docs/auth/guides/plugins.md, https://neon.com/docs/auth/guides/plugins/oauth-provider.md, https://neon.com/docs/auth/roadmap.md, and the `@neon/auth` client plugin list. Re-fetch those pages if this skill may be stale. An unlisted upstream plugin needs a live check; do not treat absence from this table as a dated roadmap item.
|
|
110
|
+
Checked 2026-10-30 against https://neon.com/docs/auth/guides/plugins.md, https://neon.com/docs/auth/guides/plugins/oauth-provider.md, https://neon.com/docs/auth/roadmap.md, and the `@neon/auth` client plugin list. Discord row checked 2026-11-11 against https://neon.com/docs/reference/api/auth/add-branch-neon-auth-oauth-provider.md; Discord: see [Apple, Microsoft, and Discord OAuth](#apple-microsoft-and-discord-oauth). Re-fetch those pages if this skill may be stale. An unlisted upstream plugin needs a live check; do not treat absence from this table as a dated roadmap item.
|
|
111
111
|
|
|
112
112
|
"Not exposed" means the Managed SDK/UI contract. It is not a claim that every raw server request was tested.
|
|
113
113
|
|
|
114
114
|
| Feature | Managed Auth | Boundary |
|
|
115
115
|
| --- | --- | --- |
|
|
116
116
|
| Email/password | Supported | `signUp.email`, `signIn.email` |
|
|
117
|
-
| Social OAuth (Google, GitHub, Microsoft, Vercel, Apple) | Supported | `signIn.social`. Shared Google credentials are for development; production and GitHub/Vercel need your own OAuth apps. Microsoft and
|
|
117
|
+
| Social OAuth (Google, GitHub, Microsoft, Vercel, Apple, Discord) | Supported | `signIn.social`. Shared Google credentials are for development; production and GitHub/Vercel need your own OAuth apps. Microsoft, Apple, and Discord always need your own. Discord: see [details](#apple-microsoft-and-discord-oauth). https://neon.com/docs/auth/guides/setup-oauth.md |
|
|
118
118
|
| Admin | Supported | Admin session required. Plugin customization is on the roadmap. |
|
|
119
119
|
| Email OTP | Supported | Managed delivery. `emailOtp.sendVerificationOtp`, `signIn.emailOtp`. |
|
|
120
120
|
| Magic Link | Supported | Enable on the branch (off by default). `signIn.magicLink`. |
|
|
@@ -123,7 +123,7 @@ Checked 2026-10-30 against https://neon.com/docs/auth/guides/plugins.md, https:/
|
|
|
123
123
|
| Open API | Supported | Server routes `/reference` and `/open-api/generate-schema`. |
|
|
124
124
|
| Phone Number | Supported with constraints | Browser client: existing users link a number, then sign in; no phone-first signup; own SMS webhook; custom UI. Next.js `auth.handler()` forwards the catch-all path, including phone OTP. A missing `auth.phoneNumber` server method is a missing typed helper, not a proxy rejection. https://neon.com/docs/auth/guides/plugins/phone-number.md |
|
|
125
125
|
| MFA / Two-Factor | Roadmap | Unavailable on Managed Auth. If required: [self-managed.md](references/self-managed.md), after confirming the installed Better Auth version. |
|
|
126
|
-
| Passkey, API Key, Generic OAuth, One Tap, Multi Session | Not exposed by Managed SDK/UI | If required: [self-managed.md](references/self-managed.md). Generic OAuth is not Google/GitHub/Microsoft/Vercel/Apple social sign-in. |
|
|
126
|
+
| Passkey, API Key, Generic OAuth, One Tap, Multi Session | Not exposed by Managed SDK/UI | If required: [self-managed.md](references/self-managed.md). Generic OAuth is not Google/GitHub/Microsoft/Vercel/Apple/Discord social sign-in. |
|
|
127
127
|
| OAuth Provider (OAuth server, MCP auth) | Supported (beta) | Neon Auth is the OAuth 2.1 / OIDC server for your MCP server or third-party OAuth clients. You host the login and consent pages; no client credentials grant. See [references/oauth-server.md](references/oauth-server.md). |
|
|
128
128
|
| SSO / SAML | Not listed or exposed | If required: [self-managed.md](references/self-managed.md), after confirming the installed Better Auth version. |
|
|
129
129
|
|
|
@@ -131,13 +131,15 @@ The default Managed client method is `getAnonymousToken()`. That JWT is a Neon a
|
|
|
131
131
|
|
|
132
132
|
Trusted domains and webhooks are Neon settings, not installable Better Auth plugins.
|
|
133
133
|
|
|
134
|
-
## Apple and
|
|
134
|
+
## Apple, Microsoft, and Discord OAuth
|
|
135
135
|
|
|
136
|
-
|
|
136
|
+
Apple, Microsoft, and Discord reject shared credentials. Add them with your own via `neon neon-auth oauth-provider add|update` (Console and API work too). A multi-line secret goes in a file with `--oauth-client-secret-file`, not inline.
|
|
137
137
|
|
|
138
138
|
- **Apple**: `client_id` is the Services ID, `client_secret` is the full `.p8` private key. Also pass `--apple-team-id` and `--apple-key-id` (10 characters). Neon Auth signs the client-secret JWT itself, so there is nothing to rotate. Rotating the key needs the new `--apple-key-id` in the same update. The return URL must be HTTPS (`https://<auth host>/<db>/auth/callback/apple`); Apple rejects localhost, so test through a tunnel or a deployed preview.
|
|
139
139
|
- **Microsoft**: `client_id` and `client_secret` from the Entra app registration. `--microsoft-tenant-id` is optional: `common` (default), `organizations`, `consumers`, a tenant GUID, or a domain. The redirect URI is `<base_url>/callback/microsoft`.
|
|
140
140
|
- **Microsoft email verification**: an email counts as verified only when the ID token carries `xms_edov` = true and `acct` = 0. Add `xms_edov` and `acct` as optional ID-token claims in Entra. Without them, a same-email existing user gets `account_not_linked`, `link-social` fails with `unable_to_link_account`, and new users stay unverified.
|
|
141
|
+
- **Discord**: Always needs your own Discord application `client_id` and `client_secret` (shared is rejected on add and update). Better Auth only; legacy Stack Auth returns 422. Scopes are `identify` and `email`. Redirect URI `<base_url>/callback/discord`. With Neon CLI 9.5.0 or later, add or update it like Microsoft using `--provider-id discord`, `--oauth-client-id`, and `--oauth-client-secret-file` (preferred to keep the secret out of shell history). Delete it with `neon neon-auth oauth-provider delete --provider-id discord`. Older CLIs can use MCP `auth.oauthProviders.add|update|delete` or the API: https://neon.com/docs/reference/api/auth/add-branch-neon-auth-oauth-provider.md
|
|
142
|
+
- **Discord email verification**: an email counts as verified only when Discord's `verified` is the boolean `true`. An unverified Discord email cannot auto-link to an existing same-email user, and a new user from it is stored as unverified. A Discord account with no email fails with `email_not_found`.
|
|
141
143
|
|
|
142
144
|
## Trusted domains
|
|
143
145
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Use this page when the request is "let MCP clients sign in my users", "protect my MCP server with OAuth", or "let another app or OAuth client call my API on behalf of my users". Managed Better Auth is the OAuth 2.1 / OIDC authorization server (the OAuth provider plugin, beta, available to all Managed projects). Do not move to self-managed Better Auth for this, and keep the app's existing login method.
|
|
4
4
|
|
|
5
|
-
"OAuth server" and "OAuth clients" here are not the social providers (
|
|
5
|
+
"OAuth server" and "OAuth clients" here are not the social sign-in providers (`signIn.social`). Those sign users in to Neon Auth. This page makes Neon Auth issue tokens to other apps.
|
|
6
6
|
|
|
7
7
|
- Docs: https://neon.com/docs/auth/guides/plugins/oauth-provider.md
|
|
8
8
|
- Configuration is per branch: each branch has its own issuer, clients, and settings.
|
|
@@ -176,7 +176,7 @@ Report any step you could not run.
|
|
|
176
176
|
## Do NOT
|
|
177
177
|
|
|
178
178
|
- Do not move to self-managed Better Auth or the Better Auth MCP plugin for this. Managed supports it.
|
|
179
|
-
- Do not confuse this with `neon neon-auth oauth-provider` (social
|
|
179
|
+
- Do not confuse this with `neon neon-auth oauth-provider` (`signIn.social` providers) or Generic OAuth.
|
|
180
180
|
- Do not call `auth.oauth.resume()`, `getConsentRequest()`, or any resume helper. Use `oauth2.continue`, `oauth2.publicClient`, and `oauth2.consent`.
|
|
181
181
|
- Do not put client secrets, or Neon API keys, in browser or mobile code.
|
|
182
182
|
- Do not skip `iss` and `aud` checks, or trust a user id from tool input instead of `sub`.
|
|
@@ -154,6 +154,7 @@ Migrating from Electric: Realtime is a drop-in replacement for Electric's role i
|
|
|
154
154
|
## Setup
|
|
155
155
|
|
|
156
156
|
- **New app:** `neon bootstrap my-app --template realtime-react`, then `neon deploy` in `my-app`.
|
|
157
|
+
- **Existing app:** follow the [Next.js example](https://neon.com/docs/realtime/examples/nextjs.md). Its setup declares Realtime with `neon config add realtime` and runs `neon deploy`, and [Adapt the example to your app](https://neon.com/docs/realtime/examples/nextjs.md#adapt-the-example-to-your-app) covers raw SQL with `createRealtime()` and no adapter, and apps with their own auth or none.
|
|
157
158
|
- **Enable** it on the linked branch with [`neon realtime enable --allowed-origin <app origin>`](https://neon.com/docs/cli/realtime.md), or declare [`preview: { realtime: true }`](https://neon.com/docs/reference/neon-ts.md#realtime) in `neon.ts` (`neon config add realtime`) and run `neon deploy`. Child branches inherit it. It's unavailable on Claimable projects until claimed, or outside the [supported regions](https://neon.com/docs/realtime/overview.md#which-regions-is-it-enabled-in).
|
|
158
159
|
- **Tables** need a [stable replica identity](references/queries.md#table-requirements); a primary key is enough. Leave [row-level security](references/queries.md#why-not-row-level-security) off on every table a live query reads: Realtime rejects those subscriptions with `unsupported query: row security`. For per-user data, authorize in the sealed query instead (see below).
|
|
159
160
|
- **Environment:** `neon env pull --service postgres --service realtime` writes `DATABASE_URL`, `NEON_REALTIME_URL` and `NEON_REALTIME_SECRET`. Expose only the URL to the browser, under your framework's public prefix (like `VITE_`). `url` options take `NEON_REALTIME_URL`; `db` takes the database name from `DATABASE_URL`.
|
|
@@ -200,7 +201,7 @@ Read [references/ssr.md](references/ssr.md) before rendering live queries on the
|
|
|
200
201
|
| Beta scope, regions, pricing, FAQ, other systems | [Overview](https://neon.com/docs/realtime/overview.md) |
|
|
201
202
|
| Architecture and consistency | [How it works](https://neon.com/docs/realtime/how-it-works.md) |
|
|
202
203
|
| A first live query | [Quickstart](https://neon.com/docs/realtime/quickstart.md) |
|
|
203
|
-
| Every SDK export | [TypeScript SDK
|
|
204
|
-
| Full-stack apps with auth and SSR | [Next.js](https://neon.com/docs/realtime/examples/nextjs.md), [TanStack](https://neon.com/docs/realtime/examples/tanstack.md) |
|
|
204
|
+
| Every SDK export, one page per module | [TypeScript SDK overview](https://neon.com/docs/realtime/sdks/typescript.md): [Backend](https://neon.com/docs/realtime/sdks/typescript/backend.md), [Client](https://neon.com/docs/realtime/sdks/typescript/client.md), [React](https://neon.com/docs/realtime/sdks/typescript/react.md), [TanStack DB](https://neon.com/docs/realtime/sdks/typescript/tanstack-db.md), [Drizzle and Drizzle client](https://neon.com/docs/realtime/sdks/typescript/drizzle.md), [Kysely](https://neon.com/docs/realtime/sdks/typescript/kysely.md) |
|
|
205
|
+
| Full-stack apps with auth and SSR, or Realtime in an existing Next.js app | [Next.js](https://neon.com/docs/realtime/examples/nextjs.md), [TanStack](https://neon.com/docs/realtime/examples/tanstack.md) |
|
|
205
206
|
| Live agent workflows | [Mastra](https://neon.com/docs/realtime/examples/mastra.md) |
|
|
206
207
|
| ORM adapters | [Drizzle](https://neon.com/docs/realtime/examples/drizzle.md), [Kysely](https://neon.com/docs/realtime/examples/kysely.md) |
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
<!-- Generated by scripts/sync-skill-docs.mjs from website@
|
|
1
|
+
<!-- Generated by scripts/sync-skill-docs.mjs from website@HEAD:e520dd136+dirty (docs/realtime/guides/mutations). Do not edit: change the docs and run npm run sync:docs. sha256:01fbd1e6a58f3c8ab13b010a70558be0ac5e93e85791fed6310a4c1d7a19e448 -->
|
|
2
2
|
Canonical page: https://neon.com/docs/realtime/guides/mutations.md
|
|
3
3
|
|
|
4
4
|
> Summary: Write through your own backend, return the transaction id, apply the change optimistically and drop the optimistic state once the change arrives on the live query. Without a framework, with React useOptimistic or with TanStack DB.
|
|
@@ -21,6 +21,8 @@ Make apps and agents super fast, with instant local writes.
|
|
|
21
21
|
- [With TanStack DB collections](#with-tanstack-db-collections)
|
|
22
22
|
- [Render the app](#render-the-app)
|
|
23
23
|
|
|
24
|
+
Last updated: 2026-11-18
|
|
25
|
+
|
|
24
26
|
Apply instant local writes using [optimistic mutations](#how-optimistic-mutations-work) that [automatically discard their optimistic state](#automatic-management-of-optimistic-state) when the changes [sync in through your live query subscriptions](subscribing.md#listen-for-changes).
|
|
25
27
|
|
|
26
28
|
## How optimistic mutations work
|
|
@@ -35,9 +37,9 @@ Realtime allows you to automate the management and lifecycle of your optimistic
|
|
|
35
37
|
|
|
36
38
|
1. apply the change to local, optimistic state, so the UI updates straight away
|
|
37
39
|
2. send the write through your backend, with your normal validation, authorization and backend logic, which returns the [ID of the transaction](https://www.postgresql.org/docs/current/transaction-id.html) that made it
|
|
38
|
-
3. wait
|
|
40
|
+
3. wait until the subscription has synced that transaction, using [`awaitTxId()`](https://neon.com/docs/realtime/sdks/typescript/client.md#client-materializedlivequerysubscriptionawaittxid)
|
|
39
41
|
4. drop the optimistic state
|
|
40
|
-
5. if the write fails, or
|
|
42
|
+
5. if the write fails, or the transaction doesn't sync before the timeout, drop the optimistic state and show an error
|
|
41
43
|
|
|
42
44
|
`awaitTxId()` remembers recently seen transaction IDs, so it resolves even when the change arrives before your backend's HTTP response. It also resolves after the subscription's `onChange`, so the synced rows already include the change when the optimistic state drops, which means nothing flickers.
|
|
43
45
|
|
|
@@ -215,7 +217,7 @@ When an edit or a delete batch matches no rows, the statement returns no row, so
|
|
|
215
217
|
|
|
216
218
|
**Important: Always pass a timeout**
|
|
217
219
|
|
|
218
|
-
`awaitTxId()` keeps waiting while the subscription reconnects or waits for a renewed sealed query,
|
|
220
|
+
`awaitTxId()` keeps waiting while the subscription reconnects or waits for a renewed sealed query, so always pass a timeout. When the timeout passes, it rejects, the optimistic change drops and the UI shows that the change couldn't be confirmed. The write may still have committed. It also rejects if the subscription errors or closes.
|
|
219
221
|
|
|
220
222
|
### Calling the routes from the frontend
|
|
221
223
|
|
|
@@ -524,7 +526,7 @@ export function Messages({ sealedQuery, refreshQuery, initialData, channelId, us
|
|
|
524
526
|
}
|
|
525
527
|
```
|
|
526
528
|
|
|
527
|
-
`mutate()` runs each mutation in its own transition, so independent writes run concurrently. The transition applies the mutation optimistically, writes through your backend and, if the write committed, waits for its txid with [`utils.awaitTxId()`](https://neon.com/docs/realtime/sdks/typescript.md#react-uselivequeryutils). When the transition ends, React drops its optimistic change. By then the change is in `data`, with the same id for a sent message, so the list doesn't flicker. If the write fails or isn't confirmed in time, the optimistic change drops the same way, the message reverts and the error line shows.
|
|
529
|
+
`mutate()` runs each mutation in its own transition, so independent writes run concurrently. The transition applies the mutation optimistically, writes through your backend and, if the write committed, waits for its txid with [`utils.awaitTxId()`](https://neon.com/docs/realtime/sdks/typescript/react.md#react-uselivequeryutils). When the transition ends, React drops its optimistic change. By then the change is in `data`, with the same id for a sent message, so the list doesn't flicker. If the write fails or isn't confirmed in time, the optimistic change drops the same way, the message reverts and the error line shows.
|
|
528
530
|
|
|
529
531
|
Edit and Delete show only on the user's own messages, and the routes still enforce authorship. They're disabled on pending messages, so you don't start a new change on a message whose last change isn't confirmed yet.
|
|
530
532
|
|
|
@@ -608,7 +610,7 @@ export function createMessagesCollection(sealedQuery: SealedLiveQuery<Message>)
|
|
|
608
610
|
export type MessagesCollection = ReturnType<typeof createMessagesCollection>
|
|
609
611
|
```
|
|
610
612
|
|
|
611
|
-
While a handler runs, TanStack DB holds back synced changes. When the handler returns, it drops the optimistic state and applies the synced rows together, so a sent message's optimistic row gives way to its synced row, which has the same id, in a single step. If a handler throws, the optimistic change rolls back. [`collection.utils.awaitTxId()`](https://neon.com/docs/realtime/sdks/typescript.md#tanstack-db-realtimecollectionutilsawaittxid) resolves once the transaction has entered TanStack DB's sync queue, and it takes the same explicit timeout.
|
|
613
|
+
While a handler runs, TanStack DB holds back synced changes. When the handler returns, it drops the optimistic state and applies the synced rows together, so a sent message's optimistic row gives way to its synced row, which has the same id, in a single step. If a handler throws, the optimistic change rolls back. [`collection.utils.awaitTxId()`](https://neon.com/docs/realtime/sdks/typescript/tanstack-db.md#tanstack-db-realtimecollectionutilsawaittxid) resolves once the transaction has entered TanStack DB's sync queue, and it takes the same explicit timeout.
|
|
612
614
|
|
|
613
615
|
Then write through the collection. This is the optimistic version of `frontend/Inbox.tsx` from the [reactivity guide](reactivity.md#query-the-collection). It runs the same local query, and its `insert()`, `update()` and `delete()` calls apply each change locally at once and call the matching handler:
|
|
614
616
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
<!-- Generated by scripts/sync-skill-docs.mjs from website@
|
|
1
|
+
<!-- Generated by scripts/sync-skill-docs.mjs from website@HEAD:e520dd136+dirty (docs/realtime/guides/queries). Do not edit: change the docs and run npm run sync:docs. sha256:e965803575c1edde217e413c6f1df44caa8ec72ac673a460a622780ac9324f0f -->
|
|
2
2
|
Canonical page: https://neon.com/docs/realtime/guides/queries.md
|
|
3
3
|
|
|
4
4
|
> Summary: Define live queries in your backend with raw SQL or Drizzle, fill in their parameters from the authenticated request, and seal them so clients can subscribe without being able to read or change them.
|
|
@@ -24,6 +24,8 @@ Define live SQL queries that you can subscribe to.
|
|
|
24
24
|
- [Exposing an endpoint](#exposing-an-endpoint)
|
|
25
25
|
- [Using server functions](#using-server-functions)
|
|
26
26
|
|
|
27
|
+
Last updated: 2026-11-18
|
|
28
|
+
|
|
27
29
|
Realtime works by defining and [subscribing](subscribing.md) to live SQL queries. Queries are designed to be [defined securely](#defining-live-queries) in your backend code and [subscribed‑to safely](#exposing-queries) in your frontend.
|
|
28
30
|
|
|
29
31
|
Define live queries using [raw SQL](#using-raw-sql) or a [query builder or ORM](#using-a-query-builder-or-orm). [Seal the queries](#sealing-queries) and [expose](#exposing-queries) them to your frontend via an [API endpoint](#exposing-an-endpoint) or a [server function](#using-server-functions), using your normal [authorization](#authorization) context.
|
|
@@ -43,7 +45,7 @@ npm install drizzle-orm pg hono jose ws
|
|
|
43
45
|
npm install -D @types/pg @types/ws
|
|
44
46
|
```
|
|
45
47
|
|
|
46
|
-
Install the Realtime [TypeScript SDK](https://neon.com/docs/realtime/sdks/typescript.md) and its [Drizzle adapter](https://neon.com/docs/realtime/sdks/typescript.md
|
|
48
|
+
Install the Realtime [TypeScript SDK](https://neon.com/docs/realtime/sdks/typescript.md) and its [Drizzle adapter](https://neon.com/docs/realtime/sdks/typescript/drizzle.md):
|
|
47
49
|
|
|
48
50
|
```bash filename="Terminal"
|
|
49
51
|
npm install @neon/realtime @neon/realtime-drizzle
|
|
@@ -161,6 +163,8 @@ So, for example, you can't `SELECT` over updated rows and you can't use function
|
|
|
161
163
|
|
|
162
164
|
Tables need a [stable replica identity](https://www.postgresql.org/docs/current/sql-altertable.html#SQL-ALTERTABLE-REPLICA-IDENTITY). If your tables have a primary key, they're fine.
|
|
163
165
|
|
|
166
|
+
Tables can't have [row-level security](https://neon.com/docs/guides/row-level-security.md) enabled. A live query on a table with RLS is rejected: the subscription moves to `error` with the code `upstream_rejected`. With [debug mode](subscribing.md#show-full-database-errors) on, the message says the table has row-level security enabled. Filter rows in the query instead, as shown in [Authorization](#authorization).
|
|
167
|
+
|
|
164
168
|
**Optional: REPLICA IDENTITY FULL:**
|
|
165
169
|
|
|
166
170
|
Setting `REPLICA IDENTITY FULL` can make live queries marginally faster, at the cost of writing the whole old row to the Postgres WAL on every update and delete. That may save Realtime a lookup when it processes those changes. If latency matters for a write-heavy table, benchmark both settings with your own workload before you switch.
|
|
@@ -184,7 +188,7 @@ export const realtime = createRealtime({
|
|
|
184
188
|
|
|
185
189
|
`createRealtime()` also takes a [`debugMode`](subscribing.md#show-full-database-errors) option.
|
|
186
190
|
|
|
187
|
-
Then define queries using [`rawSql`](https://neon.com/docs/realtime/sdks/typescript.md#backend-rawsql). For example:
|
|
191
|
+
Then define queries using [`rawSql`](https://neon.com/docs/realtime/sdks/typescript/backend.md#backend-rawsql). For example:
|
|
188
192
|
|
|
189
193
|
```ts filename="backend/queries-raw.ts"
|
|
190
194
|
import { rawSql } from "@neon/realtime/server"
|
|
@@ -228,7 +232,7 @@ Never use literal interpolation for user input like `` `WHERE user_id = '${userI
|
|
|
228
232
|
|
|
229
233
|
#### Parameter types
|
|
230
234
|
|
|
231
|
-
You can pass strings, numbers, booleans, bigints and `null` as they are. Other value types need a [`pgParam`](https://neon.com/docs/realtime/sdks/typescript.md#backend-pgparam) helper to specify the Postgres type. A `Date` could be a `date`, a `timestamp` or a `timestamptz`, so wrap it in `pgParam.date()`, `pgParam.timestamp()` or `pgParam.timestamptz()`.
|
|
235
|
+
You can pass strings, numbers, booleans, bigints and `null` as they are. Other value types need a [`pgParam`](https://neon.com/docs/realtime/sdks/typescript/backend.md#backend-pgparam) helper to specify the Postgres type. A `Date` could be a `date`, a `timestamp` or a `timestamptz`, so wrap it in `pgParam.date()`, `pgParam.timestamp()` or `pgParam.timestamptz()`.
|
|
232
236
|
|
|
233
237
|
For example, this filters messages `since` a [timestamp with timezone](https://neon.com/postgresql/tutorial/timestamp#introduction-to-postgresql-timestamp):
|
|
234
238
|
|
|
@@ -254,11 +258,11 @@ There are helpers for dates, JSON, `bytea` and arrays, such as `pgParam.array("t
|
|
|
254
258
|
|
|
255
259
|
### Using a query builder or ORM
|
|
256
260
|
|
|
257
|
-
Realtime supports an adapter pattern to convert any typed query object to raw SQL. This works by passing an adapter to [`createRealtime`](https://neon.com/docs/realtime/sdks/typescript.md#backend-createrealtime).
|
|
261
|
+
Realtime supports an adapter pattern to convert any typed query object to raw SQL. This works by passing an adapter to [`createRealtime`](https://neon.com/docs/realtime/sdks/typescript/backend.md#backend-createrealtime).
|
|
258
262
|
|
|
259
263
|
The rest of these guides use the Drizzle versions of `backend/realtime.ts` and `backend/queries.ts` below in place of the raw SQL files above.
|
|
260
264
|
|
|
261
|
-
For example, configure Realtime to use the [`drizzleAdapter`](https://neon.com/docs/realtime/sdks/typescript.md#drizzle-drizzleadapter):
|
|
265
|
+
For example, configure Realtime to use the [`drizzleAdapter`](https://neon.com/docs/realtime/sdks/typescript/drizzle.md#drizzle-drizzleadapter):
|
|
262
266
|
|
|
263
267
|
```ts filename="backend/realtime.ts" {2,7}
|
|
264
268
|
import { createRealtime } from "@neon/realtime/server"
|
|
@@ -314,13 +318,13 @@ To seal a query you pass your query instance, e.g.:
|
|
|
314
318
|
const query = messagesQuery(userId, channelId)
|
|
315
319
|
```
|
|
316
320
|
|
|
317
|
-
To the [`seal`](https://neon.com/docs/realtime/sdks/typescript.md#backend-realtimeserverseal) method of the `RealtimeServer` instance you created above:
|
|
321
|
+
To the [`seal`](https://neon.com/docs/realtime/sdks/typescript/backend.md#backend-realtimeserverseal) method of the `RealtimeServer` instance you created above:
|
|
318
322
|
|
|
319
323
|
```ts filename="backend/server.ts"
|
|
320
324
|
const sealedQuery = await realtime.seal({ query })
|
|
321
325
|
```
|
|
322
326
|
|
|
323
|
-
It's local [Web Crypto](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API) work with no network call, so it's cheap to run on every request. It returns a [`SealedLiveQuery<Row>`](https://neon.com/docs/realtime/sdks/typescript.md#backend-sealedlivequery), which has three fields:
|
|
327
|
+
It's local [Web Crypto](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API) work with no network call, so it's cheap to run on every request. It returns a [`SealedLiveQuery<Row>`](https://neon.com/docs/realtime/sdks/typescript/backend.md#backend-sealedlivequery), which has three fields:
|
|
324
328
|
|
|
325
329
|
- `capability`: the encrypted query
|
|
326
330
|
- `expiresAt`: when it expires, in Unix milliseconds
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
<!-- Generated by scripts/sync-skill-docs.mjs from website@
|
|
1
|
+
<!-- Generated by scripts/sync-skill-docs.mjs from website@HEAD:e520dd136+dirty (docs/realtime/guides/reactivity). Do not edit: change the docs and run npm run sync:docs. sha256:ac050d9a74a806eb5acd080446c816adcaeddc76e378d0a623e9239198480fc6 -->
|
|
2
2
|
Canonical page: https://neon.com/docs/realtime/guides/reactivity.md
|
|
3
3
|
|
|
4
4
|
> Summary: Bind live queries to React component state with useLiveQuery, change their parameters and handle errors, or sync a broader live query into a TanStack DB collection and derive instant, local queries from it.
|
|
@@ -21,6 +21,8 @@ Bind live queries to component and agent state.
|
|
|
21
21
|
- [Manage optimistic state](#manage-optimistic-state)
|
|
22
22
|
- [Other frameworks](#other-frameworks)
|
|
23
23
|
|
|
24
|
+
Last updated: 2026-11-18
|
|
25
|
+
|
|
24
26
|
Build reactive apps and agents using higher-level reactivity primitives that manage live query [subscriptions](subscribing.md) for you.
|
|
25
27
|
|
|
26
28
|
**Important: Framework support**
|
|
@@ -33,7 +35,7 @@ This page continues the [running example](https://github.com/neondatabase/exampl
|
|
|
33
35
|
|
|
34
36
|
## React
|
|
35
37
|
|
|
36
|
-
The `@neon/realtime-react` binding exports a [`RealtimeProvider`](https://neon.com/docs/realtime/sdks/typescript.md#react-realtimeprovider), a [`useLiveQuery()` hook](https://neon.com/docs/realtime/sdks/typescript.md#react-uselivequery) and a [`useRealtimeClient()` hook](https://neon.com/docs/realtime/sdks/typescript.md#react-userealtimeclient) that returns the provider's client. It works with React 18 and 19.
|
|
38
|
+
The `@neon/realtime-react` binding exports a [`RealtimeProvider`](https://neon.com/docs/realtime/sdks/typescript/react.md#react-realtimeprovider), a [`useLiveQuery()` hook](https://neon.com/docs/realtime/sdks/typescript/react.md#react-uselivequery) and a [`useRealtimeClient()` hook](https://neon.com/docs/realtime/sdks/typescript/react.md#react-userealtimeclient) that returns the provider's client. It works with React 18 and 19.
|
|
37
39
|
|
|
38
40
|
Install it alongside the client SDK:
|
|
39
41
|
|
|
@@ -43,7 +45,7 @@ npm install @neon/realtime-react
|
|
|
43
45
|
|
|
44
46
|
### RealtimeProvider
|
|
45
47
|
|
|
46
|
-
Wrap your app in `<RealtimeProvider>`. This allows all of your `useLiveQuery()` subscriptions to use the same [`RealtimeClient`](https://neon.com/docs/realtime/sdks/typescript.md#client-realtimeclient) and WebSocket connection.
|
|
48
|
+
Wrap your app in `<RealtimeProvider>`. This allows all of your `useLiveQuery()` subscriptions to use the same [`RealtimeClient`](https://neon.com/docs/realtime/sdks/typescript/client.md#client-realtimeclient) and WebSocket connection.
|
|
47
49
|
|
|
48
50
|
```tsx filename="frontend/main.tsx"
|
|
49
51
|
import { StrictMode } from "react"
|
|
@@ -65,7 +67,7 @@ createRoot(document.getElementById("root")!).render(
|
|
|
65
67
|
|
|
66
68
|
### useLiveQuery
|
|
67
69
|
|
|
68
|
-
[`useLiveQuery()`](https://neon.com/docs/realtime/sdks/typescript.md#react-uselivequery) takes a `sealedQuery` and a `refreshQuery` (and, optionally, [`initialData` from SSR](ssr.md)) and returns the query's current rows and state.
|
|
70
|
+
[`useLiveQuery()`](https://neon.com/docs/realtime/sdks/typescript/react.md#react-uselivequery) takes a `sealedQuery` and a `refreshQuery` (and, optionally, [`initialData` from SSR](ssr.md)) and returns the query's current rows and state.
|
|
69
71
|
|
|
70
72
|
For example, here we define a `Messages` component with `useLiveQuery`:
|
|
71
73
|
|
|
@@ -147,11 +149,11 @@ The hook also accepts an optional `initialData` parameter, for example from a se
|
|
|
147
149
|
|
|
148
150
|
#### utils
|
|
149
151
|
|
|
150
|
-
The `utils` in the return value give you access to the hook's underlying [materialized subscription](https://neon.com/docs/realtime/sdks/typescript.md#react-uselivequeryutils).
|
|
152
|
+
The `utils` in the return value give you access to the hook's underlying [materialized subscription](https://neon.com/docs/realtime/sdks/typescript/react.md#react-uselivequeryutils).
|
|
151
153
|
|
|
152
154
|
This provides `getSnapshot()`, `getState()`, `awaitRows()`, the `onChange`, `onUpdate` and `onStateChange` listeners, `renew()` and `awaitTxId()`. It's stable for the life of the subscription, so register listeners in an effect and return the remover, as the `onUpdate` listener does.
|
|
153
155
|
|
|
154
|
-
Note that a `changes` update has already been applied by the time its listener runs, and it [carries the txids](https://neon.com/docs/realtime/sdks/typescript.md#client-livequerybatchinfo) of the transactions in it, which the [mutations guide](mutations.md#how-optimistic-mutations-work) uses to confirm optimistic writes.
|
|
156
|
+
Note that a `changes` update has already been applied by the time its listener runs, and it [carries the txids](https://neon.com/docs/realtime/sdks/typescript/client.md#client-livequerybatchinfo) of the transactions in it, which the [mutations guide](mutations.md#how-optimistic-mutations-work) uses to confirm optimistic writes.
|
|
155
157
|
|
|
156
158
|
`utils` omits `unsubscribe()`, because React owns cleanup. The hook unsubscribes when the component unmounts or its sealed query changes. `getState()` and the listeners report the state of the underlying subscription, so they can differ from the hook's `status`.
|
|
157
159
|
|
|
@@ -308,13 +310,13 @@ export function createMessagesCollection(sealedQuery: SealedLiveQuery<Message>)
|
|
|
308
310
|
export type MessagesCollection = ReturnType<typeof createMessagesCollection>
|
|
309
311
|
```
|
|
310
312
|
|
|
311
|
-
`getKey` returns each message's primary key. TanStack DB keys rows by it, so use a stable, unique column, never a subscription's `rowId`. `refreshQuery` renews the sealed query the same way [the React hook does](#refreshquery). While renewals fail, the collection stays `ready` with its last rows. See the [`realtimeCollectionOptions()` reference](https://neon.com/docs/realtime/sdks/typescript.md#tanstack-db-realtimecollectionoptions) for the rest of the options.
|
|
313
|
+
`getKey` returns each message's primary key. TanStack DB keys rows by it, so use a stable, unique column, never a subscription's `rowId`. `refreshQuery` renews the sealed query the same way [the React hook does](#refreshquery). While renewals fail, the collection stays `ready` with its last rows. See the [`realtimeCollectionOptions()` reference](https://neon.com/docs/realtime/sdks/typescript/tanstack-db.md#tanstack-db-realtimecollectionoptions) for the rest of the options.
|
|
312
314
|
|
|
313
315
|
The collection starts syncing as soon as a live query using it is mounted. It's in the `loading` state until the first result arrives, and `ready` from then on, with each committed transaction applied atomically. A `ready` collection stays ready while the subscription is `connecting` or `stale`, so there's no separate recovery flag to render. If the subscription ends in `error`, so does the collection.
|
|
314
316
|
|
|
315
317
|
### Query the collection
|
|
316
318
|
|
|
317
|
-
Create the collection once, when the app starts. The collection takes the client directly,
|
|
319
|
+
Create the collection once, when the app starts. The collection takes the client directly, so an app that only uses collections doesn't need `RealtimeProvider`. `Channel` still calls `useLiveQuery()`, though, so keep both views inside `RealtimeProvider`:
|
|
318
320
|
|
|
319
321
|
```tsx filename="frontend/main.tsx"
|
|
320
322
|
import { StrictMode } from "react"
|
|
@@ -402,6 +404,6 @@ For writes through the collection, with optimistic state, see the [mutations gui
|
|
|
402
404
|
|
|
403
405
|
Bindings for other frameworks are coming. Until then, you can use the current implementations as a reference to write your own.
|
|
404
406
|
|
|
405
|
-
The React binding is a thin layer over the client subscription: `useSyncExternalStore` plus the [`QueryRefreshController`](https://neon.com/docs/realtime/sdks/typescript.md#client-queryrefreshcontroller). Point a coding agent at [its source](https://github.com/neondatabase/neon-pkgs/tree/main/packages/realtime-react) and it can reproduce the binding for other frameworks, such as Solid, Svelte or Vue.
|
|
407
|
+
The React binding is a thin layer over the client subscription: `useSyncExternalStore` plus the [`QueryRefreshController`](https://neon.com/docs/realtime/sdks/typescript/client.md#client-queryrefreshcontroller). Point a coding agent at [its source](https://github.com/neondatabase/neon-pkgs/tree/main/packages/realtime-react) and it can reproduce the binding for other frameworks, such as Solid, Svelte or Vue.
|
|
406
408
|
|
|
407
409
|
You can also see the [source code for the TanStack DB collection here](https://github.com/neondatabase/neon-pkgs/blob/main/packages/realtime-tanstack/src/collection-options.ts).
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
<!-- Generated by scripts/sync-skill-docs.mjs from website@
|
|
1
|
+
<!-- Generated by scripts/sync-skill-docs.mjs from website@HEAD:e520dd136+dirty (docs/realtime/guides/ssr). Do not edit: change the docs and run npm run sync:docs. sha256:bc08714370ef437123354cae2af2e4423894ac1e87bd95fee2f6799b53725f8f -->
|
|
2
2
|
Canonical page: https://neon.com/docs/realtime/guides/ssr.md
|
|
3
3
|
|
|
4
4
|
> Summary: Server-render pages that use live queries. Read and seal the same query for each request, send both to the browser, render the initial rows straight away and let the first result bring the page live.
|
|
@@ -23,6 +23,8 @@ Render sealed queries and initial query results on the server.
|
|
|
23
23
|
- [Keep secrets on the server](#keep-secrets-on-the-server)
|
|
24
24
|
- [Examples](#examples)
|
|
25
25
|
|
|
26
|
+
Last updated: 2026-11-18
|
|
27
|
+
|
|
26
28
|
[Server-side rendering (SSR)](https://developer.mozilla.org/en-US/docs/Glossary/SSR) lets a page arrive with its rows already in the HTML, then subscribe to ongoing changes as soon as it hydrates.
|
|
27
29
|
|
|
28
30
|
Realtime supports SSR, including with [Next.js](https://neon.com/docs/realtime/examples/nextjs.md) and [TanStack Start](https://neon.com/docs/realtime/examples/tanstack.md).
|
|
@@ -559,7 +561,7 @@ export function getRouter() {
|
|
|
559
561
|
|
|
560
562
|
### Define the collection
|
|
561
563
|
|
|
562
|
-
Define the collection as a descriptor with the two-argument `collectionOptions(id, factory)` around [`realtimeCollectionOptions()`](https://neon.com/docs/realtime/sdks/typescript.md#tanstack-db-realtimecollectionoptions), and give it a stable id. Each `DbClient` runs the factory once, to create its own instance of the collection. Unlike `createMessagesCollection()` in the reactivity guide, it doesn't take a Realtime client: the factory reads the one from its `DbClient`. The descriptor is cheap to build, so the loader and the channel page each build it, and the id resolves both to the same collection:
|
|
564
|
+
Define the collection as a descriptor with the two-argument `collectionOptions(id, factory)` around [`realtimeCollectionOptions()`](https://neon.com/docs/realtime/sdks/typescript/tanstack-db.md#tanstack-db-realtimecollectionoptions), and give it a stable id. Each `DbClient` runs the factory once, to create its own instance of the collection. Unlike `createMessagesCollection()` in the reactivity guide, it doesn't take a Realtime client: the factory reads the one from its `DbClient`. The descriptor is cheap to build, so the loader and the channel page each build it, and the id resolves both to the same collection:
|
|
563
565
|
|
|
564
566
|
```ts filename="src/collections.ts"
|
|
565
567
|
import { collectionOptions } from "@tanstack/react-db"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
<!-- Generated by scripts/sync-skill-docs.mjs from website@
|
|
1
|
+
<!-- Generated by scripts/sync-skill-docs.mjs from website@HEAD:e520dd136+dirty (docs/realtime/guides/subscribing). Do not edit: change the docs and run npm run sync:docs. sha256:81179e0b1e9ab06abb855f26595bd639b5934dd3d3b9a7866270f06de5f934f3 -->
|
|
2
2
|
Canonical page: https://neon.com/docs/realtime/guides/subscribing.md
|
|
3
3
|
|
|
4
4
|
> Summary: Subscribe to live queries from trusted backend code or the browser. Fetch sealed queries from your API, handle every callback and renew sealed queries before they expire.
|
|
@@ -21,7 +21,9 @@ Subscribe to live queries using the Realtime client.
|
|
|
21
21
|
- [Log client diagnostics](#log-client-diagnostics)
|
|
22
22
|
- [Show full database errors](#show-full-database-errors)
|
|
23
23
|
|
|
24
|
-
|
|
24
|
+
Last updated: 2026-11-18
|
|
25
|
+
|
|
26
|
+
Once you've [defined](queries.md) and [sealed](queries.md#sealing-queries) a query, you can [subscribe to it](#subscribe-to-the-sealed-query) using the [low‑level Realtime client](https://neon.com/docs/realtime/sdks/typescript/client.md#client-createrealtimeclient).
|
|
25
27
|
|
|
26
28
|
**Important: Client-side reactivity**
|
|
27
29
|
|
|
@@ -39,7 +41,7 @@ The guide continues the [running example](https://github.com/neondatabase/exampl
|
|
|
39
41
|
|
|
40
42
|
### Subscribe in trusted backend code
|
|
41
43
|
|
|
42
|
-
Add a `url` to [`createRealtime()`](https://neon.com/docs/realtime/sdks/typescript.md#backend-createrealtime) and it returns a direct server, which seals queries with your secret and subscribes to them itself.
|
|
44
|
+
Add a `url` to [`createRealtime()`](https://neon.com/docs/realtime/sdks/typescript/backend.md#backend-createrealtime) and it returns a direct server, which seals queries with your secret and subscribes to them itself.
|
|
43
45
|
|
|
44
46
|
```ts filename="backend/worker.ts" {11,19,20,22}
|
|
45
47
|
import { createRealtime } from "@neon/realtime/server"
|
|
@@ -208,17 +210,17 @@ function renderMessage(message: Message): HTMLLIElement {
|
|
|
208
210
|
|
|
209
211
|
Rows arrive decoded, so `created_at` is a `Date`, as Drizzle's `Message` type says. The client's default parsers decode these Postgres types:
|
|
210
212
|
|
|
211
|
-
| Postgres type
|
|
212
|
-
|
|
|
213
|
-
| `bool`
|
|
214
|
-
| `int2`, `int4`, `oid`, `float4`, `float8`
|
|
215
|
-
| `json`, `jsonb`
|
|
216
|
-
| `timestamptz`
|
|
217
|
-
| `timestamp`
|
|
218
|
-
| `date`
|
|
219
|
-
| `bytea`
|
|
220
|
-
| `int8`, `numeric`
|
|
221
|
-
| Everything else, such as `text` and `uuid` | `string`, as Postgres formats it
|
|
213
|
+
| Postgres type | Arrives as |
|
|
214
|
+
| - | - |
|
|
215
|
+
| `bool` | `boolean` |
|
|
216
|
+
| `int2`, `int4`, `oid`, `float4`, `float8` | `number` |
|
|
217
|
+
| `json`, `jsonb` | The parsed JSON value |
|
|
218
|
+
| `timestamptz` | `Date` |
|
|
219
|
+
| `timestamp` | `Date` in local time |
|
|
220
|
+
| `date` | `Date` at local midnight |
|
|
221
|
+
| `bytea` | `Uint8Array` |
|
|
222
|
+
| `int8`, `numeric` | `string`, so their values stay exact |
|
|
223
|
+
| Everything else, such as `text` and `uuid` | `string`, as Postgres formats it |
|
|
222
224
|
|
|
223
225
|
`NULL` arrives as `null`, and arrays of built-in types decode element by element.
|
|
224
226
|
|
|
@@ -230,23 +232,23 @@ When you're done with a subscription, call `unsubscribe()`. It moves the subscri
|
|
|
230
232
|
|
|
231
233
|
A subscription has three callbacks. Each one takes a listener and returns a function that removes it:
|
|
232
234
|
|
|
233
|
-
| Callback
|
|
234
|
-
|
|
|
235
|
-
| `onChange`
|
|
236
|
-
| `onStateChange` | `state: LiveQueryState`
|
|
237
|
-
| `onUpdate`
|
|
235
|
+
| Callback | Listener arguments | Fires |
|
|
236
|
+
| - | - | - |
|
|
237
|
+
| `onChange` | `snapshot: LiveQuerySnapshot<Row>` | After each state change, after each `changes` update while `live`, and when a new result is complete. Materialized subscriptions only. |
|
|
238
|
+
| `onStateChange` | `state: LiveQueryState` | When the status changes. |
|
|
239
|
+
| `onUpdate` | `update: RawLiveQueryUpdate<Row>` | With `type: "rows"` and `rows`, each `{ rowId, row }`, when a complete, authoritative result replaces the previous one. With `type: "changes"`, `changes` and `batch: LiveQueryBatchInfo` when committed transactions change the result. Each change is an `upsert` with a `rowId` and `row`, or a `remove` with only a `rowId`. |
|
|
238
240
|
|
|
239
241
|
Listeners run in the order you add them, and one that throws doesn't stop the others. Each initial result and each committed transaction becomes visible atomically. Outside a listener, `getSnapshot()` and `getState()` return the current values.
|
|
240
242
|
|
|
241
243
|
The status tells you how far to trust the rows:
|
|
242
244
|
|
|
243
|
-
| Status
|
|
244
|
-
|
|
|
245
|
+
| Status | Meaning |
|
|
246
|
+
| - | - |
|
|
245
247
|
| `connecting` | Waiting for a result: when it starts, including with `initialData` from a [server render](ssr.md), after a reconnect, and after renewing an expired sealed query. Rows you already have stay. |
|
|
246
|
-
| `live`
|
|
247
|
-
| `stale`
|
|
248
|
-
| `error`
|
|
249
|
-
| `closed`
|
|
248
|
+
| `live` | The rows are authoritative and changes are streaming. It stays `live` while the server replaces the whole result. |
|
|
249
|
+
| `stale` | The sealed query expired and the subscription is waiting for a renewed one. The rows are usable but may be out of date. Render them normally. |
|
|
250
|
+
| `error` | Automatic recovery has stopped. See [handle errors](#handle-errors). |
|
|
251
|
+
| `closed` | Closed by `unsubscribe()` or `client.close()`. It doesn't reopen. |
|
|
250
252
|
|
|
251
253
|
By default, subscriptions are materialized. The client keeps the rows and applies each update before `onUpdate` fires, so `getSnapshot()` in an update listener already includes it. If your code keeps its own rows, as TanStack DB does, pass `{ materialize: false }` for a raw subscription. It has the same callbacks except `onChange`, and no `getSnapshot()`. Keep the rows in a map keyed by `rowId`, replace them on each `rows` update and apply each `changes` update's upserts and removes:
|
|
252
254
|
|
|
@@ -276,7 +278,7 @@ subscription.onUpdate((update: RawLiveQueryUpdate<Message>) => {
|
|
|
276
278
|
for (const change of update.changes) {
|
|
277
279
|
if (change.type === "upsert") {
|
|
278
280
|
rows.set(change.rowId, change.row)
|
|
279
|
-
} else {
|
|
281
|
+
} else if (change.type === "remove") {
|
|
280
282
|
rows.delete(change.rowId)
|
|
281
283
|
}
|
|
282
284
|
}
|
|
@@ -291,7 +293,7 @@ subscription.onStateChange((state: LiveQueryState) => {
|
|
|
291
293
|
|
|
292
294
|
A `rowId` is opaque and scoped to its subscription, and each `rows` update invalidates every earlier one. It isn't a primary key, so don't store it or match it against your own ids. A `rows` update can arrive at any time, for example after a reconnect, and it always replaces the whole result.
|
|
293
295
|
|
|
294
|
-
Each `changes` update also carries the ids of the Postgres transactions it covers, in `update.batch.txids`. The [mutations guide](mutations.md) uses them to confirm optimistic mutations.
|
|
296
|
+
Each `changes` update also carries the ids of the Postgres transactions it covers, in `update.batch.txids`. The [mutations guide](mutations.md) uses them to confirm optimistic mutations. With `ORDER BY`, `changes` can also include `move` changes, which carry a `rowId` and the `afterRowId` it now follows (`null` for the first row), and no row.
|
|
295
297
|
|
|
296
298
|
## Renew the sealed query
|
|
297
299
|
|
|
@@ -415,11 +417,11 @@ function renderMessage(message: Message): HTMLLIElement {
|
|
|
415
417
|
|
|
416
418
|
If the replacement's `queryFingerprint` doesn't match, the promise that `renew()` returns rejects. A changed parameter, like a different channel, makes a different query, so subscribe to the new one and unsubscribe from the old.
|
|
417
419
|
|
|
418
|
-
You don't write this yourself when you use the bindings. The [React and TanStack DB bindings](reactivity.md) take a `refreshQuery` function and renew with the same timing, 10 seconds before expiry with a 1-second retry. They're built on [`QueryRefreshController`](https://neon.com/docs/realtime/sdks/typescript.md#client-queryrefreshcontroller), which you can use if you're writing a binding for another framework.
|
|
420
|
+
You don't write this yourself when you use the bindings. The [React and TanStack DB bindings](reactivity.md) take a `refreshQuery` function and renew with the same timing, 10 seconds before expiry with a 1-second retry. They're built on [`QueryRefreshController`](https://neon.com/docs/realtime/sdks/typescript/client.md#client-queryrefreshcontroller), which you can use if you're writing a binding for another framework.
|
|
419
421
|
|
|
420
422
|
## Handle errors
|
|
421
423
|
|
|
422
|
-
When automatic recovery stops, the subscription moves to `error`, and its `error` is a [`LiveQueryError`](https://neon.com/docs/realtime/sdks/typescript.md#client-livequeryerror) with:
|
|
424
|
+
When automatic recovery stops, the subscription moves to `error`, and its `error` is a [`LiveQueryError`](https://neon.com/docs/realtime/sdks/typescript/client.md#client-livequeryerror) with:
|
|
423
425
|
|
|
424
426
|
- `code`: a stable, machine-readable error code
|
|
425
427
|
- `message`: a description of the failure
|
|
@@ -437,7 +439,7 @@ If the connection itself fails, for example because of a fatal protocol error, e
|
|
|
437
439
|
|
|
438
440
|
### Log client diagnostics
|
|
439
441
|
|
|
440
|
-
The client is silent by default. To see what it's doing, pass a `logLevel` to [`createRealtimeClient()`](https://neon.com/docs/realtime/sdks/typescript.md#client-createrealtimeclient): `"error"`, `"warn"`, `"info"` or `"debug"`. Each level includes the ones before it.
|
|
442
|
+
The client is silent by default. To see what it's doing, pass a `logLevel` to [`createRealtimeClient()`](https://neon.com/docs/realtime/sdks/typescript/client.md#client-createrealtimeclient): `"error"`, `"warn"`, `"info"` or `"debug"`. Each level includes the ones before it.
|
|
441
443
|
|
|
442
444
|
```ts filename="frontend/client.ts" {7}
|
|
443
445
|
import { createRealtimeClient } from "@neon/realtime/client"
|
|
@@ -450,7 +452,7 @@ export const client = createRealtimeClient({
|
|
|
450
452
|
})
|
|
451
453
|
```
|
|
452
454
|
|
|
453
|
-
Entries go to the console unless you pass a [`logger`](https://neon.com/docs/realtime/sdks/typescript.md#client-realtimelogger), which receives each [entry](https://neon.com/docs/realtime/sdks/typescript.md#client-realtimelogentry) instead. An entry has a `level`, a `message`, a `timestamp` and a stable `event` name, like `connection_lost` or `subscription_failed`. Match on `event`, not on `message`:
|
|
455
|
+
Entries go to the console unless you pass a [`logger`](https://neon.com/docs/realtime/sdks/typescript/client.md#client-realtimelogger), which receives each [entry](https://neon.com/docs/realtime/sdks/typescript/client.md#client-realtimelogentry) instead. An entry has a `level`, a `message`, a `timestamp` and a stable `event` name, like `connection_lost` or `subscription_failed`. Match on `event`, not on `message`:
|
|
454
456
|
|
|
455
457
|
```ts
|
|
456
458
|
logger: (entry) => {
|
|
@@ -480,6 +482,8 @@ export const realtime = createRealtime({
|
|
|
480
482
|
|
|
481
483
|
Every query it seals then reports errors with the database's full message, plus its SQLSTATE code in `sqlState` when there is one. It's a backend option because it travels inside each sealed query.
|
|
482
484
|
|
|
485
|
+
To check a query's full error from the terminal without writing code, run [`neon realtime subscribe --debug`](https://neon.com/docs/cli/realtime.md#subscribe).
|
|
486
|
+
|
|
483
487
|
**Warning: Development only**
|
|
484
488
|
|
|
485
489
|
Full error details can expose schema, table and column names to anyone who subscribes, including through any error message your UI shows. Never turn on `debugMode` in production.
|