agentleFS
Leo-AtienzaLeo-Atienza/atlas-claude/skills/drizzle-neon/SKILL.md

drizzle-neon

Skill4 starsChanged 4 months agoMITView on GitHub

Drizzle ORM 0.45 + Neon serverless Postgres for Next.js 16: schemas, HTTP vs WebSocket connections, migrations, RSC patterns, and this environment's Neon MCP tools.

  • Reads credentials
  • Installs packages

The file

Files
SKILL.md

Drizzle ORM + Neon Postgres for Next.js 16

The 2026 serverless-native database stack. SQL-like TypeScript queries, types inferred from schema, ~60KB Drizzle client (vs Prisma's ~500KB+), zero codegen step, first-class edge runtime support.

Version pairing (verified 2026-07-04 via npm view)

PackageVersionNotes
drizzle-orm^0.45Core ORM, runtime-only ~60KB. Stable line (0.45.2 as of 2026-07-04). v1.0 is RC-only (1.0.0-rc.4, 2026-06-27 — relations v2, codec system, drizzle-kit SDK + MCP server); stay on 0.45 until GA, then follow the v1 upgrade guide.
drizzle-kitlatestCLI for migrations + studio
@neondatabase/serverlesslatestNeon's HTTP/WebSocket driver — edge-native
dotenv (or use Next.js env)optionalLocal env loading for migration scripts

Install

npm install drizzle-orm @neondatabase/serverless
npm install -D drizzle-kit

Add to .env.local:

DATABASE_URL=postgresql://user:pass@ep-cool-name.region.neon.tech/dbname?sslmode=require

(Get this from Neon dashboard or via the neon-postgres Anthropic skill / mcp__MCP_DOCKER__get_connection_string MCP tool.)

Schema

db/schema.ts — the single source of truth. Types are inferred from here:

import { pgTable, text, timestamp, uuid, integer, boolean, index } from 'drizzle-orm/pg-core';
import { sql } from 'drizzle-orm';

export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  email: text('email').notNull().unique(),
  name: text('name').notNull(),
  createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
}, (t) => ({
  emailIdx: index('users_email_idx').on(t.email),
}));

