← Back to dashboard

Neon Integration Guide

What is Neon?

The real model

neon.ts + neon checkout: per-branch Postgres, auth, buckets, functions and gateway.

Query with `@neondatabase/serverless` — `neon()` over HTTP for one-shot queries, `Pool` over WebSockets only for interactive transactions. Use pooled `DATABASE_URL` for traffic and `DATABASE_URL_UNPOOLED` for migrations. Declare services in `neon.ts` (`@neon/config`), apply with `neon deploy --env <file>`, and run `neon checkout <task> --create` per task. Functions run Node 24 with a 15-min time-to-first-byte; their URLs are public, so verify a JWT first. Backend services exist only in us-east-1/2, eu-central-1 and ap-southeast-1. For codeAmani: keep Clerk + Stripe, and Kenya-targeted apps go in Frankfurt with M-Pesa callbacks on a Function deduped by CheckoutRequestID.

Six Neon primitives

Ordinary Postgres at the centre; everything around it branches with it.

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

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.

PrimitiveWhat it isStatus (2026-10)
Lakebase PostgresPostgres with decoupled compute/storage, autoscaling, scale-to-zero, instant restore, copy-on-write branchesGA, all regions
Managed Better AuthHosted Better Auth; users/sessions live in your DB (neon_auth schema) and branch with itGA
FunctionsLong-running Node.js 24 serverless functions next to your data (APIs, agents, WebSocket/SSE, cron)4 regions
Object StorageS3-compatible buckets that branch copy-on-write with the database4 regions
AI GatewayOne Neon credential → OpenAI-compatible, Anthropic Messages, Responses, Gemini endpoints4 regions, paid plans
RealtimeLive SQL subscriptions on standard Postgres (@neon/realtime)Beta (preview.realtime)
Data APIPostgREST-compatible HTTP interfaceMigration 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.

Official Documentation

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)

PackageVersionUse
neon (CLI; neonctl is the same binary)8.8.0Everything: link, checkout, deploy, branches, functions, buckets
@neondatabase/serverless1.2.0Postgres over HTTP/WebSockets (Node ≥ 19, edge)
@neon/config1.9.2defineConfig for neon.ts (@neon/config/v1)
@neon/env1.6.3parseEnv typed env, neon-env run runtime injection
@neon/sdk7.3.0Management API from TS (preferred over @neondatabase/api-client)
@neondatabase/auth0.6.0-betaManaged Better Auth client/server SDK (Better Auth 1.7)
@neon/functions0.11.0waitUntil for Functions
@neon/realtime0.1.1Realtime (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:

Bash
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
  • A human signs in with neon login (neon auth is an alias). An unattended agent must not launch browser auth — use NEON_API_KEY in CI.
  • No account yet: neon claim provisions a Claimable project (72-hour expiry, 15-minute claim code). Don't use it to paper over a failed sign-in.

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

Bash
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:

Bash
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

Bash
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.

Bash
npm i @neon/config        # or: neon config init
TypeScript
// 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 keyInjects
(always) PostgresDATABASE_URL (pooled), DATABASE_URL_UNPOOLED (direct), NEON_BRANCH
auth: trueNEON_AUTH_BASE_URL, NEON_AUTH_JWKS_URL
aiGateway: trueNEON_AI_GATEWAY_TOKEN, NEON_AI_GATEWAY_BASE_URL
bucketsAWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ENDPOINT_URL_S3, AWS_REGION
dataApiNEON_DATA_API_URL (requires auth: true or an external JWKS)
preview.realtimeNEON_REALTIME_URL, NEON_REALTIME_SECRET (needs @neon/config ≥ 1.9.0)

Apply it — Terraform-style:

Bash
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)

Bash
npm install @neondatabase/serverless
TypeScript
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"})`,
]);
  • HTTP (neon()) by default — fastest for single queries and batch transactions. Max request/response size 64 MB.
  • WebSockets (Pool / Client) only for interactive transactions, sessions or pg compatibility. Node ≥ 22 has a built-in WebSocket.
  • sql.unsafe(name) interpolates a trusted identifier — never user input.
  • Install from npm; the JSR package @neon/serverless is frozen at 1.0.1.

Pooled vs direct

VariableHostUse for
DATABASE_URLep-…-pooler.<region>.aws.neon.tech (PgBouncer, transaction mode, up to 10,000 clients)App traffic
DATABASE_URL_UNPOOLEDep-….<region>.aws.neon.techMigrations, 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

TypeScript
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.

Bash
npm install @prisma/client@7 @prisma/adapter-neon@7 dotenv
npm install -D prisma@7 tsx
TypeScript
// 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") },
});
TypeScript
// 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).

