Neon Integration Guide

Technology: neon · Category: database · Last reviewed: 2026-10-17

Source: https://tech-stack.codeamanilabs.org/guide/neon

Insight:

Neon is no longer "just serverless Postgres": it's a set of backend primitives around Lakebase Postgres (Databricks) — Postgres, Managed Better Auth, Functions, Object Storage, AI Gateway, Realtime and a Data API — declared in one neon.ts and branched together. One neon checkout gives a PR its own database, auth users, files, functions and gateway endpoint, copy-on-write.

███╗   ██╗███████╗ ██████╗ ███╗   ██╗
████╗  ██║██╔════╝██╔═══██╗████╗  ██║
██╔██╗ ██║█████╗  ██║   ██║██╔██╗ ██║
██║╚██╗██║██╔══╝  ██║   ██║██║╚██╗██║
██║ ╚████║███████╗╚██████╔╝██║ ╚████║
╚═╝  ╚═══╝╚══════╝ ╚═════╝ ╚═╝  ╚═══╝

Neon Integration Guide

Focus: Lakebase Postgres on Neon plus Neon's branchable backend primitives — the neon CLI, neon.ts config-as-code, the serverless driver, and the hosted MCP server — wired the codeAmani way (Next.js on Vercel, Clerk, Stripe).

Overview

Neon is a set of cloud backend primitives built around Lakebase Postgres, from Databricks. Lakebase Postgres is one product reached two ways — through Neon (free plan, full backend primitives) or through Databricks. Neon's own naming convention: call the database Lakebase Postgres and use Neon for the brand and access path.

Primitive What it is Status (2026-10)
Lakebase Postgres Postgres with decoupled compute/storage, autoscaling, scale-to-zero, instant restore, copy-on-write branches GA, all regions
Managed Better Auth Hosted Better Auth; users/sessions live in your DB (neon_auth schema) and branch with it GA
Functions Long-running Node.js 24 serverless functions next to your data (APIs, agents, WebSocket/SSE, cron) 4 regions
Object Storage S3-compatible buckets that branch copy-on-write with the database 4 regions
AI Gateway One Neon credential → OpenAI-compatible, Anthropic Messages, Responses, Gemini endpoints 4 regions, paid plans
Realtime Live SQL subscriptions on standard Postgres (@neon/realtime) Beta (preview.realtime)
Data API PostgREST-compatible HTTP interface Migration path only (see below)

Backend-service regions: Functions, Object Storage, AI Gateway and branch logs run only in aws-us-east-1, aws-us-east-2, aws-eu-central-1 and aws-ap-southeast-1. Postgres alone is also in aws-us-west-2, aws-eu-west-2, aws-ap-southeast-2 and aws-sa-east-1. Azure regions are deprecated for new projects. Pick the region at project creation — you can't move a project later.

Everything branches together: one branch gets its own database, auth users, bucket view, function deployment and gateway endpoint.

flowchart LR
    A["main branch<br/>Postgres · Auth · Buckets · Functions · Gateway"] -->|"neon checkout pr-42 --create"| B["pr-42 branch<br/>copy-on-write of all of it"]
    B --> C["build · migrate · test"]
    C --> Q1{"Good?"}
    Q1 -->|"yes"| D["merge code · run migration on main"]
    Q1 -->|"no"| E["neon branches reset / delete<br/>or TTL expires it"]

Official Documentation

Resource URL
Docs index (every page, .md-fetchable) https://neon.com/docs/llms.txt
How a Neon backend fits together https://neon.com/docs/get-started/backend-overview
neon.ts reference https://neon.com/docs/reference/neon-ts
Serverless driver https://neon.com/docs/serverless/serverless-driver
Neon CLI https://neon.com/docs/cli
MCP server https://neon.com/docs/ai/neon-mcp-server
Functions https://neon.com/docs/compute/functions/overview
Object Storage https://neon.com/docs/storage/overview
AI Gateway https://neon.com/docs/ai-gateway/overview
Managed Better Auth https://neon.com/docs/auth/overview
Realtime (beta) https://neon.com/docs/realtime/overview
Connection pooling https://neon.com/docs/connect/connection-pooling
Pricing https://neon.com/pricing

