- Published on
Use Drizzle with Neon in Next.js
- Authors
- Name
- Shelton Ma
1. Setup PostgreSQL with Neon
Sign In: neon, create a project on Neon
2. Configure Drizzle ORM
1. Documentation
Drizzle ORM Documentation for Neon
2. alias scripts
// package.json
"scripts": {
"db:generate": "npx drizzle-kit generate",
"db:migrate": "npx drizzle-kit migrate",
"db:studio": "npx drizzle-kit studio"
},
Get Started with Drizzle and PostgreSQL
3. Setup:File Structure
📦 <project root> ├ 📂 drizzle ├ 📂 src │ ├ 📂 db │ │ └ 📜 schema.ts │ └ 📜 index.ts ├ 📜 .env ├ 📜 drizzle.config.ts ├ 📜 package.json └ 📜 tsconfig.json
Install Dependencies
pnpm add drizzle-orm pg dotenv pnpm add -D drizzle-kit tsx @types/pg pnpm add @neondatabase/serverless
Set Up Environment Variables
in .env.local DATABASE_URL=
Connect Drizzle ORM to the Database
src/db/drizzle.ts
import { neon } from "@neondatabase/serverless"; import { drizzle } from "drizzle-orm/neon-http"; const sql = neon(process.env.DATABASE_URL!); export const db = drizzle({ client: sql });
Create tables in
src/db/schema.ts
.import { integer, text, pgTable } from "drizzle-orm/pg"; export const users = pgTable("users", { id: integer("id").primaryKey().autoIncrement(), name: text("name"), email: text("email").unique().notNull(), });
Setup Drizzle config file
drizzle.config.ts
import { defineConfig } from "drizzle-kit"; export default defineConfig({ schema: "./src/db/schema.ts", out: "./drizzle", driver: "pg", dbCredentials: { connectionString: process.env.DATABASE_URL!, }, });
Applying changes to the database
npx drizzle-kit generate # pnpm run db:generate npx drizzle-kit migrate # pnpm run db:migrate npx drizzle-kit studio # pnpm run db:studio
Usage
import { db } from "@/db/drizzle";
const data = await db
.select()
.from(projects)
.where(eq(projects.userId, userId))
.limit(limit)
.offset((page - 1) * limit)
.orderBy(desc(projects.updatedAt));