| name | neon |
| description | Neon serverless Postgres with autoscaling, instant database branching, and zero-downtime deployments. Use when building serverless applications, implementing database branching for dev/staging, or deploying with Vercel/Netlify. |
| user-invocable | false |
| disable-model-invocation | true |
| progressive_disclosure | {"entry_point":{"summary":"Neon serverless Postgres with autoscaling, instant database branching, and zero-downtime deployments. Use when building serverless applications, implementing database branching for dev/staging, or ...","when_to_use":"When working with neon-serverless-postgres or related functionality.","quick_start":"1. Review the core concepts below. 2. Apply patterns to your use case. 3. Follow best practices for implementation."}} |
Neon Serverless Postgres Skill
progressive_disclosure:
entry_point:
summary: "Serverless Postgres with autoscaling, branching, and instant database provisioning"
when_to_use:
- "When needing serverless Postgres"
- "When building edge and serverless apps"
- "When implementing database branching for dev/staging"
- "When using Drizzle, Prisma, or raw SQL"
quick_start:
- "Create project on Neon console"
- "Get connection string"
- "Connect with Drizzle/Prisma/pg"
- "Deploy with Vercel/Netlify"
token_estimate:
entry: 75-90
full: 3800-4800
Core Concepts
Neon Architecture
- Projects: Top-level container for databases and branches
- Databases: Postgres databases within a project
- Branches: Git-like database copies for development
- Compute: Autoscaling Postgres instances
- Storage: Separated from compute for instant branching
Key Features
- Serverless: Pay-per-use, scales to zero
- Branching: Instant database copies from any point in time
- Autoscaling: Compute scales based on load
- Instant Provisioning: Databases ready in seconds
- Connection Pooling: Built-in PgBouncer support
Connection Strings
Standard Connection
DATABASE_URL="postgresql://user:password@ep-xxx.region.aws.neon.tech/dbname"
DATABASE_URL="postgresql://user:password@ep-xxx.region.aws.neon.tech/dbname?sslmode=require"
Connection Pooling
DATABASE_URL="postgresql://user:password@ep-xxx-pooler.region.aws.neon.tech/dbname?sslmode=require"
DIRECT_URL="postgresql://user:password@ep-xxx.region.aws.neon.tech/dbname"
Drizzle ORM Integration
Setup
import type { Config } from "drizzle-kit";
export default {
schema: "./src/db/schema.ts",
out: "./drizzle",
driver: "pg",
dbCredentials: {
connectionString: process.env.DATABASE_URL!,
},
} satisfies Config;
import { drizzle } from "drizzle-orm/neon-http";
import { neon } from "@neondatabase/serverless";
const sql = neon(process.env.DATABASE_URL!);
export const db = drizzle(sql);
Schema Definition
import { pgTable, serial, text, timestamp, varchar } from "drizzle-orm/pg-core";
export const users = pgTable("users", {
id: serial("id").primaryKey(),
name: varchar("name", { length: 255 }).notNull(),
email: varchar("email", { length: 255 }).notNull().unique(),
createdAt: timestamp("created_at").defaultNow(),
});
export const posts = pgTable("posts", {
id: serial("id").primaryKey(),
title: text("title").notNull(),
content: text("content"),
userId: serial("user_id").references(() => users.id),
createdAt: timestamp().(),
});
Queries
import { db } from "./db";
import { users, posts } from "./db/schema";
import { eq } from "drizzle-orm";
const newUser = await db.insert(users).values({
name: "John Doe",
email: "john@example.com",
}).returning();
const allUsers = await db.select().from(users);
const userPosts = await db
.select()
.from(posts)
.leftJoin(users, eq(posts.userId, users.id));
await db.update(users)
.set({ name: "Jane Doe" })
.where(eq(users.id, 1));
Migrations
npx drizzle-kit generate:pg
npx drizzle-kit push:pg
import { drizzle } from "drizzle-orm/postgres-js";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import postgres from "postgres";
const sql = postgres(process.env.DIRECT_URL!, { max: 1 });
const db = drizzle(sql);
await migrate(db, { migrationsFolder: "./drizzle" });
await sql.end();
Prisma Integration
Setup
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL") // For migrations
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
posts Post[]
createdAt DateTime @default(now())
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
userId Int
user User @relation(fields: [userId], references: [id])
createdAt DateTime @default(now())
}
Client Usage
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
const user = await prisma.user.create({
data: {
name: "John Doe",
email: "john@example.com",
},
});
const userWithPosts = await prisma.user.findUnique({
where: { id: 1 },
include: { posts: true },
});
await prisma.$transaction([
prisma.user.create({ data: { name: "User 1", email: "u1@example.com" } }),
prisma.user.create({ data: { name: "User 2", email: "u2@example.com" } }),
]);
Migrations
npx prisma migrate dev --name init
npx prisma migrate deploy
npx prisma generate
Node-Postgres (pg) Integration
Direct Connection
import { Pool } from "pg";
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false },
});
const result = await pool.query("SELECT * FROM users WHERE email = $1", [
"john@example.com",
]);
const client = await pool.connect();
try {
await client.query("BEGIN");
await client.query("INSERT INTO users (name, email) VALUES ($1, $2)", [
"John",
"john@example.com",
]);
await client.query("COMMIT");
} catch (e) {
await client.query("ROLLBACK");
throw e;
} finally {
client.release();
}
Serverless Driver
import { neon, neonConfig } from "@neondatabase/serverless";
neonConfig.fetchConnectionCache = true;
const sql = neon(process.env.DATABASE_URL!);
const result = await sql`SELECT * FROM users WHERE email = ${email}`;
const [user] = await sql.transaction([
sql`INSERT INTO users (name, email) VALUES (${name}, ${email}) RETURNING *`,
sql`INSERT INTO audit_log (action) VALUES ('user_created')`,
]);
Database Branching
Branch Types
- Main: Production branch
- Development: Feature development
- Preview: PR/deployment previews
- Testing: QA and testing environments
Creating Branches
neonctl branches create --name dev --parent main
curl -X POST https://console.neon.tech/api/v2/projects/{project_id}/branches \
-H "Authorization: Bearer $NEON_API_KEY" \
-d '{"name": "dev", "parent_id": "main"}'
Branch Workflows
Feature Development
neonctl branches create --name feature/user-auth --parent dev
neonctl connection-string feature/user-auth
DATABASE_URL="postgresql://...feature-user-auth..."
npm run migrate
neonctl branches delete feature/user-auth
Preview Deployments
{
"env": {
"DATABASE_URL": "@database-url-main"
},
"build": {
"env": {
"DATABASE_URL": "@database-url-preview"
}
}
}
- name: Create Neon Branch
run: |
BRANCH_NAME="preview-${{ github.event.number }}"
neonctl branches create --name $BRANCH_NAME --parent main
DATABASE_URL=$(neonctl connection-string $BRANCH_NAME)
echo "DATABASE_URL=$DATABASE_URL" >> $GITHUB_ENV
Point-in-Time Recovery
neonctl branches create --name recovery \
--parent main \
--timestamp "2024-01-15T10:30:00Z"
neonctl branches reset main --from recovery
Vercel Integration
Automatic Setup
npm i -g vercel
vercel link
vercel integration add neon
Manual Configuration
vercel env add DATABASE_URL
vercel env add DATABASE_URL preview
vercel env add DATABASE_URL production
Next.js Integration
import { neon } from "@neondatabase/serverless";
export const runtime = "edge";
export async function GET() {
const sql = neon(process.env.DATABASE_URL!);
const users = await sql`SELECT * FROM users`;
return Response.json(users);
}
export async function GET(
request: Request,
{ params }: { params: { id: string } }
) {
const sql = neon(process.env.DATABASE_URL!);
const [user] = await sql`SELECT * FROM users WHERE id = ${params.id}`;
if (!user) {
return new Response("Not found", { status: 404 });
}
return Response.json(user);
}
Connection Pooling
PgBouncer Pooling
const pooledDb = drizzle(neon(process.env.DATABASE_URL!));
const directDb = drizzle(neon(process.env.DIRECT_URL!));
{
"scripts": {
"migrate": "DATABASE_URL=$DIRECT_URL drizzle-kit push:pg",
"dev": "next dev"
}
}
Connection Limits
import { Pool } from "pg";
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
});
import { neon } from "@neondatabase/serverless";
Autoscaling and Compute
Compute Units
- 0.25 Compute Units (CU)
- Scales to zero when idle
- Shared compute
- 0.25 - 4 CU autoscaling
- Configurable min/max
- Dedicated compute
Configuration
neonctl set-compute --min 0.25 --max 2 --branch main
curl -X PATCH https://console.neon.tech/api/v2/projects/{id}/branches/{branch_id} \
-d '{"compute": {"min_cu": 0.25, "max_cu": 2}}'
Autoscaling Strategy
const computeConfig = {
dev: { min: 0.25, max: 1 },
staging: { min: 0.5, max: 2 },
main: { min: 1, max: 4 },
};
Read Replicas
Setup
neonctl read-replica create --branch main --region us-east-1
neonctl connection-string --replica
Usage Pattern
const writeDb = drizzle(neon(process.env.DATABASE_URL!));
const readDb = drizzle(neon(process.env.DATABASE_URL_REPLICA!));
async function getUser(id: number) {
return await readDb.select().from(users).where(eq(users.id, id));
}
async function updateUser(id: number, data: any) {
return await writeDb.update(users).set(data).where(eq(users.id, id));
}
const replicas = [
process.env.DATABASE_URL_REPLICA_1!,
process.env.DATABASE_URL_REPLICA_2!,
];
function getReadConnection() {
const url = replicas[Math.(.() * replicas.)];
((url));
}
CLI Usage
Installation
npm install -g neonctl
npx neonctl --help
Common Commands
neonctl auth
neonctl projects list
neonctl projects create --name my-app
neonctl branches list
neonctl branches create --name dev --parent main
neonctl connection-string main
neonctl databases create --name analytics
neonctl databases list
neonctl set-compute --min 0.5 --max 2
neonctl branches delete dev
Migration Strategies
Drizzle Migrations
import { drizzle } from "drizzle-orm/postgres-js";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import postgres from "postgres";
const runMigrations = async () => {
const connection = postgres(process.env.DIRECT_URL!, { max: 1 });
const db = drizzle(connection);
console.log("Running migrations...");
await migrate(db, { migrationsFolder: "./drizzle" });
console.log("Migrations complete!");
await connection.end();
};
runMigrations();
Prisma Migrations
npx prisma migrate dev --name add_users_table
npx prisma migrate deploy
npx prisma migrate reset
Zero-Downtime Migrations
ALTER TABLE users ADD COLUMN new_email VARCHAR(255);
UPDATE users SET new_email = email;
ALTER TABLE users ALTER COLUMN new_email SET NOT NULL;
ALTER TABLE users DROP COLUMN email;
ALTER TABLE users RENAME COLUMN new_email TO email;
Branch-Based Migrations
neonctl branches create --name migration/add-index --parent main
DATABASE_URL=$(neonctl connection-string migration/add-index) \
npm run migrate
DATABASE_URL=$(neonctl connection-string migration/add-index) \
npm run test
npm run migrate:production
neonctl branches delete migration/add-index
Best Practices
Serverless Optimization
import { neon } from "@neondatabase/serverless";
const sql = neon(process.env.DATABASE_URL!);
import { neonConfig } from "@neondatabase/serverless";
neonConfig.fetchConnectionCache = true;
const pooledUrl = process.env.DATABASE_URL;
Connection Management
let cachedDb: ReturnType<typeof drizzle> | null = null;
function getDb() {
if (!cachedDb) {
const sql = neon(process.env.DATABASE_URL!);
cachedDb = drizzle(sql);
}
return cachedDb;
}
await db.transaction(async (tx) => {
await tx.insert(users).values({ name: "John" });
await tx.insert(auditLog).values({ action: "user_created" });
});
Branch Strategy
Environments:
main: Production data
staging: Pre-production testing
dev: Shared development
feature/*: Individual features
preview/*: PR previews (auto-created)
Lifecycle:
- Create from parent on feature start
- Run migrations independently
- Test thoroughly
- Merge schema changes
- Delete after feature completion
Cost Optimization
Environment Variables
Required Variables
DATABASE_URL="postgresql://user:pass@ep-xxx-pooler.region.aws.neon.tech/db?sslmode=require"
DIRECT_URL="postgresql://user:pass@ep-xxx.region.aws.neon.tech/db?sslmode=require"
NEON_API_KEY="your_api_key"
NEON_PROJECT_ID="your_project_id"
Multi-Environment Setup
DATABASE_URL="postgresql://...dev-branch..."
DATABASE_URL="postgresql://...staging-branch..."
DATABASE_URL="postgresql://...main-branch..."
Common Patterns
API Route with Caching
import { neon } from "@neondatabase/serverless";
export const runtime = "edge";
export async function GET() {
const sql = neon(process.env.DATABASE_URL!);
const users = await sql`SELECT * FROM users ORDER BY created_at DESC LIMIT 10`;
return Response.json(users, {
headers: {
"Cache-Control": "s-maxage=60, stale-while-revalidate",
},
});
}
Server Actions (Next.js)
"use server";
import { neon } from "@neondatabase/serverless";
import { revalidatePath } from "next/cache";
export async function createUser(formData: FormData) {
const sql = neon(process.env.DATABASE_URL!);
const name = formData.get("name") as string;
const email = formData.get("email") as string;
await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`;
revalidatePath("/users");
}
Connection Testing
async function testConnection() {
const sql = neon(process.env.DATABASE_URL!);
try {
const result = await sql`SELECT version()`;
console.log("✅ Connected to Neon:", result[0].version);
return true;
} catch (error) {
console.error("❌ Connection failed:", error);
return false;
}
}
Troubleshooting
Connection Issues
const url = new URL(process.env.DATABASE_URL!);
if (!url.searchParams.has("sslmode")) {
url.searchParams.set("sslmode", "require");
}
import { neon } from "@neondatabase/serverless";
const sql = neon(process.env.DATABASE_URL!);
await sql`SELECT 1`;
Migration Failures
export DIRECT_URL="postgresql://...direct-endpoint..."
npx prisma migrate deploy
npx prisma migrate status
npx prisma migrate reset
Performance Issues
import { drizzle } from "drizzle-orm/neon-http";
const db = drizzle(sql, { logger: true });
await sql`CREATE INDEX idx_users_email ON users(email)`;
This skill provides comprehensive coverage of Neon serverless Postgres, including database branching, ORM integrations, serverless deployment patterns, and production best practices.