Docs as markdown. Append .md to any docs URL (or send Accept: text/markdown). Look pages up in llms.txt — don't guess URLs.


Packages (verified on npm 2026-10-17)

Package Version Use
neon (CLI; neonctl is the same binary) 8.8.0 Everything: link, checkout, deploy, branches, functions, buckets
@neondatabase/serverless 1.2.0 Postgres over HTTP/WebSockets (Node ≥ 19, edge)
@neon/config 1.9.2 defineConfig for neon.ts (@neon/config/v1)
@neon/env 1.6.3 parseEnv typed env, neon-env run runtime injection
@neon/sdk 7.3.0 Management API from TS (preferred over @neondatabase/api-client)
@neondatabase/auth 0.6.0-beta Managed Better Auth client/server SDK (Better Auth 1.7)
@neon/functions 0.11.0 waitUntil for Functions
@neon/realtime 0.1.1 Realtime (beta)
@neondatabase/mcp-server-neon — Deprecated — use the hosted MCP server

The CLI is preferred over MCP for agents (it can deploy Functions; MCP can't do everything). Install, then check credentials without printing them:

npm i -g neon                 # binary is `neon`; `neonctl` is an alias
neon --version
neon profile list -o json     # an `account` other than "-" means you're signed in

One-shot setup (agent tooling + linked project + optional neon.ts):

neon init --skip-template --agent claude \
  --org-id <org-id> --project-name my-app --region-id aws-us-east-2 -y

--services auth,functions,object-storage,ai-gateway declares services in neon.ts; it writes config but doesn't deploy. Or do it piece by piece:

neon link --project-id <project-id> -y   # writes git-ignored .neon, pulls env
neon checkout dev-search --create        # new branch per task; pulls its env
neon diff                                # schema diff vs parent before you commit

link and checkout run neon env pull by default, which writes the branch's variables into .env (or .env.local). Pass --no-env-pull to keep secrets off disk and inject at runtime with neon-env run -- next dev (from @neon/env).

Useful commands

neon branches list
neon connection-string            # alias: neon cs
neon inspect db                   # read-only health checks (sizes, unused indexes, bloat…)
neon snapshots create --branch main --name pre-migration
neon logs query --branch production --source function --minimum-severity error --since 6h
neon functions deploy <slug> --src functions/api.ts
neon buckets list
neon credentials create --scope ai_gateway:invoke
neon skills update -y             # keep Neon agent skills current

neon.ts — config as code

neon.ts declares which services exist on every branch and how new branches are tuned. It's TypeScript, so invalid combinations fail to compile with a message that names the fix.

npm i @neon/config        # or: neon config init
// neon.ts
import { defineConfig } from "@neon/config/v1";

export default defineConfig({
  aiGateway: true,                         // injects NEON_AI_GATEWAY_TOKEN / _BASE_URL
  buckets: {
    uploads: { access: "private" },        // injects AWS_* S3 credentials
  },
  functions: {
    api: {                                 // slug: ^[a-z0-9]{1,20}$, immutable once deployed
      name: "Public API",
      source: "functions/api.ts",
      env: { STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY! },
    },
  },
  triggers: {
    nightly: { type: "schedule", function: "api", cron: "0 3 * * *", functionPath: "/cron/nightly" },
  },
  branch: (branch) => {
    if (branch.exists || branch.isDefault) return {};   // never retune live branches
    return {
      ttl: "7d",
      postgres: {
        computeSettings: { autoscalingLimitMinCu: 0.25, autoscalingLimitMaxCu: 1, suspendTimeout: "5m" },
      },
    };
  },
});
Service key Injects
(always) Postgres DATABASE_URL (pooled), DATABASE_URL_UNPOOLED (direct), NEON_BRANCH
auth: true NEON_AUTH_BASE_URL, NEON_AUTH_JWKS_URL
aiGateway: true NEON_AI_GATEWAY_TOKEN, NEON_AI_GATEWAY_BASE_URL
buckets AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ENDPOINT_URL_S3, AWS_REGION
dataApi NEON_DATA_API_URL (requires auth: true or an external JWKS)
preview.realtime NEON_REALTIME_URL, NEON_REALTIME_SECRET (needs @neon/config ≥ 1.9.0)

Apply it — Terraform-style:

neon status                         # live config (read-only)
neon config plan                    # dry-run diff
neon deploy --env .env.local        # apply; alias for `neon config apply`, then pulls env

Function env gotchas (from the docs): values resolve at deploy time from process.env; --env <file> loads that file before neon.ts is evaluated. Every declared key must be a defined string — never write ?? "": deploying an empty value deletes the live variable. aiGateway, functions and buckets moved out of preview in @neon/config 1.6.0 (the preview.* form is a deprecated alias).


Connecting to Postgres

Serverless driver (default for Vercel)

npm install @neondatabase/serverless
import { neon } from "@neondatabase/serverless";

const sql = neon(process.env.DATABASE_URL!);

// Tagged template only — values are parameterized automatically.
const posts = await sql`SELECT * FROM posts WHERE id = ${postId}`;

// Plain parameterized string:
const same = await sql.query("SELECT * FROM posts WHERE id = $1", [postId]);

// Non-interactive transaction over HTTP:
await sql.transaction([
  sql`INSERT INTO posts (title) VALUES (${"a"})`,
  sql`INSERT INTO posts (title) VALUES (${"b"})`,
]);

Pooled vs direct

Variable Host Use for
DATABASE_URL ep-…-pooler.<region>.aws.neon.tech (PgBouncer, transaction mode, up to 10,000 clients) App traffic
DATABASE_URL_UNPOOLED ep-….<region>.aws.neon.tech Migrations, LISTEN/NOTIFY, session state

max_connections scales with compute size (104 at 0.25 CU, 419 at 1 CU, capped at 4,000 from 9 CU); 7 are reserved. In long-lived processes keep pg pools small (e.g. max: 5) — effective connections = max × live instances.

Drizzle

import { neon } from "@neondatabase/serverless";
import { drizzle } from "drizzle-orm/neon-http";

export const db = drizzle(neon(process.env.DATABASE_URL!));

Point drizzle-kit at DATABASE_URL_UNPOOLED (see examples/drizzle.config.ts).

Prisma 7

Pin the major: Prisma's latest tag is an 8.x prerelease.

npm install @prisma/client@7 @prisma/adapter-neon@7 dotenv
npm install -D prisma@7 tsx
// prisma.config.ts — CLI (migrate, db push) uses the DIRECT url
import { defineConfig, env } from "prisma/config";
export default defineConfig({
  schema: "prisma/schema.prisma",
  datasource: { url: env("DATABASE_URL_UNPOOLED") },
});
// lib/prisma.ts — runtime uses the POOLED url through the adapter
import { PrismaClient } from "@prisma/client";
import { PrismaNeon } from "@prisma/adapter-neon";

const adapter = new PrismaNeon({ connectionString: process.env.DATABASE_URL! });
export const prisma = new PrismaClient({ adapter });

In Prisma 7, no url in the schema.prisma datasource block, and don't install @neondatabase/serverless/ws separately — the adapter bundles them. (Prisma ≤ 6 used url + directUrl in the schema.)


Backend primitives

Functions

Any module whose default export has fetch(request) → Response is a function; a Hono app works as-is (export default app).

// functions/api.ts
import { Hono } from "hono";
import { neon } from "@neondatabase/serverless";
import { createRemoteJWKSet, jwtVerify } from "jose";

const sql = neon(process.env.DATABASE_URL!);         // injected per branch
const jwks = createRemoteJWKSet(new URL(process.env.NEON_AUTH_JWKS_URL!));
const issuer = new URL(process.env.NEON_AUTH_BASE_URL!).origin;

const app = new Hono<{ Variables: { userId: string } }>();

app.use("*", async (c, next) => {                     // public URL: authenticate first
  const header = c.req.header("authorization") ?? "";
  if (!header.toLowerCase().startsWith("bearer ")) return c.text("Unauthorized", 401);
  try {
    const { payload } = await jwtVerify(header.slice(7), jwks, { issuer });
    if (!payload.sub) return c.text("Unauthorized", 401);
    c.set("userId", payload.sub);
  } catch {
    return c.text("Unauthorized", 401);
  }
  await next();
});

app.get("/notes", async (c) => {
  const userId = c.get("userId");
  return c.json(await sql`SELECT id, body FROM notes WHERE owner_id = ${userId}`);
});

export default app;
neon dev                               # local dev server with branch env injected
neon deploy --env .env.local           # or: neon functions deploy api --src functions/api.ts

Runtime limits that shape design:

Limit Value
Runtime Node.js 24, JS/TS only, microVM per isolate
Time to first byte 15 min
Stream / WebSocket heartbeat ≥ 1 byte every 15 min
waitUntil (from @neon/functions) 15 min after response
Memory 2,048 MiB fixed
Concurrency 100 concurrent invocations per account (default)
Shutdown SIGINT, then hard stop after 5 s

Functions are request/response, not a job queue — pair with Inngest/QStash for retryable work. They don't host websites. Every function URL is public: verify a JWT or API key at the top of the handler and allowlist CORS origins in production.

Object Storage

import { S3Client } from "@aws-sdk/client-s3";

export const s3 = new S3Client({
  region: process.env.AWS_REGION,
  endpoint: process.env.AWS_ENDPOINT_URL_S3,
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
  },
  forcePathStyle: true,
  requestChecksumCalculation: "WHEN_REQUIRED",   // else presigned PUTs reject real bodies
});