TypeScript
// 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;
Bash
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:

LimitValue
RuntimeNode.js 24, JS/TS only, microVM per isolate
Time to first byte15 min
Stream / WebSocket heartbeat≥ 1 byte every 15 min
waitUntil (from @neon/functions)15 min after response
Memory2,048 MiB fixed
Concurrency100 concurrent invocations per account (default)
ShutdownSIGINT, 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

TypeScript
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.

DialectBase 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)
TypeScript
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

TypeScript
// 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

  • Data API (PostgREST-compatible): use it only to keep an existing supabase-js/PostgREST database client working during a migration. New apps query Postgres from route handlers or Functions — browser-facing RLS is easy to misconfigure.
  • Realtime (beta): createRealtime on the server, seal() a query, subscribe from the client with @neon/realtime/client or useLiveQuery. Treat it as beta.

MCP server (hosted)

Bash
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 parameterEffect
?readonly=trueReads + 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).

SQL
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

YAML
# .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)

FreeLaunchScale
Compute100 CU-hours/project$0.106/CU-hour$0.222/CU-hour
Postgres storage1 GB/project, 20 GB account$0.35/GB-month$0.35/GB-month
Branches included1010 (+$1.50/branch-month)25 (+$1.50)
History window6 hup to 7 dup to 30 d
Scale to zero5 min, always on5 min, can disable1 min → always on
Egress5 GB500 GB, then $0.10/GB500 GB, then $0.10/GB
Auth MAU60k1M1M
Object Storage5 GB/project$0.023/GB-month$0.023/GB-month
AI Gateway—prepaid creditsprepaid 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

IssueFix
First query slow / Prisma P1001Compute was scaled to zero; retry, or add connect_timeout=15
wrong URL scheme / missing host from the driverDATABASE_URL not loaded (node --env-file=.env, or dotenv/config)
Migration fails through PgBouncerUse DATABASE_URL_UNPOOLED for migrations
defineConfig throws on a function env keyA process.env value is unset — add it to the --env file or drop the key
Function deploy requires_claimClaimable project not yet claimed — Functions/Storage/Gateway need a claimed account
Functions/Storage/Gateway unavailableProject is outside the four backend-service regions — create a new project in one
AI Gateway 4xx on Anthropic endpointBase URL must end in /anthropic (no /v1) and model must be an Anthropic ID
503 SlowDown from storageBack off and retry
Auth can't be enabledProject has IP Allow or Private Networking enabled

codeAmani notes

  • Database choice. Neon is one of codeAmani's two Postgres options (with Supabase). Pick Neon for branch-per-PR previews, scale-to-zero on low-traffic SME apps, and pgvector without a separate vector store.
  • Keep the stack's defaults. Auth stays Clerk and payments stay Stripe. Don't swap in Managed Better Auth unless a project has no auth provider or the user asks to migrate. Neon's own guidance says the same: keep a working IdP.
  • Secrets server-side only. DATABASE_URL*, NEON_API_KEY, NEON_AI_GATEWAY_TOKEN, AWS_SECRET_ACCESS_KEY, NEON_AUTH_COOKIE_SECRET and NEON_REALTIME_SECRET never get a NEXT_PUBLIC_ prefix. Store them in Hazina; prefer --no-env-pull + neon-env run when an agent shouldn't write a .env. Never paste connection strings into chat.
  • Authorization lives in code. Neon has no service-role key, but Functions have public URLs and the Data API leans on RLS — verify the caller's JWT (Clerk JWKS works too) and scope every query to that user.
  • AI routing. Anthropic Claude stays primary. Calling Claude directly is the default; the AI Gateway is an option when the code already runs on Neon Functions and one branch-scoped credential is worth more than direct provider keys. It needs a paid plan and prepaid credits.
  • Kenya-targeted projects. No Neon region is in Africa. Use aws-eu-central-1 (Frankfurt) — the nearest region that also has Functions/Storage/Gateway — so M-Pesa callback handlers on Functions sit next to the data. Verify Daraja callbacks inside the Function (it's a public URL), store CheckoutRequestID before replying, and dedupe on callback. Functions require ≥ 1 byte per 15 min on quiet streams; Daraja callbacks are short POSTs, so this only matters for SSE/WebSocket status feeds.
  • Branch hygiene. Give dev/preview branches a ttl in neon.ts or expires_at in CI. Free plan stops at 10 branches; paid extras are $1.50/branch-month.
  • MCP is for dev/test. Use ?readonly=true&projectId=… for analysis sessions; never connect it to production.