@neon/skills 0.0.0 → 1.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/LICENSE +202 -0
- package/README.md +164 -1
- package/mcp.json +9 -0
- package/package.json +52 -2
- package/plugin.json +14 -0
- package/skills/neon/SKILL.md +490 -0
- package/skills/neon/references/claimable-neon.md +121 -0
- package/skills/neon-ai-gateway/SKILL.md +315 -0
- package/skills/neon-functions/SKILL.md +619 -0
- package/skills/neon-functions/references/ai-sdk.md +145 -0
- package/skills/neon-functions/references/mastra-studio.md +127 -0
- package/skills/neon-functions/references/mcp.md +146 -0
- package/skills/neon-functions/references/sentry.md +244 -0
- package/skills/neon-functions/references/sse.md +163 -0
- package/skills/neon-object-storage/SKILL.md +228 -0
- package/skills/neon-postgres/SKILL.md +193 -0
- package/skills/neon-postgres/references/full-text-search.md +99 -0
- package/skills/neon-postgres/references/hybrid-search.md +90 -0
- package/skills/neon-postgres/references/vector-search.md +137 -0
- package/skills/neon-postgres-branches/SKILL.md +292 -0
- package/skills/neon-postgres-egress-optimizer/SKILL.md +266 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
# Server-sent events (SSE) on Neon Functions
|
|
2
|
+
|
|
3
|
+
SSE is the one-way (server → client) streaming counterpart to WebSockets: the browser opens a long-lived `GET` with [`EventSource`](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) and the server pushes text frames down it. On Neon Functions an SSE endpoint is just a normal `fetch` handler that returns a `Response` whose body is a `ReadableStream` with `Content-Type: text/event-stream` — there is no library to install and nothing to upgrade. The runtime holds the response open as long as bytes keep flowing (15-minute heartbeat, see [Timeouts](../SKILL.md#timeouts-and-runtime-limits)).
|
|
4
|
+
|
|
5
|
+
Reach for SSE over WebSockets when you only need server → client updates (live counters, notifications, progress, token streams) — it's simpler to run (plain HTTP, no `upgrade`), and `EventSource` **reconnects on its own**, so there's no client backoff to write.
|
|
6
|
+
|
|
7
|
+
## Minimal SSE endpoint (no framework)
|
|
8
|
+
|
|
9
|
+
A function's default export is `{ fetch }`; SSE needs nothing more. Return a `ReadableStream` and write `data:` frames into it:
|
|
10
|
+
|
|
11
|
+
```typescript
|
|
12
|
+
// src/index.ts
|
|
13
|
+
const encoder = new TextEncoder();
|
|
14
|
+
|
|
15
|
+
export default {
|
|
16
|
+
fetch(request: Request): Response {
|
|
17
|
+
const url = new URL(request.url);
|
|
18
|
+
if (url.pathname !== "/events") return new Response("ok");
|
|
19
|
+
|
|
20
|
+
let timer: ReturnType<typeof setInterval>;
|
|
21
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
22
|
+
start(controller) {
|
|
23
|
+
// An SSE frame is `data: <payload>\n\n`. A line starting with `:` is a
|
|
24
|
+
// comment — used here as a heartbeat to keep the stream from going idle.
|
|
25
|
+
controller.enqueue(encoder.encode("data: hello\n\n"));
|
|
26
|
+
timer = setInterval(
|
|
27
|
+
() => controller.enqueue(encoder.encode(": ping\n\n")),
|
|
28
|
+
25_000,
|
|
29
|
+
);
|
|
30
|
+
},
|
|
31
|
+
// cancel() fires when the client disconnects.
|
|
32
|
+
cancel() {
|
|
33
|
+
clearInterval(timer);
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
return new Response(stream, {
|
|
38
|
+
headers: {
|
|
39
|
+
"Content-Type": "text/event-stream",
|
|
40
|
+
"Cache-Control": "no-cache, no-transform",
|
|
41
|
+
Connection: "keep-alive",
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
> `cancel()` is a method on the stream's underlying source; it fires when the client disconnects. Use it to drop the client from any broadcast set and clear timers. A cleanup function returned from `start()` is ignored, so it has to be a real `cancel()` method.
|
|
49
|
+
|
|
50
|
+
## With Hono
|
|
51
|
+
|
|
52
|
+
Hono routes the HTTP side; the SSE response is the same `ReadableStream`. Returning a raw `Response` keeps full control over the stream (and sidesteps concurrent-write edge cases in stream helpers):
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
// src/index.ts
|
|
56
|
+
import { Hono } from "hono";
|
|
57
|
+
import { cors } from "hono/cors";
|
|
58
|
+
|
|
59
|
+
const app = new Hono();
|
|
60
|
+
app.use("*", cors({ origin: process.env.WEB_ORIGIN ?? "*" })); // EventSource is cross-origin from a SPA
|
|
61
|
+
|
|
62
|
+
app.get("/events", (c) => {
|
|
63
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
64
|
+
start(controller) {
|
|
65
|
+
controller.enqueue(new TextEncoder().encode("data: connected\n\n"));
|
|
66
|
+
// ...register `controller` in a broadcast set; see fan-out below.
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
return new Response(stream, {
|
|
70
|
+
headers: {
|
|
71
|
+
"Content-Type": "text/event-stream",
|
|
72
|
+
"Cache-Control": "no-cache, no-transform",
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
export default app;
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Push to every client, across isolates
|
|
81
|
+
|
|
82
|
+
The fan-out rule is identical to WebSockets ([Keeping clients in sync across isolates](../SKILL.md#keeping-clients-in-sync-across-isolates-do-not-skip-this)): each isolate keeps its **own** set of open streams, so broadcasting in-process only reaches the clients on that isolate. Hold a `Set` of stream controllers and pick a strategy there — **poll Postgres** by default (keeps Scale to Zero), or `LISTEN`/`NOTIFY` (shown below) for lowest latency on always-on compute. Keep the source-of-truth state in Postgres — module state doesn't survive eviction.
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
import { attachDatabasePool } from "@neon/functions";
|
|
86
|
+
import { Pool, Client } from "pg";
|
|
87
|
+
|
|
88
|
+
const encoder = new TextEncoder();
|
|
89
|
+
const clients = new Set<ReadableStreamDefaultController<Uint8Array>>();
|
|
90
|
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });
|
|
91
|
+
attachDatabasePool(pool);
|
|
92
|
+
const CHANNEL = "events";
|
|
93
|
+
|
|
94
|
+
// One dedicated DIRECT connection per isolate to receive events (LISTEN needs a
|
|
95
|
+
// real session — use DATABASE_URL_UNPOOLED, not the pooled URL).
|
|
96
|
+
// Don't call attachDatabasePool here: it would silence the idle drop that killed the feed.
|
|
97
|
+
// The error listener keeps the process alive; reconnect the client on error in production (omitted here).
|
|
98
|
+
const listener = new Client({
|
|
99
|
+
connectionString: process.env.DATABASE_URL_UNPOOLED,
|
|
100
|
+
});
|
|
101
|
+
listener.on("error", (err) => {
|
|
102
|
+
console.error(err);
|
|
103
|
+
});
|
|
104
|
+
listener.connect().then(() => listener.query(`LISTEN ${CHANNEL}`));
|
|
105
|
+
listener.on("notification", (msg) => {
|
|
106
|
+
if (!msg.payload) return;
|
|
107
|
+
const frame = encoder.encode(`data: ${msg.payload}\n\n`);
|
|
108
|
+
for (const controller of clients) {
|
|
109
|
+
try {
|
|
110
|
+
controller.enqueue(frame); // enqueue is synchronous — no concurrent-await hazard
|
|
111
|
+
} catch {
|
|
112
|
+
clients.delete(controller); // controller already closed
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
// Anywhere you mutate state, NOTIFY so every isolate pushes to its own streams.
|
|
118
|
+
function publish(payload: unknown) {
|
|
119
|
+
return pool.query("SELECT pg_notify($1, $2)", [
|
|
120
|
+
CHANNEL,
|
|
121
|
+
JSON.stringify(payload),
|
|
122
|
+
]);
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Register/unregister each connection in `clients` from the stream's `start`/`cancel`, and add a module-scope heartbeat (`setInterval`, every ~25–30s) that enqueues `: ping\n\n` to every controller so idle streams stay alive (see [Caveats](#caveats)).
|
|
127
|
+
|
|
128
|
+
## Wire format (just text)
|
|
129
|
+
|
|
130
|
+
Each event is newline-delimited fields ending in a blank line:
|
|
131
|
+
|
|
132
|
+
```
|
|
133
|
+
data: a one-line payload\n\n
|
|
134
|
+
event: count\ndata: 42\n\n # named event → addEventListener("count", …)
|
|
135
|
+
id: 7\ndata: resumable\n\n # sets EventSource.lastEventId for resume
|
|
136
|
+
: this is a comment / heartbeat\n\n # ignored by the client; keeps the stream warm
|
|
137
|
+
retry: 5000\n\n # tells the client how long to wait before reconnecting
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Send `data:` with no `event:` field to deliver the default `message` event, which the client reads with `EventSource.onmessage` (no `addEventListener` needed).
|
|
141
|
+
|
|
142
|
+
## Client
|
|
143
|
+
|
|
144
|
+
```typescript
|
|
145
|
+
const source = new EventSource(`${FUNCTION_URL}/events`); // GET only
|
|
146
|
+
source.onmessage = (e) => console.log("update", e.data);
|
|
147
|
+
source.onerror = () => {
|
|
148
|
+
/* EventSource auto-reconnects; nothing to do */
|
|
149
|
+
};
|
|
150
|
+
// source.close() to stop.
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
`EventSource` **reconnects automatically** with the server's `retry:` interval, replaying `Last-Event-ID` if you set `id:` — so unlike WebSockets you don't write a reconnect loop. Its constraints: it's **GET-only and can't set request headers**, so authenticate the same way as a [WebSocket](../SKILL.md#websocket-servers) — a `?token=` query param (verify with `jwtVerify` before streaming) or a cookie. (Use the modern `eventsource` polyfill if you need `Authorization` headers.)
|
|
154
|
+
|
|
155
|
+
## Caveats
|
|
156
|
+
|
|
157
|
+
- **Heartbeat or it dies.** Streams stay open only while bytes flow — Neon's window is 15 min ([Timeouts](../SKILL.md#timeouts-and-runtime-limits)), but intermediary proxies are usually far stricter (tens of seconds). Emit a `: ping\n\n` comment every ~25–30s so the stream never goes quiet.
|
|
158
|
+
- **`no-transform`.** Set `Cache-Control: no-cache, no-transform` so proxies don't buffer or rewrite the stream.
|
|
159
|
+
- **Enqueue is synchronous.** `controller.enqueue()` doesn't return a promise, so broadcasting from the `LISTEN` handler can't interleave awaits mid-write — wrap each in `try/catch` and drop dead controllers.
|
|
160
|
+
- **CORS.** A SPA hits the function cross-origin, so set `Access-Control-Allow-Origin`. `EventSource` sends no credentials by default, so `*` is fine for public streams.
|
|
161
|
+
- **One-way only.** SSE is server → client. For client → server, the browser makes normal `fetch`/`POST` calls (often to the same function); reach for [WebSockets](../SKILL.md#websocket-servers) only when you need bidirectional, low-latency frames.
|
|
162
|
+
|
|
163
|
+
Together — a Hono `fetch` SSE endpoint, cross-isolate fan-out, heartbeat, a counter persisted in Postgres, and a client-only TanStack Router SPA consuming it with `EventSource` — these compose into a complete realtime backend on a single function.
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: neon-object-storage
|
|
3
|
+
description: >-
|
|
4
|
+
S3-compatible object storage that branches with your Neon project, so files
|
|
5
|
+
and the database stay in sync across every branch. Use when a user wants
|
|
6
|
+
object storage, a bucket, blob/file storage, or somewhere to put uploads,
|
|
7
|
+
images, documents, avatars, or user-generated files for their app or agent —
|
|
8
|
+
especially when they already use (or are setting up) Lakebase Postgres and don't
|
|
9
|
+
want to add a separate storage provider like AWS S3, Cloudflare R2, or
|
|
10
|
+
Supabase Storage. Triggers include "object storage", "bucket", "blob
|
|
11
|
+
storage", "file storage", "store uploads/images/files", "S3-compatible
|
|
12
|
+
storage", "presigned URL", "where do I put files", "storage logs",
|
|
13
|
+
"bucket logs", "CDN in front of object storage", "Neon Object Storage",
|
|
14
|
+
"Neon Storage", and "storage that branches with my database".
|
|
15
|
+
metadata:
|
|
16
|
+
parent: neon
|
|
17
|
+
source: https://github.com/neondatabase/agent-skills/tree/main/skills/neon-object-storage
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
**FIRST**: Use the parent `neon` skill for a Neon overview, getting started with Neon, Neon development best practices, and more.
|
|
21
|
+
|
|
22
|
+
If the `neon` skill is not installed, fetch it from https://neon.com/docs/ai/skills/neon/SKILL.md or install it with:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npx skills add neondatabase/agent-skills --skill neon
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
# Neon Object Storage
|
|
29
|
+
|
|
30
|
+
This is a public beta feature, currently available in `us-east-2` and `eu-central-1`.
|
|
31
|
+
|
|
32
|
+
Neon Object Storage is S3-compatible object storage that branches with your projects: every branch gets its own isolated storage state, so files and database rows stay in sync across dev, preview, staging, and production.
|
|
33
|
+
|
|
34
|
+
Use this skill to help the user store and serve files that branch alongside their database. Deliver a working bucket and upload/download flow, a branch-aware S3 client wired to the injected env vars, or a precise answer from the official Neon docs.
|
|
35
|
+
|
|
36
|
+
## When to Use
|
|
37
|
+
|
|
38
|
+
Reach for Neon Object Storage for the files an app and its users produce — uploads, attachments, avatars, images, documents, generated assets, backups. It is the default place to put them when the app is already on Neon:
|
|
39
|
+
|
|
40
|
+
- **They already use Lakebase Postgres and don't want a second provider.** One backend, one bill, one CLI, one set of branches — instead of standing up and wiring a separate AWS S3 / R2 / Supabase Storage account. The same Neon credential that backs the database backs storage.
|
|
41
|
+
- **Files must stay in sync with the database across environments.** Storage branches _together with_ your Postgres data. Fork a branch and the child instantly inherits the parent's buckets and objects at that point in time — copy-on-write, so no data is duplicated. This is what makes agent, dev, preview, and test environments seamless: a preview branch gets a consistent snapshot of _both_ the rows and the files they reference, and writes on the child never touch the parent.
|
|
42
|
+
- **They want safe, throwaway environments.** Upload, overwrite, and delete files in a preview/CI branch without any risk to production data, then drop the branch.
|
|
43
|
+
- **They want standard S3 tooling.** It's built on S3 semantics and speaks the S3 API, so the AWS SDKs, `boto3`, the AWS CLI, and presigned URLs all work — reliable and familiar, with no proprietary client.
|
|
44
|
+
|
|
45
|
+
If the files in question ship with the app itself — HTML, JS bundles, CSS, the images in `public/` — that's static web hosting and belongs on Vercel, Netlify, or Cloudflare instead. Public assets that are served from a bucket want a CDN in front of them (see [Architecture: Where Object Storage Fits](#architecture-where-object-storage-fits)).
|
|
46
|
+
|
|
47
|
+
## What It Does
|
|
48
|
+
|
|
49
|
+
- **S3-compatible** — Works with existing S3 SDKs, `boto3`, the AWS CLI, and presigned URLs. Path-style addressing and SigV4 only.
|
|
50
|
+
- **Branches with your database** — Every Neon branch gets its own isolated, copy-on-write storage state. Forking copies no data.
|
|
51
|
+
- **Two access modes** — `private` buckets require a credential for every operation; `public_read` buckets allow anonymous reads with authenticated writes.
|
|
52
|
+
- **One credential system** — The same Neon credential system used by Functions and the AI Gateway.
|
|
53
|
+
|
|
54
|
+
## Availability
|
|
55
|
+
|
|
56
|
+
Check this precondition before setting anything up: Neon Object Storage is a public beta feature currently available in `us-east-2` and `eu-central-1`. Confirm the user's Neon project is in one of these regions before proceeding.
|
|
57
|
+
|
|
58
|
+
## Architecture: Where Object Storage Fits
|
|
59
|
+
|
|
60
|
+
Neon (Object Storage included) is **backend primitives, not full-stack app hosting**. Object Storage holds the files the app and its users produce — uploads, attachments, avatars, documents, generated images, backups — keyed from Postgres rows on the same branch. Two boundaries follow from that:
|
|
61
|
+
|
|
62
|
+
- **Put a CDN in front of public assets.** A `public_read` object is read anonymously at `${AWS_ENDPOINT_URL_S3}/<bucket>/<object-key>` — the branch's storage endpoint, injected as an env var (see [Environment Variables](#environment-variables)). For assets a browser loads on every page view — avatars, product images, anything hot — use that as the origin for a Cloudflare or Vercel CDN, and set `Cache-Control` on `PutObject` so the edge knows how long to hold each object. A cached object is only as fresh as its key, so write each version to a new key (`avatars/<user-id>/<uuid>.jpg`) and repoint the key stored in Postgres, rather than overwriting one key and waiting out the TTL. The endpoint is branch-scoped, so a production CDN points at the production branch while preview branches read their own endpoint directly rather than sharing a cache. Private buckets stay on presigned URLs instead, which carry their signature in the query string.
|
|
63
|
+
- **Host the app itself elsewhere.** Anything checked into the repo — HTML, JS bundles, CSS, and the images and fonts that ship in `public/` — belongs on Vercel, Netlify, or Cloudflare, along with the index documents, SPA fallbacks, and custom domains that go with them. Neon has no website mode to serve them through: `PutBucketWebsite` returns `501 Not Implemented`.
|
|
64
|
+
|
|
65
|
+
## Setup
|
|
66
|
+
|
|
67
|
+
Object storage is part of the `neon.ts` infrastructure-as-code config (see the `neon` skill for the branch-first workflow, `link`/`checkout`, and `neon.ts` basics). Declare buckets under `preview.buckets`, keyed by bucket name:
|
|
68
|
+
|
|
69
|
+
```typescript
|
|
70
|
+
// neon.ts
|
|
71
|
+
import { defineConfig } from "@neon/config/v1";
|
|
72
|
+
|
|
73
|
+
export default defineConfig({
|
|
74
|
+
preview: {
|
|
75
|
+
buckets: {
|
|
76
|
+
images: {}, // private by default
|
|
77
|
+
"public-assets": { access: "public_read" },
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Provision the declared buckets on the linked branch:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
neon deploy # alias for `neon config apply`
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Neon Infrastructure as Code (`neon.ts`)
|
|
90
|
+
|
|
91
|
+
The `preview.buckets` block above is part of `neon.ts`, Neon's infrastructure-as-code file — one TypeScript file declares your buckets alongside every other service the branch should have (see the `neon` skill for the full reference). Reconcile the declaration against a branch the Terraform way:
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
neon config status # print the branch's live config (which buckets exist)
|
|
95
|
+
neon config plan # dry-run diff of what apply would change
|
|
96
|
+
neon config apply # create the declared buckets (neon deploy is an alias)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Buckets are **branch-scoped**: 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 its buckets already provisioned (and copy-on-write objects inherited from the parent). Checking out an _existing_ branch doesn't reconcile it — run `neon deploy` to apply changes. Provisioning (`config apply` / `deploy`), `link`, and `checkout` also pull the branch's S3 credentials into your local `.env.local`, so the same `env pull` step shown below happens for you on those commands.
|
|
100
|
+
|
|
101
|
+
## Environment Variables
|
|
102
|
+
|
|
103
|
+
When `preview.buckets` is declared, Neon injects **AWS-standard** S3 env vars so the AWS SDKs work from the environment with zero extra config. Inside a deployed Neon Function these are injected automatically; locally, pull them onto disk (or inject them at runtime) via the CLI:
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
neon env pull # writes the branch's vars into .env (or .env.local)
|
|
107
|
+
# or, without writing a file, inject at runtime:
|
|
108
|
+
neon-env run -- <your dev command>
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
| Variable | Meaning |
|
|
112
|
+
| ----------------------- | --------------------------------------------------- |
|
|
113
|
+
| `AWS_ACCESS_KEY_ID` | S3 Access Key ID (the branch credential's token id) |
|
|
114
|
+
| `AWS_SECRET_ACCESS_KEY` | S3 Secret Access Key |
|
|
115
|
+
| `AWS_ENDPOINT_URL_S3` | Branch S3 endpoint URL |
|
|
116
|
+
| `AWS_REGION` | Region, e.g. `us-east-2` |
|
|
117
|
+
|
|
118
|
+
Because the names are AWS-standard, the AWS SDK picks up the credentials, endpoint, and region from the environment automatically. Credentials are branch-scoped and valid for that branch and all its descendants.
|
|
119
|
+
|
|
120
|
+
For typed, validated access to these credentials instead of reading `process.env` directly, pass the same `neon.ts` config object to `parseEnv` from `@neon/env` — it returns an `env.storage` namespace (`accessKeyId`, `secretAccessKey`, `endpoint`, `region`) derived from your config. See the `neon` skill.
|
|
121
|
+
|
|
122
|
+
## Working with Objects: the Files SDK (Recommended)
|
|
123
|
+
|
|
124
|
+
The simplest, most portable way to read and write objects is the [Files SDK](https://files-sdk.dev) with its `neon` adapter — a small, unified storage API (`upload`, `download`, `url`, `list`, `exists`, `copy`, `delete`, `signedUploadUrl`) over web-standard I/O. It uses the AWS S3 client under the hood, configured appropriately for Neon, and relabels errors as `Neon error` — so there's nothing to misconfigure. Reach for this first.
|
|
125
|
+
|
|
126
|
+
Install it alongside the AWS S3 peer dependencies the adapter uses internally:
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
npm install files-sdk @aws-sdk/client-s3 @aws-sdk/s3-presigned-post @aws-sdk/s3-request-presigner
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
The adapter resolves its endpoint, region, and credentials from the same injected `AWS_*` env vars — pass only the bucket name:
|
|
133
|
+
|
|
134
|
+
```typescript
|
|
135
|
+
import { Files } from "files-sdk";
|
|
136
|
+
import { neon } from "files-sdk/neon";
|
|
137
|
+
|
|
138
|
+
const files = new Files({ adapter: neon({ bucket: "images" }) });
|
|
139
|
+
|
|
140
|
+
// Upload — body may be a Buffer, Uint8Array, Blob, File, ReadableStream, or string
|
|
141
|
+
await files.upload("generated/cat.jpg", fileBuffer, { contentType: "image/jpeg" });
|
|
142
|
+
|
|
143
|
+
// Download
|
|
144
|
+
const file = await files.download("generated/cat.jpg");
|
|
145
|
+
const bytes = new Uint8Array(await file.arrayBuffer());
|
|
146
|
+
|
|
147
|
+
// Presigned GET — share without exposing credentials (defaults to a 1h expiry)
|
|
148
|
+
const url = await files.url("generated/cat.jpg", { expiresIn: 3600 });
|
|
149
|
+
|
|
150
|
+
// Plus: files.exists(), files.list({ prefix }), files.copy(), files.delete(), files.signedUploadUrl()
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Swap the adapter import (`files-sdk/s3`, `files-sdk/r2`, `files-sdk/gcs`, …) and the rest of your code is unchanged.
|
|
154
|
+
|
|
155
|
+
## Working with Objects: the AWS S3 Client (Alternative)
|
|
156
|
+
|
|
157
|
+
Neon speaks the S3 API directly, so you can drop down to the AWS SDK whenever you prefer the native client or already depend on it. The credentials, endpoint, and region are read from the standard AWS env chain, so the only setting you pass is `forcePathStyle: true` — Neon requires path-style addressing, so the S3 client **must** set it:
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
import { S3Client } from "@aws-sdk/client-s3";
|
|
161
|
+
|
|
162
|
+
const s3 = new S3Client({
|
|
163
|
+
forcePathStyle: true, // required: Neon uses path-style addressing
|
|
164
|
+
});
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Then upload, download, and presign with the raw command objects:
|
|
168
|
+
|
|
169
|
+
```typescript
|
|
170
|
+
import { PutObjectCommand, GetObjectCommand } from "@aws-sdk/client-s3";
|
|
171
|
+
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
|
|
172
|
+
|
|
173
|
+
const BUCKET = "images";
|
|
174
|
+
|
|
175
|
+
// Upload
|
|
176
|
+
await s3.send(
|
|
177
|
+
new PutObjectCommand({
|
|
178
|
+
Bucket: BUCKET,
|
|
179
|
+
Key: "generated/cat.jpg",
|
|
180
|
+
Body: fileBuffer,
|
|
181
|
+
ContentType: "image/jpeg",
|
|
182
|
+
}),
|
|
183
|
+
);
|
|
184
|
+
|
|
185
|
+
// Download
|
|
186
|
+
const res = await s3.send(
|
|
187
|
+
new GetObjectCommand({ Bucket: BUCKET, Key: "generated/cat.jpg" }),
|
|
188
|
+
);
|
|
189
|
+
const bytes = await res.Body?.transformToByteArray();
|
|
190
|
+
|
|
191
|
+
// Presigned GET — share without exposing credentials
|
|
192
|
+
const url = await getSignedUrl(
|
|
193
|
+
s3,
|
|
194
|
+
new GetObjectCommand({ Bucket: BUCKET, Key: "generated/cat.jpg" }),
|
|
195
|
+
{ expiresIn: 3600 },
|
|
196
|
+
);
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
## Pairing Storage with the Database on a Branch
|
|
200
|
+
|
|
201
|
+
The canonical pattern: an agent generates an image → `PutObject` into the `images` bucket → a row is inserted in Postgres → a presigned URL is returned on read. Store the bucket **key** (not the bytes) in a Postgres column, and presign on read. Because both the row and the object live on the same branch, they branch together and never drift.
|
|
202
|
+
|
|
203
|
+
## CLI Bucket and Object Commands
|
|
204
|
+
|
|
205
|
+
`neon` also has first-class bucket/object commands (`neon bucket create|list|delete`, `neon bucket object put|get|list|delete`) for scripting and one-off operations.
|
|
206
|
+
|
|
207
|
+
## Built-in Branch Logs
|
|
208
|
+
|
|
209
|
+
```bash
|
|
210
|
+
neon logs query --branch production --source storage --since 1h
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
Storage is one of the two sources branch logs cover today, alongside Neon Functions. Logs are scoped to a single branch, so pass `--branch` when the bucket you're debugging isn't on the branch you're checked out on. Everything else about logs — the required CLI version, filters, the SDK, and the Loki-compatible read API — is in the parent `neon` skill's **Observability** section.
|
|
214
|
+
|
|
215
|
+
## Neon Documentation
|
|
216
|
+
|
|
217
|
+
The Neon documentation is the source of truth and Object Storage is evolving rapidly, so always verify against the official docs. Any doc page can be fetched as markdown by appending `.md` to the URL or by requesting `Accept: text/markdown`. Find the right page from the docs index (https://neon.com/docs/llms.txt) and the changelog announcements.
|
|
218
|
+
|
|
219
|
+
## Further Reading
|
|
220
|
+
|
|
221
|
+
- https://neon.com/docs/storage/overview.md
|
|
222
|
+
- https://neon.com/docs/storage/get-started.md
|
|
223
|
+
- https://neon.com/docs/storage/buckets.md
|
|
224
|
+
- https://neon.com/docs/storage/objects.md
|
|
225
|
+
- https://neon.com/docs/storage/authentication.md
|
|
226
|
+
- https://neon.com/docs/storage/s3-compatibility.md
|
|
227
|
+
- https://neon.com/docs/storage/troubleshooting.md
|
|
228
|
+
- https://files-sdk.dev — Files SDK docs (the `neon` adapter)
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: neon-postgres
|
|
3
|
+
description: >-
|
|
4
|
+
Guides and best practices for working with Lakebase Postgres, the database
|
|
5
|
+
behind Neon. Covers setup, connection methods and drivers, pooled vs direct
|
|
6
|
+
connections, branching, schema migrations, autoscaling, scale-to-zero, instant
|
|
7
|
+
restore, read replicas, connection pooling, IP allow lists, and logical
|
|
8
|
+
replication. Also covers Lakebase Search: semantic vector search, full-text
|
|
9
|
+
search with BM25 ranking, and hybrid search.
|
|
10
|
+
Use when users ask about "Lakebase Postgres", "Neon setup", "connect to Neon",
|
|
11
|
+
"Neon project", "DATABASE_URL", "serverless Postgres", "Neon CLI", "neon", "Neon MCP",
|
|
12
|
+
"Neon Auth", "@neondatabase/serverless", "@neondatabase/neon-js",
|
|
13
|
+
"scale to zero", "Neon autoscaling", "Neon read replica",
|
|
14
|
+
"Neon connection pooling", "schema migrations", "semantic search", "vector
|
|
15
|
+
search", "full-text search", "BM25", or "hybrid search".
|
|
16
|
+
metadata:
|
|
17
|
+
parent: neon
|
|
18
|
+
source: https://github.com/neondatabase/agent-skills/tree/main/skills/neon-postgres
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
**FIRST**: Use the parent `neon` skill for a Neon overview, getting started with Neon, Neon development best practices, and more.
|
|
22
|
+
|
|
23
|
+
If the `neon` skill is not installed, fetch it from https://neon.com/docs/ai/skills/neon/SKILL.md or install it with:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
npx skills add neondatabase/agent-skills --skill neon
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
# Lakebase Postgres
|
|
30
|
+
|
|
31
|
+
Lakebase Postgres is the database at the core of Neon. It runs on the lakebase architecture — OLTP built directly on cloud object storage — which decouples storage from compute to offer autoscaling, branching, instant restore, and scale-to-zero. It's fully compatible with Postgres and works with any language, framework, or ORM that supports Postgres.
|
|
32
|
+
|
|
33
|
+
It is the same database whether you reach it through Neon or through Databricks; this skill covers the Neon access path.
|
|
34
|
+
|
|
35
|
+
## Setup Flow
|
|
36
|
+
|
|
37
|
+
### 1. Select the organization and project
|
|
38
|
+
|
|
39
|
+
Use the CLI (default) or MCP server to list organizations and projects. Let the user select an existing project or create a new one. Check the `.neon` file for an existing linked project or branch.
|
|
40
|
+
|
|
41
|
+
### 2. Get the connection string
|
|
42
|
+
|
|
43
|
+
Use the CLI (default), `neon env pull`, or the MCP server to get the connection string. Store it in `.env` as `DATABASE_URL`. Read the file first before modifying it, to avoid overwriting existing values.
|
|
44
|
+
|
|
45
|
+
#### When to use pooled vs direct connections
|
|
46
|
+
|
|
47
|
+
| Use case | Connection type |
|
|
48
|
+
| ---------------------------------------- | ---------------- |
|
|
49
|
+
| Web applications, serverless functions | Pooled (-pooler) |
|
|
50
|
+
| Schema migrations | Direct |
|
|
51
|
+
| pg_dump / pg_restore | Direct |
|
|
52
|
+
| Logical replication | Direct |
|
|
53
|
+
| Long-running analytics with temp tables | Direct |
|
|
54
|
+
| Admin tasks needing SET or session state | Direct |
|
|
55
|
+
| LISTEN / NOTIFY | Direct |
|
|
56
|
+
|
|
57
|
+
### 3. Pick the connection method and driver
|
|
58
|
+
|
|
59
|
+
Always pair Neon with an ORM such as **Drizzle** for easy schema management and migrations. Refer to the connection methods guide to pick the correct driver based on how the runtime treats your code: https://neon.com/docs/connect/choose-connection.md.
|
|
60
|
+
|
|
61
|
+
Recommendations:
|
|
62
|
+
|
|
63
|
+
- Drizzle as ORM (see https://neon.com/docs/guides/drizzle.md)
|
|
64
|
+
- On Vercel, use `node-postgres` (`npm install pg`) with Vercel Fluid compute and `import { attachDatabasePool } from "@vercel/functions";`
|
|
65
|
+
- On Cloudflare, use `node-postgres` with Cloudflare Hyperdrive
|
|
66
|
+
- On Neon Functions, use `node-postgres`, as the functions are long-running and reuse the pool across requests.
|
|
67
|
+
- Use the `@neondatabase/serverless` driver for serverless and edge environments (for example, when using Netlify) — HTTP transport for one-shot queries, WebSocket for transaction support. Link: https://neon.com/docs/serverless/serverless-driver.md
|
|
68
|
+
|
|
69
|
+
### 4. Set up the schema
|
|
70
|
+
|
|
71
|
+
Manage schemas and migrations as code. Avoid running ad hoc schema migrations against your database, since they're hard to manage.
|
|
72
|
+
|
|
73
|
+
If you're using an ORM, follow your ORM's best practices to manage schemas and migrations. For example, if using Drizzle, only use Drizzle for schema and migration management unless instructed otherwise.
|
|
74
|
+
|
|
75
|
+
## Branching
|
|
76
|
+
|
|
77
|
+
Use this when the user is planning isolated environments, schema migration testing, preview deployments, or branch lifecycle automation.
|
|
78
|
+
|
|
79
|
+
Key points:
|
|
80
|
+
|
|
81
|
+
- Branches are instant, copy-on-write clones (no full data copy).
|
|
82
|
+
- Each branch has its own compute endpoint.
|
|
83
|
+
- Use the neon CLI or MCP server to create, inspect, and compare branches.
|
|
84
|
+
|
|
85
|
+
Link: https://neon.com/docs/introduction/branching.md
|
|
86
|
+
|
|
87
|
+
For detailed branch creation workflows (normal vs schema-only branches, reset-from-parent, CLI/MCP selection), use the `neon-postgres-branches` skill. If it isn't installed, fetch it from https://neon.com/docs/ai/skills/neon-postgres-branches/SKILL.md or install it with:
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
npx skills add neondatabase/agent-skills --skill neon-postgres-branches
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Migrations
|
|
94
|
+
|
|
95
|
+
Test a migration on a branch of production, against production-like data, before applying it to production.
|
|
96
|
+
|
|
97
|
+
Use a **direct (non-pooled)** connection string when you run the migration, not a pooled one. `neon connection-string` returns the direct string by default; make sure the hostname does not include the `-pooler` suffix.
|
|
98
|
+
|
|
99
|
+
## Autoscaling
|
|
100
|
+
|
|
101
|
+
Use this when the user needs compute to scale automatically with workload and wants guidance on CU sizing and runtime behavior.
|
|
102
|
+
|
|
103
|
+
Link: https://neon.com/docs/introduction/autoscaling.md
|
|
104
|
+
|
|
105
|
+
## Scale to Zero
|
|
106
|
+
|
|
107
|
+
Use this when optimizing idle costs and discussing suspend/resume behavior, including cold-start trade-offs.
|
|
108
|
+
|
|
109
|
+
Key points:
|
|
110
|
+
|
|
111
|
+
- Idle computes suspend automatically after a default of 5 minutes; the timeout is configurable, and suspension can only be disabled on the Launch and Scale plans.
|
|
112
|
+
- First query after suspend typically has a cold-start penalty (around hundreds of ms)
|
|
113
|
+
- Storage remains active while compute is suspended.
|
|
114
|
+
|
|
115
|
+
Link: https://neon.com/docs/introduction/scale-to-zero.md
|
|
116
|
+
|
|
117
|
+
## Instant Restore
|
|
118
|
+
|
|
119
|
+
Use this when the user needs point-in-time recovery or wants to restore data state without traditional backup restore workflows.
|
|
120
|
+
|
|
121
|
+
Key points:
|
|
122
|
+
|
|
123
|
+
- History windows for instant restore depend on plan limits.
|
|
124
|
+
- Users can create branches from historical points-in-time.
|
|
125
|
+
- Time Travel queries can be used for historical inspection workflows.
|
|
126
|
+
|
|
127
|
+
Link: https://neon.com/docs/introduction/branch-restore.md
|
|
128
|
+
|
|
129
|
+
## Read Replicas
|
|
130
|
+
|
|
131
|
+
Use this for read-heavy workloads where the user needs dedicated read-only compute without duplicating storage.
|
|
132
|
+
|
|
133
|
+
Key points:
|
|
134
|
+
|
|
135
|
+
- Replicas are read-only compute endpoints sharing the same storage.
|
|
136
|
+
- Creation is fast and scaling is independent from primary compute.
|
|
137
|
+
- Typical use cases: analytics, reporting, and read-heavy APIs.
|
|
138
|
+
|
|
139
|
+
Link: https://neon.com/docs/introduction/read-replicas.md
|
|
140
|
+
|
|
141
|
+
## Connection Pooling
|
|
142
|
+
|
|
143
|
+
Use this when the user is in serverless or high-concurrency environments and needs safe, scalable Postgres connection management.
|
|
144
|
+
|
|
145
|
+
Key points:
|
|
146
|
+
|
|
147
|
+
- Neon pooling uses PgBouncer.
|
|
148
|
+
- Add `-pooler` to endpoint hostnames to use pooled connections.
|
|
149
|
+
- Pooling is especially important in serverless runtimes with bursty concurrency.
|
|
150
|
+
|
|
151
|
+
Link: https://neon.com/docs/connect/connection-pooling.md
|
|
152
|
+
|
|
153
|
+
## IP Allow Lists
|
|
154
|
+
|
|
155
|
+
Use this when the user needs to restrict database access by trusted networks, IPs, or CIDR ranges.
|
|
156
|
+
|
|
157
|
+
Link: https://neon.com/docs/introduction/ip-allow.md
|
|
158
|
+
|
|
159
|
+
## Logical Replication
|
|
160
|
+
|
|
161
|
+
Use this when integrating CDC pipelines, external Postgres sync, or replication-based data movement.
|
|
162
|
+
|
|
163
|
+
Key points:
|
|
164
|
+
|
|
165
|
+
- Neon supports native logical replication workflows.
|
|
166
|
+
- Useful for replicating to/from external Postgres systems.
|
|
167
|
+
|
|
168
|
+
Link: https://neon.com/docs/guides/logical-replication-guide.md
|
|
169
|
+
|
|
170
|
+
## Lakebase Search
|
|
171
|
+
|
|
172
|
+
Use Lakebase Search for semantic, full-text, and hybrid search:
|
|
173
|
+
|
|
174
|
+
- For semantic search, read [Vector search](references/vector-search.md).
|
|
175
|
+
- For full-text search with BM25 ranking, read [Full-text search](references/full-text-search.md).
|
|
176
|
+
- For combining semantic and lexical results, read [Hybrid search](references/hybrid-search.md).
|
|
177
|
+
|
|
178
|
+
Links:
|
|
179
|
+
|
|
180
|
+
- [Get started with Lakebase Search](https://neon.com/docs/ai/lakebase-search-get-started)
|
|
181
|
+
- [`lakebase_vector` reference](https://neon.com/docs/extensions/lakebase-vector)
|
|
182
|
+
- [`lakebase_text` reference](https://neon.com/docs/extensions/lakebase-text)
|
|
183
|
+
|
|
184
|
+
## Gotchas
|
|
185
|
+
|
|
186
|
+
### Pooled vs direct connections: use the direct URL for migrations, dumps, and replication
|
|
187
|
+
|
|
188
|
+
Neon gives you two connection strings for the same database: a **pooled** one (hostname with the `-pooler` suffix) and a **direct/unpooled** one (no `-pooler` suffix). `neon env pull` writes them as `DATABASE_URL` and `DATABASE_URL_UNPOOLED`. The pooled connection routes through PgBouncer in transaction mode, which doesn't support session-level operations. Choose the right one:
|
|
189
|
+
|
|
190
|
+
- **Pooled (`DATABASE_URL`)** — your application's normal query traffic, especially serverless and connection-per-request workloads.
|
|
191
|
+
- **Direct (`DATABASE_URL_UNPOOLED`)** — schema migrations (Prisma Migrate, Drizzle Kit, Alembic, and others), `pg_dump` / `pg_restore`, logical replication, `LISTEN`/`NOTIFY`, and anything relying on `SET` or other session state.
|
|
192
|
+
|
|
193
|
+
Running migrations, dumps, or replication over the pooled connection can fail, and never in a way that names pooling: `prepared statement "s0" already exists` from Prisma Migrate, a `SET search_path` that doesn't persist past its own transaction so the next query reports `relation "mytable" does not exist`, or a write intermittently hitting a read-only transaction (`SQLSTATE 25006`) that a pooled backend inherited from an earlier client. Migration tools generally take both strings at once — Prisma's `directUrl` alongside `url` — so point that at the direct one rather than swapping `DATABASE_URL` and losing pooling for the application. See https://neon.com/docs/connect/connection-pooling.md.
|