Max object 5 GiB (multipart for > 100 MB). Throttling returns 503 SlowDown — back off and retry. Free plan: 5 GB per project. A storage_object_created trigger can call a Function on upload.

AI Gateway

Needs a paid plan with prepaid credits ($5 minimum). One credential, every model; the per-branch host looks like br-<name>-api.ai.<cell>.<region>.aws.neon.tech.

Dialect Base URL
Chat Completions / Embeddings (OpenAI SDK) ${NEON_AI_GATEWAY_BASE_URL}/v1
OpenAI Responses API ${NEON_AI_GATEWAY_BASE_URL}/openai/v1
Anthropic Messages (Anthropic SDK) ${NEON_AI_GATEWAY_BASE_URL}/anthropic (SDK appends /v1/messages)
import Anthropic from "@anthropic-ai/sdk";

const claude = new Anthropic({
  authToken: process.env.NEON_AI_GATEWAY_TOKEN,          // authToken, not apiKey
  baseURL: `${process.env.NEON_AI_GATEWAY_BASE_URL}/anthropic`,
});

The Anthropic endpoint forwards cache_control and extended thinking unchanged. Check what your branch can serve at runtime with GET {base}/v1/models rather than hard-coding the catalog.

Managed Better Auth

// lib/auth/server.ts (Next.js)
import { createNeonAuth } from "@neondatabase/auth/next/server";

