@neon/skills 2.1.1 → 2.2.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 +7 -1
- package/package.json +5 -3
- package/plugin.json +2 -2
- package/skills/neon/SKILL.md +31 -10
- package/skills/neon-ai-gateway/SKILL.md +43 -14
- package/skills/neon-functions/SKILL.md +12 -11
- package/skills/neon-functions/references/sse.md +2 -2
- package/skills/neon-object-storage/SKILL.md +5 -4
- package/skills/neon-postgres/SKILL.md +5 -2
- package/skills/neon-postgres/references/full-text-search.md +27 -17
- package/skills/neon-postgres/references/hybrid-search.md +19 -15
- package/skills/neon-postgres/references/lakebase-search-drizzle.md +99 -14
- package/skills/neon-postgres/references/vector-search.md +93 -10
- package/skills/neon-realtime/SKILL.md +206 -0
- package/skills/neon-realtime/references/mutations.md +743 -0
- package/skills/neon-realtime/references/queries.md +509 -0
- package/skills/neon-realtime/references/reactivity.md +407 -0
- package/skills/neon-realtime/references/ssr.md +695 -0
- package/skills/neon-realtime/references/subscribing.md +485 -0
|
@@ -10,6 +10,7 @@ Contents:
|
|
|
10
10
|
- [Extensions](#extensions): custom migration required to create extensions (Drizzle can't)
|
|
11
11
|
- [Schema](#schema): columns, generated `tsvector`, and the ANN index
|
|
12
12
|
- [BM25 Index](#bm25-index): created after the corpus is seeded
|
|
13
|
+
- [Generate and Store Embeddings](#generate-and-store-embeddings): call the AI Gateway and insert vectors with Drizzle
|
|
13
14
|
- [Query](#query): vector, BM25, and hybrid reads
|
|
14
15
|
- [Tune Per Query](#tune-per-query): per-query GUCs
|
|
15
16
|
|
|
@@ -22,18 +23,22 @@ Rules:
|
|
|
22
23
|
|
|
23
24
|
## Config
|
|
24
25
|
|
|
25
|
-
`drizzle-kit generate` and `migrate` read `drizzle.config.ts`. Point `dbCredentials.url` at the **direct (unpooled)** connection string:
|
|
26
|
+
`drizzle-kit generate` and `migrate` read `drizzle.config.ts`. If the connection string is in `.env`, install `dotenv` (`npm install dotenv`) and load it here. Point `dbCredentials.url` at the **direct (unpooled)** connection string:
|
|
26
27
|
|
|
27
28
|
```typescript
|
|
28
29
|
// drizzle.config.ts
|
|
30
|
+
import "dotenv/config";
|
|
29
31
|
import { defineConfig } from "drizzle-kit";
|
|
30
32
|
|
|
33
|
+
const databaseUrl = process.env.DATABASE_URL_UNPOOLED;
|
|
34
|
+
if (!databaseUrl) throw new Error("Missing DATABASE_URL_UNPOOLED");
|
|
35
|
+
|
|
31
36
|
export default defineConfig({
|
|
32
37
|
schema: "./src/schema.ts",
|
|
33
38
|
out: "./drizzle",
|
|
34
39
|
dialect: "postgresql",
|
|
35
40
|
// Direct (unpooled) URL. Neon exposes it as DATABASE_URL_UNPOOLED.
|
|
36
|
-
dbCredentials: { url:
|
|
41
|
+
dbCredentials: { url: databaseUrl },
|
|
37
42
|
});
|
|
38
43
|
```
|
|
39
44
|
|
|
@@ -57,7 +62,14 @@ The columns, the generated `tsvector`, and the `lakebase_ann` index all go in `s
|
|
|
57
62
|
|
|
58
63
|
```typescript
|
|
59
64
|
// src/schema.ts
|
|
60
|
-
import {
|
|
65
|
+
import {
|
|
66
|
+
pgTable,
|
|
67
|
+
bigint,
|
|
68
|
+
text,
|
|
69
|
+
vector,
|
|
70
|
+
index,
|
|
71
|
+
customType,
|
|
72
|
+
} from "drizzle-orm/pg-core";
|
|
61
73
|
import { sql } from "drizzle-orm";
|
|
62
74
|
|
|
63
75
|
const tsvector = customType<{ data: string }>({
|
|
@@ -69,10 +81,12 @@ const tsvector = customType<{ data: string }>({
|
|
|
69
81
|
export const documents = pgTable(
|
|
70
82
|
"documents",
|
|
71
83
|
{
|
|
72
|
-
id: bigint("id", { mode: "number" })
|
|
84
|
+
id: bigint("id", { mode: "number" })
|
|
85
|
+
.generatedByDefaultAsIdentity()
|
|
86
|
+
.primaryKey(),
|
|
73
87
|
title: text("title").notNull(),
|
|
74
88
|
body: text("body").notNull(),
|
|
75
|
-
embedding: vector("embedding", { dimensions:
|
|
89
|
+
embedding: vector("embedding", { dimensions: 1024 }),
|
|
76
90
|
bodyTsv: tsvector("body_tsv").generatedAlwaysAs(
|
|
77
91
|
sql`to_tsvector('english', "body")`,
|
|
78
92
|
),
|
|
@@ -86,7 +100,7 @@ export const documents = pgTable(
|
|
|
86
100
|
);
|
|
87
101
|
```
|
|
88
102
|
|
|
89
|
-
|
|
103
|
+
The 1024-dimensional column is an example; set it to the output dimension of your selected embedding model. Use the same model and dimensions for stored documents and queries. Postgres maintains `body_tsv`, so never write it from the app. Generate and apply the migration after the extensions migration above:
|
|
90
104
|
|
|
91
105
|
```bash
|
|
92
106
|
npx drizzle-kit generate --name=lakebase_search
|
|
@@ -106,6 +120,66 @@ npx drizzle-kit generate --custom --name=bm25_index
|
|
|
106
120
|
CREATE INDEX documents_body_bm25 ON documents USING lakebase_bm25 (body_tsv);
|
|
107
121
|
```
|
|
108
122
|
|
|
123
|
+
## Generate and Store Embeddings
|
|
124
|
+
|
|
125
|
+
Use the [Vercel AI SDK](https://ai-sdk.dev) (`ai`, 6+) with Neon's `@neon/ai-sdk-provider` 1.0.0+. Follow the [gateway setup](vector-search.md#prepare-embeddings), then install the packages with `npm install @neon/ai-sdk-provider ai dotenv`:
|
|
126
|
+
|
|
127
|
+
```typescript
|
|
128
|
+
import "dotenv/config";
|
|
129
|
+
import { neon } from "@neon/ai-sdk-provider";
|
|
130
|
+
import { embed, embedMany } from "ai";
|
|
131
|
+
|
|
132
|
+
const embeddingModel = neon.embeddingModel("qwen3-embedding-0-6b");
|
|
133
|
+
const providerOptions = { neon: { dimensions: 1024 } };
|
|
134
|
+
// Qwen3 query prompt adapted for Neon documentation search; documents stay unprefixed.
|
|
135
|
+
const queryPrompt =
|
|
136
|
+
"Instruct: Given a question about Neon, retrieve documentation passages that answer the question\nQuery: ";
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Generate a document vector, then insert it with Drizzle:
|
|
140
|
+
|
|
141
|
+
```typescript
|
|
142
|
+
const { embedding } = await embed({
|
|
143
|
+
model: embeddingModel,
|
|
144
|
+
value: body,
|
|
145
|
+
providerOptions,
|
|
146
|
+
});
|
|
147
|
+
await db.insert(documents).values({
|
|
148
|
+
title,
|
|
149
|
+
body,
|
|
150
|
+
embedding,
|
|
151
|
+
});
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
For bulk imports, skip blank rows and embed/insert one batch at a time:
|
|
155
|
+
|
|
156
|
+
```typescript
|
|
157
|
+
const batchSize = 64;
|
|
158
|
+
const nonBlankRows = rows.filter((row) => row && row.body.trim().length > 0);
|
|
159
|
+
|
|
160
|
+
for (let offset = 0; offset < nonBlankRows.length; offset += batchSize) {
|
|
161
|
+
const batch = nonBlankRows.slice(offset, offset + batchSize);
|
|
162
|
+
const { embeddings: vectors } = await embedMany({
|
|
163
|
+
model: embeddingModel,
|
|
164
|
+
values: batch.map((row) => row.body),
|
|
165
|
+
providerOptions,
|
|
166
|
+
maxParallelCalls: 1,
|
|
167
|
+
});
|
|
168
|
+
await db.insert(documents).values(
|
|
169
|
+
batch.map((row, index) => {
|
|
170
|
+
const embedding = vectors[index];
|
|
171
|
+
if (!embedding)
|
|
172
|
+
throw new Error(`Missing embedding for batch row ${index}`);
|
|
173
|
+
return { ...row, embedding };
|
|
174
|
+
}),
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
`embedMany` splits embedding requests using the provider's per-request input limit. This loop also bounds database inserts and memory; tune `batchSize` for your workload. Chunk long documents before embedding. Earlier batches stay committed if a later batch fails.
|
|
180
|
+
|
|
181
|
+
Apply `queryPrompt` only to queries, keeping the original text for BM25. Use the same model and dimensions for documents and queries; re-embed documents when switching models.
|
|
182
|
+
|
|
109
183
|
## Query
|
|
110
184
|
|
|
111
185
|
Use the query builder with Drizzle's `cosineDistance` helper for vector search. It emits the `<=>` operator, so keep the index on `vector_cosine_ops`:
|
|
@@ -114,7 +188,11 @@ Use the query builder with Drizzle's `cosineDistance` helper for vector search.
|
|
|
114
188
|
import { cosineDistance } from "drizzle-orm";
|
|
115
189
|
import { documents } from "./schema";
|
|
116
190
|
|
|
117
|
-
|
|
191
|
+
const { embedding: queryEmbedding } = await embed({
|
|
192
|
+
model: embeddingModel,
|
|
193
|
+
value: `${queryPrompt}${queryText}`,
|
|
194
|
+
providerOptions,
|
|
195
|
+
});
|
|
118
196
|
const distance = cosineDistance(documents.embedding, queryEmbedding);
|
|
119
197
|
|
|
120
198
|
const rows = await db
|
|
@@ -130,17 +208,23 @@ BM25 has no Drizzle helper: `<@>` and `to_bm25query` require raw SQL. Reference
|
|
|
130
208
|
import { sql } from "drizzle-orm";
|
|
131
209
|
|
|
132
210
|
const rows = await db.execute(sql`
|
|
133
|
-
SELECT id, title,
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
211
|
+
SELECT id, title, score
|
|
212
|
+
FROM (
|
|
213
|
+
SELECT id, title,
|
|
214
|
+
body_tsv <@> to_bm25query(
|
|
215
|
+
to_tsvector('english', ${queryText}),
|
|
216
|
+
'documents_body_bm25'::regclass
|
|
217
|
+
) AS score
|
|
218
|
+
FROM documents
|
|
219
|
+
) AS keyword_scored
|
|
220
|
+
WHERE score < 0
|
|
139
221
|
ORDER BY score
|
|
140
222
|
LIMIT ${k}
|
|
141
223
|
`);
|
|
142
224
|
```
|
|
143
225
|
|
|
226
|
+
Filter `score < 0` before the candidate cutoff: scalar BM25 scoring returns zero for non-matches, which must not become keyword hits. Partial query-term matches remain eligible.
|
|
227
|
+
|
|
144
228
|
Run the [hybrid search](hybrid-search.md) RRF query the same way: raw SQL through `db.execute`.
|
|
145
229
|
|
|
146
230
|
## Tune Per Query
|
|
@@ -168,5 +252,6 @@ const rows = await db.transaction(async (tx) => {
|
|
|
168
252
|
|
|
169
253
|
Sources:
|
|
170
254
|
|
|
255
|
+
- [AI Gateway embeddings](https://neon.com/docs/ai-gateway/embeddings)
|
|
171
256
|
- [Get started with Lakebase Search](https://neon.com/docs/ai/lakebase-search-get-started)
|
|
172
|
-
- [Schema migration with Lakebase Postgres and Drizzle ORM](https://neon.com/docs/guides/drizzle-migrations)
|
|
257
|
+
- [Schema migration with Lakebase Postgres and Drizzle ORM](https://neon.com/docs/guides/drizzle-migrations)
|
|
@@ -5,7 +5,7 @@ Use `lakebase_vector` for approximate nearest-neighbor retrieval over embeddings
|
|
|
5
5
|
## Contents
|
|
6
6
|
|
|
7
7
|
- [Create the extension](#create-the-extension) — enable `lakebase_vector` and its `pgvector` dependency
|
|
8
|
-
- [Prepare embeddings](#prepare-embeddings) —
|
|
8
|
+
- [Prepare embeddings](#prepare-embeddings) — generate vectors with the AI Gateway and match the column dimension
|
|
9
9
|
- [Build the index](#build-the-index) — match the distance metric, operator class, and query operator
|
|
10
10
|
- [Tune the index](#tune-the-index) — configure index-build options and concurrent index management
|
|
11
11
|
- [Query](#query) — rank by vector distance or filter by a similarity radius
|
|
@@ -24,28 +24,111 @@ CREATE EXTENSION IF NOT EXISTS lakebase_vector CASCADE;
|
|
|
24
24
|
|
|
25
25
|
## Prepare Embeddings
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
Neon's [AI Gateway embeddings endpoint](https://neon.com/docs/ai-gateway/embeddings) is an OpenAI-compatible way to generate vectors for Lakebase Search. This table uses 1024 dimensions as an example; set the column dimension to the output of the model and any `dimensions` parameter you choose:
|
|
28
28
|
|
|
29
29
|
```sql
|
|
30
30
|
CREATE TABLE documents (
|
|
31
31
|
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
|
32
32
|
title text NOT NULL,
|
|
33
33
|
body text NOT NULL,
|
|
34
|
-
embedding vector(
|
|
34
|
+
embedding vector(1024)
|
|
35
35
|
);
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
Enable the AI Gateway on the branch and get `NEON_AI_GATEWAY_TOKEN` and the bare-host `NEON_AI_GATEWAY_BASE_URL`:
|
|
39
|
+
|
|
40
|
+
- With `neon.ts`, declare `aiGateway: true`, run `neon deploy`, then run `neon env pull --file .env`.
|
|
41
|
+
- Without `neon.ts`, run `neon env pull --service ai-gateway --file .env` from a directory linked to the intended project and branch. This requests the gateway variables explicitly and skips other services.
|
|
42
|
+
- Alternatively, get both values from the Neon Console. Neon Functions receive them automatically.
|
|
43
|
+
|
|
44
|
+
### AI SDK (Recommended)
|
|
45
|
+
|
|
46
|
+
For TypeScript apps, use Neon's `@neon/ai-sdk-provider` 1.0.0+ with the [Vercel AI SDK](https://ai-sdk.dev) (`ai`, 6+) (`npm install @neon/ai-sdk-provider ai dotenv`). The provider reads `NEON_AI_GATEWAY_TOKEN` and `NEON_AI_GATEWAY_BASE_URL` directly and sends embedding requests to `/v1/embeddings`. Load `.env` in a standalone app; Neon Functions inject the variables automatically.
|
|
47
|
+
|
|
48
|
+
```typescript
|
|
49
|
+
import "dotenv/config";
|
|
50
|
+
import { neon } from "@neon/ai-sdk-provider";
|
|
51
|
+
import { embed, embedMany } from "ai";
|
|
52
|
+
|
|
53
|
+
const embeddingModel = neon.embeddingModel("qwen3-embedding-0-6b");
|
|
54
|
+
const providerOptions = { neon: { dimensions: 1024 } };
|
|
55
|
+
// Qwen3 query prompt adapted for Neon documentation search; documents stay unprefixed.
|
|
56
|
+
const queryPrompt =
|
|
57
|
+
"Instruct: Given a question about Neon, retrieve documentation passages that answer the question\nQuery: ";
|
|
58
|
+
|
|
59
|
+
const { embeddings: documentEmbeddings } = await embedMany({
|
|
60
|
+
model: embeddingModel,
|
|
61
|
+
values: documentBodies, // non-empty document batch; store vectors by input index
|
|
62
|
+
providerOptions,
|
|
63
|
+
maxParallelCalls: 1,
|
|
64
|
+
});
|
|
65
|
+
const { embedding: queryEmbedding } = await embed({
|
|
66
|
+
model: embeddingModel,
|
|
67
|
+
value: `${queryPrompt}${queryText}`,
|
|
68
|
+
providerOptions,
|
|
69
|
+
}); // bind to $1 below
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Skip empty imports before calling `embedMany`. It returns vectors in input order and splits requests according to the provider's item limit. For large imports, also split document text within the endpoint's token limits and keep database writes bounded.
|
|
73
|
+
|
|
74
|
+
For Neon documentation search, the example adapts the task instruction in Qwen3's stored `query` prompt from [config_sentence_transformers.json](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B/blob/main/config_sentence_transformers.json). Its `document` prompt is empty, so document text stays unprefixed. Neither SDK applies SentenceTransformers prompts automatically. Keep the original `queryText` for BM25, and use the selected model's own prompt conventions if you switch models.
|
|
75
|
+
|
|
76
|
+
### OpenAI SDK Alternative
|
|
77
|
+
|
|
78
|
+
For an existing OpenAI SDK integration, install `openai` and `dotenv` (`npm install openai dotenv`) and configure the client explicitly:
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
import "dotenv/config";
|
|
82
|
+
import OpenAI from "openai";
|
|
83
|
+
|
|
84
|
+
const apiKey = process.env.NEON_AI_GATEWAY_TOKEN;
|
|
85
|
+
const gatewayBaseUrl = process.env.NEON_AI_GATEWAY_BASE_URL;
|
|
86
|
+
if (!apiKey || !gatewayBaseUrl) {
|
|
87
|
+
throw new Error("Missing Neon AI Gateway credentials");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const client = new OpenAI({
|
|
91
|
+
apiKey,
|
|
92
|
+
baseURL: `${gatewayBaseUrl}/v1`,
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
async function embedBatch(inputs: string[]): Promise<number[][]> {
|
|
96
|
+
if (inputs.length === 0) return [];
|
|
97
|
+
const response = await client.embeddings.create({
|
|
98
|
+
model: "qwen3-embedding-0-6b",
|
|
99
|
+
input: inputs,
|
|
100
|
+
dimensions: 1024,
|
|
101
|
+
encoding_format: "float",
|
|
102
|
+
});
|
|
103
|
+
const vectors: number[][] = [];
|
|
104
|
+
for (const item of response.data) vectors[item.index] = item.embedding;
|
|
105
|
+
return inputs.map((_, index) => {
|
|
106
|
+
const embedding = vectors[index];
|
|
107
|
+
if (!embedding) throw new Error(`Missing embedding for input ${index}`);
|
|
108
|
+
return embedding;
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const documentEmbeddings = await embedBatch(documentBodies);
|
|
113
|
+
const [queryEmbedding] = await embedBatch([`${queryPrompt}${queryText}`]);
|
|
114
|
+
if (!queryEmbedding) throw new Error("Missing query embedding");
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Use the same `queryPrompt` defined above, only for query inputs. Keep each batch within the endpoint's input and rate limits, and pair each vector with its source row using the response `index`. The [OpenAI JavaScript SDK v6](https://github.com/openai/openai-node/blob/v6.0.0/src/resources/embeddings.ts) defaults to requesting base64 and decodes the response as base64. If a compatible endpoint returns float arrays instead, that decoder can silently turn them into zeros. Pass `encoding_format: "float"` explicitly for the AI Gateway; the SDK then returns the float arrays directly. Base64 can reduce response size when an endpoint actually returns base64, but do not assume that format for this gateway.
|
|
118
|
+
|
|
119
|
+
Use the same model and output dimensions for stored documents and queries. Follow the model's input conventions: some models recommend a query instruction while document text remains unprefixed. If the model supports shorter vectors, compare retrieval quality, storage, and latency before changing dimensions; set the column and both embedding requests to the chosen size. Switching models requires re-embedding the corpus; changing dimensions also requires migrating the vector column and index. Generate embeddings in the application, outside SQL, unless the architecture already provides an in-database embedding function. Other embedding providers are also valid when their output matches the schema and index.
|
|
39
120
|
|
|
40
121
|
## Build the Index
|
|
41
122
|
|
|
42
123
|
Choose the operator class and query operator as a matched pair:
|
|
43
124
|
|
|
44
|
-
| Metric
|
|
45
|
-
|
|
|
46
|
-
| Cosine
|
|
47
|
-
| L2 / Euclidean | Absolute distance matters; vectors do not need normalization | `vector_l2_ops`
|
|
48
|
-
| Inner product
|
|
125
|
+
| Metric | Common use | Operator class | Distance operator |
|
|
126
|
+
| -------------- | ------------------------------------------------------------ | ------------------- | ----------------- |
|
|
127
|
+
| Cosine | Most text embeddings | `vector_cosine_ops` | `<=>` |
|
|
128
|
+
| L2 / Euclidean | Absolute distance matters; vectors do not need normalization | `vector_l2_ops` | `<->` |
|
|
129
|
+
| Inner product | Unit-normalized vectors; matches cosine for unit vectors | `vector_ip_ops` | `<#>` |
|
|
130
|
+
|
|
131
|
+
Choose the metric recommended for the selected model, and keep its index operator class and query operator aligned. The [Qwen3 Embedding model card](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B) demonstrates cosine similarity and normalized dot product for retrieval. For unit-normalized vectors, cosine, inner product, and L2 have the same exact ranking; approximate indexes can still differ in recall and latency, so benchmark on your corpus.
|
|
49
132
|
|
|
50
133
|
```sql
|
|
51
134
|
CREATE INDEX documents_embedding_ann ON documents
|
|
@@ -79,7 +162,7 @@ For a large table, use `CREATE INDEX CONCURRENTLY` to avoid locking out writes w
|
|
|
79
162
|
|
|
80
163
|
## Query
|
|
81
164
|
|
|
82
|
-
Generate the query embedding with the same model and
|
|
165
|
+
Generate the query embedding with the same model and dimensions used for stored documents, following the model's query-input conventions (using the Qwen3 query prompt shown above), then bind it as a parameter:
|
|
83
166
|
|
|
84
167
|
```sql
|
|
85
168
|
SELECT id, title, embedding <=> $1::vector AS distance
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: neon-realtime
|
|
3
|
+
description: >-
|
|
4
|
+
Neon Realtime makes any SQL query live. Build realtime, reactive apps and agents on Lakebase Postgres with live SQL queries and reactivity primitives. Use when app UI or agent state must update live from database rows (dashboards, feeds, collaboration, multi-user or multi-device sync), for optimistic mutations, or to replace polling or other realtime sync systems. Triggers include "live query", "subscribe", "sync engine", "useLiveQuery", "TanStack DB", "optimistic updates", "@neon/realtime". For push that doesn't come from database rows (presence, typing, LLM streams), use neon-functions.
|
|
5
|
+
metadata:
|
|
6
|
+
parent: neon
|
|
7
|
+
source: https://github.com/neondatabase/agent-skills/tree/main/skills/neon-realtime
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
**FIRST**: Use the parent `neon` skill for a Neon overview, getting started with Neon, Neon development best practices, and more.
|
|
11
|
+
|
|
12
|
+
If the `neon` skill is not installed, fetch it from https://neon.com/docs/ai/skills/neon/SKILL.md or install it with:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
neon skills -s neon -y
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
# Neon Realtime
|
|
19
|
+
|
|
20
|
+
Neon's Realtime makes any SQL query live. Subscribe in realtime to your Lakebase Postgres database. Develop apps and agents with end-to-end reactivity using type-safe live queries and optimistic mutations.
|
|
21
|
+
|
|
22
|
+
Realtime is new and in beta, so its APIs aren't in your training data. Start from the core pattern below, and read each section's reference file before writing that code.
|
|
23
|
+
|
|
24
|
+
## How It Works
|
|
25
|
+
|
|
26
|
+
Realtime's layers compose: a live query engine inside Postgres, the Live SQL API (a WebSocket API), lower-level client SDKs (`seal()`, `subscribe()`), and reactivity primitives such as `useLiveQuery`.
|
|
27
|
+
|
|
28
|
+
1. In trusted backend code, **define** a live query (any read-only SQL, including joins, aggregates, ordering and limits), **seal** it with `NEON_REALTIME_SECRET` and **expose** it from an authenticated endpoint or server function. The client can't read or change a sealed query's SQL or parameters.
|
|
29
|
+
2. The client **subscribes** with the sealed query. It receives the full initial result, then each committed transaction's changes as one batch. Results stay consistent, but delivery of every change event isn't guaranteed.
|
|
30
|
+
3. **Writes** go through your own API, which returns each write's `txid` for `awaitTxId()`.
|
|
31
|
+
|
|
32
|
+
## Core Pattern
|
|
33
|
+
|
|
34
|
+
The guides' chat app, with `messages` authorized through `channel_members`. The backend seals the query and returns each write's `txid`:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { createRealtime, rawSql } from "@neon/realtime/server"
|
|
38
|
+
import { drizzleAdapter } from "@neon/realtime-drizzle"
|
|
39
|
+
import { and, desc, eq, getTableColumns, sql } from "drizzle-orm"
|
|
40
|
+
import { Hono } from "hono"
|
|
41
|
+
import { HTTPException } from "hono/http-exception"
|
|
42
|
+
import { requireUser } from "./auth"
|
|
43
|
+
import { db } from "./db"
|
|
44
|
+
import { channelMembers, messages, type Message } from "./schema"
|
|
45
|
+
|
|
46
|
+
export const realtime = createRealtime({ secret: process.env.NEON_REALTIME_SECRET!, db: "neondb", adapter: drizzleAdapter() })
|
|
47
|
+
|
|
48
|
+
// Each selected key must match its column name
|
|
49
|
+
export function messagesQuery(userId: string, channelId: number) {
|
|
50
|
+
return db
|
|
51
|
+
.select(getTableColumns(messages)).from(messages)
|
|
52
|
+
.innerJoin(channelMembers, eq(channelMembers.channel_id, messages.channel_id))
|
|
53
|
+
.where(and(eq(channelMembers.user_id, userId), eq(messages.channel_id, channelId)))
|
|
54
|
+
.orderBy(desc(messages.created_at))
|
|
55
|
+
.limit(50)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Or raw SQL
|
|
59
|
+
const rawMessagesQuery = (userId: string, channelId: number) => rawSql<Message>(
|
|
60
|
+
`SELECT messages.author_id, messages.body, messages.channel_id, messages.created_at, messages.id FROM messages
|
|
61
|
+
INNER JOIN channel_members ON channel_members.channel_id = messages.channel_id WHERE channel_members.user_id = $1 AND messages.channel_id = $2 ORDER BY messages.created_at DESC LIMIT 50`,
|
|
62
|
+
[userId, channelId]
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
// The id of the transaction that made the change, read in the write's own RETURNING
|
|
66
|
+
const txid = sql<string>`pg_current_xact_id()::text`
|
|
67
|
+
|
|
68
|
+
const app = new Hono()
|
|
69
|
+
.post("/api/v1/messages/live", async (c) => {
|
|
70
|
+
const user = await requireUser(c)
|
|
71
|
+
const { channelId } = await c.req.json<{ channelId: number }>() // validate input
|
|
72
|
+
return c.json(await realtime.seal({ query: messagesQuery(user.id, channelId) }))
|
|
73
|
+
})
|
|
74
|
+
.post("/api/v1/messages", async (c) => {
|
|
75
|
+
const user = await requireUser(c)
|
|
76
|
+
const { id, channelId, body } = await c.req.json<{ id: string; channelId: number; body: string }>() // validate input
|
|
77
|
+
// One statement. The membership row supplies channel_id and author_id, so only a member's message is inserted.
|
|
78
|
+
// List every column in table order, alias each sql field, and cast untyped params (they resolve to text)
|
|
79
|
+
const [sent] = await db.insert(messages).select(
|
|
80
|
+
db.select({
|
|
81
|
+
id: sql`${id}::uuid`.as("id"), channel_id: channelMembers.channel_id, author_id: channelMembers.user_id,
|
|
82
|
+
body: sql`${body}`.as("body"), created_at: sql`now()`.as("created_at"),
|
|
83
|
+
})
|
|
84
|
+
.from(channelMembers)
|
|
85
|
+
.where(and(eq(channelMembers.channel_id, channelId), eq(channelMembers.user_id, user.id)))
|
|
86
|
+
).returning({ txid })
|
|
87
|
+
if (!sent) throw new HTTPException(403, { message: "Not a member of this channel" })
|
|
88
|
+
return c.json({ kind: "committed", txid: sent.txid })
|
|
89
|
+
})
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
The React frontend subscribes and sends optimistic messages:
|
|
93
|
+
|
|
94
|
+
```tsx
|
|
95
|
+
import { createRealtimeClient, type SealedLiveQuery } from "@neon/realtime/client"
|
|
96
|
+
import { drizzleParsers } from "@neon/realtime-drizzle/client"
|
|
97
|
+
import { useLiveQuery } from "@neon/realtime-react"
|
|
98
|
+
import { startTransition, useCallback, useOptimistic } from "react"
|
|
99
|
+
import type { Message } from "../backend/schema"
|
|
100
|
+
import { fetchSealedMessages, sendMessage } from "./api"
|
|
101
|
+
|
|
102
|
+
// One client per app, because subscriptions share its connection. Wrap the app in <RealtimeProvider client={client}>
|
|
103
|
+
export const client = createRealtimeClient({ url: import.meta.env.VITE_NEON_REALTIME_URL, parsers: { ...drizzleParsers } })
|
|
104
|
+
|
|
105
|
+
const NO_MESSAGES: readonly Message[] = []
|
|
106
|
+
type Props = { sealedQuery: SealedLiveQuery<Message>; channelId: number; userId: string }
|
|
107
|
+
|
|
108
|
+
export function Messages({ sealedQuery, channelId, userId }: Props) {
|
|
109
|
+
const refreshQuery = useCallback(() => fetchSealedMessages(channelId), [channelId])
|
|
110
|
+
const { data, status, error, utils } = useLiveQuery(sealedQuery, { refreshQuery })
|
|
111
|
+
// Once the sent message syncs, show only the synced row
|
|
112
|
+
const [messages, addOptimistic] = useOptimistic(data ?? NO_MESSAGES, (current, message: Message) =>
|
|
113
|
+
current.some(({ id }) => id === message.id) ? current : [message, ...current]
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
function send(body: string) {
|
|
117
|
+
// The server sets author and timestamp but keeps this id
|
|
118
|
+
const message = { id: crypto.randomUUID(), channel_id: channelId, author_id: userId, body, created_at: new Date() }
|
|
119
|
+
startTransition(async () => {
|
|
120
|
+
addOptimistic(message)
|
|
121
|
+
try {
|
|
122
|
+
const result = await sendMessage(message) // maps channel_id to channelId
|
|
123
|
+
if (result.kind === "committed") await utils.awaitTxId(result.txid, 10_000)
|
|
124
|
+
} catch { /* show "Couldn't confirm the change" */ }
|
|
125
|
+
})
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (status === "error") return <p role="alert">Live updates stopped: {error.message}</p>
|
|
129
|
+
if (data === undefined) return <p>Loading messages</p>
|
|
130
|
+
return (
|
|
131
|
+
<form action={(form) => send(String(form.get("body")))}>
|
|
132
|
+
<input name="body" required />
|
|
133
|
+
<ul>{messages.map((message) => <li key={message.id}>{message.body}</li>)}</ul>
|
|
134
|
+
</form>
|
|
135
|
+
)
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Choose the Stack
|
|
140
|
+
|
|
141
|
+
A live query replaces fetching app data from an API or another sync system. Reuse existing query code, and use the highest layer that fits rather than wiring changes into app state by hand.
|
|
142
|
+
|
|
143
|
+
| Use | For |
|
|
144
|
+
| --- | --- |
|
|
145
|
+
| `drizzleAdapter()` from `@neon/realtime-drizzle`, or `kyselyAdapter()` from `@neon/realtime-kysely` | Queries written in Drizzle or Kysely |
|
|
146
|
+
| `rawSql` from `@neon/realtime/server` | Any other ORM, or none |
|
|
147
|
+
| `useLiveQuery` from `@neon/realtime-react` | React. Binds one sealed query to a component's state |
|
|
148
|
+
| `realtimeCollectionOptions` from `@neon/realtime-tanstack` | Many views over the same data, or an app on TanStack DB. Oversync one broader query into a collection, then derive local live queries from it |
|
|
149
|
+
| `client.subscribe()` from `@neon/realtime/client` | Other frameworks |
|
|
150
|
+
| `realtime.subscribe()` from `@neon/realtime/server` | Agents and workers, in trusted backend code |
|
|
151
|
+
|
|
152
|
+
Migrating from Electric: Realtime is a drop-in replacement for Electric's role in your stack. Live SQL queries replace shapes, and `realtimeCollectionOptions()` replaces `electricCollectionOptions()`.
|
|
153
|
+
|
|
154
|
+
## Setup
|
|
155
|
+
|
|
156
|
+
- **New app:** `neon bootstrap my-app --template realtime-react`, then `neon deploy` in `my-app`.
|
|
157
|
+
- **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
|
+
- **Tables** need a [stable replica identity](references/queries.md#table-requirements); a primary key is enough.
|
|
159
|
+
- **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`.
|
|
160
|
+
- **Install** `@neon/realtime` and the packages chosen above. Use these SDKs, not the still-evolving WebSocket protocol.
|
|
161
|
+
|
|
162
|
+
## Define and Seal Queries
|
|
163
|
+
|
|
164
|
+
Read [references/queries.md](references/queries.md) before writing query or sealing code, including Kysely and server functions.
|
|
165
|
+
|
|
166
|
+
- **Read-only and deterministic.** A raw query is a single `SELECT` with no `;` and `$1` placeholders. It can't call `now()` or `gen_random_uuid()`, so pass such values as parameters, wrapping every value except strings, numbers, booleans, bigints and null in a `pgParam` helper (`pgParam.timestamptz(date)`).
|
|
167
|
+
- **Authorize in the query.** Check the session before sealing, and join through your membership tables so revoked access drops out. Any web framework auth works, including Managed Better Auth, but not [RLS](references/queries.md#why-not-row-level-security) yet. See [Authorization](references/queries.md#authorization).
|
|
168
|
+
- **A sealed query is a bearer token.** Keep it out of URLs, logs and persistent storage, and never fill its parameters from unchecked input.
|
|
169
|
+
- **Check a query** before wiring it in: [`neon realtime subscribe "SELECT ..."`](https://neon.com/docs/cli/realtime.md#subscribe) prints the initial result, then each transaction's changes, until you stop it. With `--output json`, each change prints a full snapshot. Set `debugMode` on `createRealtime` for full database errors (development only).
|
|
170
|
+
- **Sealed queries expire.** Pass `refreshQuery` to the bindings or call `renew()`, sealing the same query and parameters, or the subscription errors. New parameters need a new sealed query and subscription. In Next.js, renew from a Route Handler, because server actions run one at a time.
|
|
171
|
+
|
|
172
|
+
## Subscribe
|
|
173
|
+
|
|
174
|
+
Read [references/reactivity.md](references/reactivity.md) before writing React or TanStack DB code. Read [references/subscribing.md](references/subscribing.md) before subscribing directly with `client.subscribe(sealed)` (`getSnapshot`, `onChange`, `onStateChange`), or from agents and workers, which add `url` to `createRealtime` and `await realtime.subscribe(query)` to seal in-process.
|
|
175
|
+
|
|
176
|
+
- **One database per client.** The first sealed query binds the connection to its `db`.
|
|
177
|
+
- **Select a stable, unique key for every row** and key rows by it, including TanStack DB's `getKey`: usually the primary key, the grouped columns for aggregates, or the combined keys for joins that repeat a row. Never use `rowId`, which every `rows` update invalidates.
|
|
178
|
+
- **`error` is final**, even after `renew()`. Fetch a fresh sealed query and subscribe again, with a new client if the connection failed. Watch `onStateChange` on direct subscriptions; `useLiveQuery()` reports errors through `status`, not by throwing or suspending.
|
|
179
|
+
- **When the session changes, leave with a full page load.** It drops the Realtime client, any TanStack `DbClient` and the previous user's rows. The hook retries a failed renewal every second, so stop renewing once one fails as signed out. Check on every renewal and write that the session's user is the one the page was loaded for, or a write from the old page lands in the new user's account. See [When the session changes](references/ssr.md#when-the-session-changes).
|
|
180
|
+
|
|
181
|
+
## Optimistic Writes
|
|
182
|
+
|
|
183
|
+
Realtime has no write path, so writes keep your backend's usual auth. Read [references/mutations.md](references/mutations.md) before writing mutations, for each layer.
|
|
184
|
+
|
|
185
|
+
- [Return the txid from the write itself](references/mutations.md#returning-the-txid-from-your-backend): `` .returning({ txid: sql<string>`pg_current_xact_id()::text` }) ``, in one round trip on any Postgres driver. Write a batch in one statement, so there's one txid. Never open `db.transaction()` just to `select pg_current_xact_id()`: that's four round trips holding a pooled connection. When a write genuinely needs several statements, put the txid in the `RETURNING` of a write that always changes a row.
|
|
186
|
+
- Always pass `awaitTxId()` a timeout: it keeps waiting through reconnects and renewals, and never settles if the txid doesn't reach the query.
|
|
187
|
+
- A write that changes no rows has no txid, so skip `awaitTxId()` and let the optimistic state drop.
|
|
188
|
+
|
|
189
|
+
## Server-Side Rendering
|
|
190
|
+
|
|
191
|
+
Read [references/ssr.md](references/ssr.md) before rendering live queries on the server, for Next.js and TanStack Start.
|
|
192
|
+
|
|
193
|
+
- Create the client in a `useState` initializer rather than at module level, render `initialData` as live rows without a loading state, and never share a TanStack `DbClient` between requests.
|
|
194
|
+
- Keep row shapes identical on both sides. `JSON.stringify` turns dates into strings, and `int8` and `numeric` arrive as strings.
|
|
195
|
+
|
|
196
|
+
## More Docs
|
|
197
|
+
|
|
198
|
+
| Task | Page |
|
|
199
|
+
| --- | --- |
|
|
200
|
+
| Beta scope, regions, pricing, FAQ, other systems | [Overview](https://neon.com/docs/realtime/overview.md) |
|
|
201
|
+
| Architecture and consistency | [How it works](https://neon.com/docs/realtime/how-it-works.md) |
|
|
202
|
+
| A first live query | [Quickstart](https://neon.com/docs/realtime/quickstart.md) |
|
|
203
|
+
| Every SDK export | [TypeScript SDK reference](https://neon.com/docs/realtime/sdks/typescript.md) |
|
|
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) |
|
|
205
|
+
| Live agent workflows | [Mastra](https://neon.com/docs/realtime/examples/mastra.md) |
|
|
206
|
+
| ORM adapters | [Drizzle](https://neon.com/docs/realtime/examples/drizzle.md), [Kysely](https://neon.com/docs/realtime/examples/kysely.md) |
|