export const posts = pgTable('posts', {
  id: uuid('id').primaryKey().defaultRandom(),
  authorId: uuid('author_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
  title: text('title').notNull(),
  body: text('body').notNull(),
  published: boolean('published').notNull().default(false),
  views: integer('views').notNull().default(0),
  createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
});

// Inferred types — use these everywhere
export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;
export type Post = typeof posts.$inferSelect;
export type NewPost = typeof posts.$inferInsert;

Connection — pick the right driver

Neon offers two transport modes via @neondatabase/serverless. Choose by runtime:

HTTP (recommended default — Vercel Edge + Node)

// db/index.ts
import { neon } from '@neondatabase/serverless';
import { drizzle } from 'drizzle-orm/neon-http';
import * as schema from './schema';

const sql = neon(process.env.DATABASE_URL!);
export const db = drizzle({ client: sql, schema });

Works everywhere. One round-trip per query (no transactions across queries). Best for stateless Vercel handlers.

WebSocket pool (when you need multi-statement transactions)

import { Pool } from '@neondatabase/serverless';
import { drizzle } from 'drizzle-orm/neon-serverless';
import * as schema from './schema';

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
export const db = drizzle({ client: pool, schema });

Required for db.transaction(async (tx) => { ... }). Slightly heavier — uses persistent WebSocket. Edge-compatible.

Queries (SQL-shaped TypeScript)

import { db } from '@/db';
import { users, posts } from '@/db/schema';
import { eq, and, desc, ilike } from 'drizzle-orm';

// SELECT
const allUsers = await db.select().from(users);

const user = await db.select().from(users).where(eq(users.email, 'a@b.com')).limit(1);

const recentPosts = await db
  .select()
  .from(posts)
  .where(and(eq(posts.published, true), ilike(posts.title, '%next%')))
  .orderBy(desc(posts.createdAt))
  .limit(20);

// JOIN
const postsWithAuthors = await db
  .select({
    post: posts,
    authorName: users.name,
  })
  .from(posts)
  .innerJoin(users, eq(users.id, posts.authorId))
  .where(eq(posts.published, true));

// INSERT (typed via NewPost)
const [created] = await db
  .insert(posts)
  .values({ authorId: user[0].id, title: 'Hello', body: 'World' })
  .returning();

// UPDATE
await db.update(posts).set({ views: sql`${posts.views} + 1` }).where(eq(posts.id, created.id));

// DELETE
await db.delete(posts).where(eq(posts.id, created.id));

Relational queries (eager loading with types)

// db/schema.ts (additional)
import { relations } from 'drizzle-orm';

export const usersRelations = relations(users, ({ many }) => ({
  posts: many(posts),
}));

export const postsRelations = relations(posts, ({ one }) => ({
  author: one(users, { fields: [posts.authorId], references: [users.id] }),
}));

// Query:
const u = await db.query.users.findFirst({
  where: eq(users.id, '...'),
  with: {
    posts: {
      where: eq(posts.published, true),
      orderBy: desc(posts.createdAt),
      limit: 5,
    },
  },
});
// u is typed as User & { posts: Post[] } — no manual type annotation

Migrations — push (dev) vs migrate (prod)

drizzle.config.ts

import { defineConfig } from 'drizzle-kit';

export default defineConfig({
  schema: './db/schema.ts',
  out: './db/migrations',
  dialect: 'postgresql',
  dbCredentials: { url: process.env.DATABASE_URL! },
});

Dev workflow — drizzle-kit push

npx drizzle-kit push

Diffs your schema against the live DB and applies changes directly. No migration files. Fast iteration. Never use in production — destructive changes (column drops, type changes) execute without review.

Production workflow — drizzle-kit migrate

npx drizzle-kit generate    # writes SQL migration to db/migrations/
# Review the SQL
npx drizzle-kit migrate     # applies pending migrations

Committed migration files give you a reviewable, reversible audit trail. Run migrate in CI as a deploy step before the new server starts.

Drizzle Studio (local DB GUI)

npx drizzle-kit studio   # localhost browser GUI for your DB

Faster than psql for ad-hoc browsing.

Next.js 16 + RSC patterns

Server Component direct query (cheapest)

// app/posts/page.tsx
import { db } from '@/db';
import { posts, users } from '@/db/schema';
import { eq, desc } from 'drizzle-orm';

export default async function PostsPage() {
  const rows = await db
    .select({ post: posts, author: users.name })
    .from(posts)
    .innerJoin(users, eq(users.id, posts.authorId))
    .where(eq(posts.published, true))
    .orderBy(desc(posts.createdAt));

  return (
    <ul>
      {rows.map(({ post, author }) => (
        <li key={post.id}>{post.title} by {author}</li>
      ))}
    </ul>
  );
}

With Cache Components (use cache)

async function getPublishedPosts() {
  'use cache';
  cacheLife('hours');
  cacheTag('posts');
  return db.select().from(posts).where(eq(posts.published, true));
}

Pair with revalidateTag('posts') from a Server Action after a mutation — fresh data on next read, no client refetch needed.

Server Action with optimistic invalidation

'use server';

import { db } from '@/db';
import { posts } from '@/db/schema';
import { revalidateTag } from 'next/cache';

export async function createPost(formData: FormData) {
  await db.insert(posts).values({
    authorId: '...',
    title: formData.get('title') as string,
    body: formData.get('body') as string,
  });
  revalidateTag('posts');
}

ATLAS Neon MCP tools (already available)

This environment ships with Neon MCP tools — use them BEFORE writing manual psql queries:

ToolPurpose
mcp__MCP_DOCKER__list_projectsList your Neon projects
mcp__MCP_DOCKER__describe_projectConnection strings, branches, roles
mcp__MCP_DOCKER__get_connection_stringPull a DATABASE_URL for any branch
mcp__MCP_DOCKER__run_sqlOne-shot SQL — handy for inspection
mcp__MCP_DOCKER__run_sql_transactionMulti-statement
mcp__MCP_DOCKER__describe_table_schemaInspect a table's columns/indexes
mcp__MCP_DOCKER__prepare_database_migration / complete_database_migrationBranch-based safe migrations (test on a branch, then merge)
mcp__MCP_DOCKER__prepare_query_tuning / complete_query_tuningEXPLAIN-driven index suggestions

The anthropic-skills:neon-postgres skill is also active — load it for Neon-specific features (auth, branching, data API).

Common bugs

SymptomCauseFix
DATABASE_URL is undefinedEdge runtime, env not loadedUse process.env.DATABASE_URL! and ensure it's set in Vercel project env (not just .env.local)
transaction is not a functionUsing neon-http driverSwitch to neon-serverless (WebSocket pool) for transactions
drizzle-kit push hangsNeon endpoint coldWait 10s for cold start; or hit the DB with a SELECT 1 first
Schema drift after pushForgot to git add db/schema.tsThe schema file IS the source of truth — always commit it
Types not updating in IDETS server cachedRestart TS server (Cmd+Shift+P → TypeScript: Restart)
Slow first query in serverlessConnection pool coldUse the HTTP driver (no pool), or warm up via a route handler called by Vercel Cron

When NOT to use Drizzle / Neon

  • You want a managed admin UI for non-devs → Supabase (Postgres + Auth + Studio in one)
  • You need offline-first / sync → use PowerSync, Yjs, or Replicache + Postgres backend
  • You're on Cloudflare D1 / Turso → Drizzle still works (just swap driver), but skip Neon entirely

Sources

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.