export const auth = createNeonAuth({
  baseUrl: process.env.NEON_AUTH_BASE_URL!,
  cookies: { secret: process.env.NEON_AUTH_COOKIE_SECRET! },   // ≥ 32 chars
});
// app/api/auth/[...path]/route.ts → export const { GET, POST } = auth.handler();

Users and sessions live in the neon_auth schema and branch with your data. Free plan covers 60k MAU; paid plans up to 1M. Can't be enabled on projects using IP Allow or Private Networking.

Data API and Realtime


MCP server (hosted)

claude mcp add --transport http neon https://mcp.neon.tech/mcp   # then /mcp to OAuth
# or let the CLI write config:
neon mcp --oauth --project --agent claude -y

Neon is also an official Claude connector (claude.ai → Settings → Connectors).

URL parameter Effect
?readonly=true Reads + schema only (no run_sql_transaction)
?projectId=<id> Scope to one project
?category=<name> (repeatable) projects, branches, endpoints, snapshots, schema, querying, neon_auth, data_api, observability, docs, functions, storage, realtime
?roleName=<role> SQL tools log in as that Postgres role (create it with SQL — Console-created roles are neon_superuser)

Preview a config without auth: curl "https://mcp.neon.tech/api/list-tools?readonly=true&category=querying". If IP Allow is on, allowlist the MCP server's IPs 34.192.103.46 and 23.22.233.166. The old /sse endpoint is retired; stdio-only clients bridge with npx -y mcp-remote@latest https://mcp.neon.tech/mcp.

Most-used tools: run_sql, describe_table_schema, create_branch, compare_database_schema, prepare_database_migration → complete_database_migration, inspect_database (15 read-only checks), list_slow_queries, explain_sql_statement, prepare_query_tuning → complete_query_tuning, create_snapshot/restore_snapshot.

Development and testing only — never point MCP at production or PII data.


pgvector

Neon ships pgvector (and the newer Lakebase Search for vector + full-text).

CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE items (id BIGSERIAL PRIMARY KEY, content TEXT, embedding VECTOR(1536));
CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);

SELECT id, content FROM items ORDER BY embedding <=> $1 LIMIT 5;   -- needs ORDER BY + LIMIT to use the index

HNSW on vector caps at 2,000 dims; for 3,072-dim embeddings index a halfvec cast (up to 4,000): USING hnsw ((embedding::halfvec(3072)) halfvec_cosine_ops).


CI: branch per PR

# .github/workflows/neon-preview.yml
on:
  pull_request:
    types: [opened, synchronize, closed]
jobs:
  preview:
    if: github.event.action != 'closed'
    runs-on: ubuntu-latest
    steps:
      - uses: neondatabase/create-branch-action@v6
        id: neon
        with:
          project_id: ${{ vars.NEON_PROJECT_ID }}
          api_key: ${{ secrets.NEON_API_KEY }}
          branch_name: preview/pr-${{ github.event.number }}
          # optional: expires_at: <ISO-8601 timestamp> to auto-delete the branch
      # outputs: db_url, db_url_pooled, db_host, db_host_pooled, branch_id, auth_url, data_api_url
  cleanup:
    if: github.event.action == 'closed'
    runs-on: ubuntu-latest
    steps:
      - uses: neondatabase/delete-branch-action@v3
        with:
          project_id: ${{ vars.NEON_PROJECT_ID }}
          api_key: ${{ secrets.NEON_API_KEY }}
          branch: preview/pr-${{ github.event.number }}

On Vercel, the Neon-managed Vercel integration does the same per preview deployment without a workflow.


Pricing snapshot (2026-10-17 — re-verify at neon.com/pricing)

Free Launch Scale
Compute 100 CU-hours/project $0.106/CU-hour $0.222/CU-hour
Postgres storage 1 GB/project, 20 GB account $0.35/GB-month $0.35/GB-month
Branches included 10 10 (+$1.50/branch-month) 25 (+$1.50)
History window 6 h up to 7 d up to 30 d
Scale to zero 5 min, always on 5 min, can disable 1 min → always on
Egress 5 GB 500 GB, then $0.10/GB 500 GB, then $0.10/GB
Auth MAU 60k 1M 1M
Object Storage 5 GB/project $0.023/GB-month $0.023/GB-month
AI Gateway — prepaid credits prepaid credits
IP Allow / Private Networking / HIPAA / SLA — — Yes

Running out of Free CU-hours or egress suspends compute; exceeding storage blocks writes. Nothing is deleted.


Troubleshooting

Issue Fix
First query slow / Prisma P1001 Compute was scaled to zero; retry, or add connect_timeout=15
wrong URL scheme / missing host from the driver DATABASE_URL not loaded (node --env-file=.env, or dotenv/config)
Migration fails through PgBouncer Use DATABASE_URL_UNPOOLED for migrations
defineConfig throws on a function env key A process.env value is unset — add it to the --env file or drop the key
Function deploy requires_claim Claimable project not yet claimed — Functions/Storage/Gateway need a claimed account
Functions/Storage/Gateway unavailable Project is outside the four backend-service regions — create a new project in one
AI Gateway 4xx on Anthropic endpoint Base URL must end in /anthropic (no /v1) and model must be an Anthropic ID
503 SlowDown from storage Back off and retry
Auth can't be enabled Project has IP Allow or Private Networking enabled

codeAmani notes

Official docs: