Skip to content
Database & Auth guide

How to Connect Postgres to Next.js with Drizzle ORM

Connect a Next.js App Router app to Postgres with Drizzle ORM and node-postgres, run migrations, read data in a Server Component and write it from a Server Action.

20 min Beginner Markdown for AI

What you'll build

  • A typed Drizzle schema and generated SQL migrations
  • One database pool per process that survives dev hot reloads
  • Migrations that run over a direct connection, queries over the pooler
  • A todo list read in a Server Component and updated by a Server Action

Before you start

  • Node.js 20 or newer
  • A Next.js 16 app using the App Router (npx create-next-app@latest)
  • A free CloudHike.dev account

Why Drizzle and node-postgres

Drizzle is a thin, typed layer over SQL. You describe tables in TypeScript, and your queries get full types without a code generation step or a separate query engine. It pairs well with pg (node-postgres), the most widely used Postgres driver for Node.js.

PieceWhat it does
drizzle-ormThe query builder and schema types your app imports
pgOpens and pools the real connections to Postgres
drizzle-kitA dev tool that turns your schema into SQL migration files and applies them

All of this runs on the server only. Database credentials never reach the browser, and a Client Component can't open a database connection.

Step 1: Create a database and install packages

  1. Sign in at cloudhike.dev and create a project.
  2. Click Deploy on the Postgres card and wait until it shows as ready.
  3. Click Copy as .env and paste the values into .env.local at the root of your Next.js app.
.env.local
Shell
# Pooled connection for your app's queries
DATABASE_URL=postgresql://...
# Direct connection for migrations (only on pooled databases)
DIRECT_URL=postgresql://...

Two URLs, two jobs. DATABASE_URL goes through a connection pooler (PgBouncer), so many app connections share a few real ones. That is what you want for queries. DIRECT_URL skips the pooler, which migrations need. The Postgres docs explain the difference in detail.

Terminal
Shell
npm install drizzle-orm pg server-only
npm install -D drizzle-kit @types/pg

Never prefix these variables with NEXT_PUBLIC_. That would bundle your database password into browser JavaScript.

Step 2: Define your schema

Each table is a pgTable() call. The TypeScript key is what you use in code, and the string is the real column name in Postgres.

db/schema.ts
TypeScript
import { boolean, integer, pgTable, text, timestamp } from "drizzle-orm/pg-core";

export const todos = pgTable("todos", {
  id: integer("id").primaryKey().generatedAlwaysAsIdentity(),
  title: text("title").notNull(),
  done: boolean("done").notNull().default(false),
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});

// Row types, inferred from the table. No codegen needed.
export type Todo = typeof todos.$inferSelect;
export type NewTodo = typeof todos.$inferInsert;

Step 3: Create a database client that survives hot reload

Create the pool once per server process. In development, Next.js reloads your modules on every save. If you create the pool at module level without care, each reload opens a new pool and the old one stays connected until you hit the connection limit. Keeping it on globalThis fixes that.

db/index.ts
TypeScript
import "server-only";
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";
import * as schema from "./schema";

const globalForDb = globalThis as unknown as { pool?: Pool };

// A small pool: the pooler behind DATABASE_URL does the heavy lifting.
const pool =
  globalForDb.pool ??
  new Pool({
    connectionString: process.env.DATABASE_URL,
    max: 5,
    idleTimeoutMillis: 30_000,
  });

if (process.env.NODE_ENV !== "production") globalForDb.pool = pool;

// Log pool errors instead of crashing the process when an idle
// connection is closed by the server.
pool.on("error", (err) => console.error("Postgres pool error", err));

export const db = drizzle(pool, { schema });

The server-only import makes the build fail if a Client Component ever imports db. Keep it in every file that touches the database.

Idle connections are closed by the server after a few minutes. That is fine: pg opens a new one on the next query. See Connect for the exact rules.

Step 4: Run migrations over DIRECT_URL

drizzle-kit reads a config file that says where your schema is and how to reach the database. Point it at DIRECT_URL, because migrations hold locks and run statements a transaction pooler can't handle. If your database has no pooler, DIRECT_URL is not set, so fall back to DATABASE_URL.

drizzle.config.ts
TypeScript
import { loadEnvConfig } from "@next/env";
import { defineConfig } from "drizzle-kit";

// drizzle-kit doesn't read .env.local on its own. This loads it the same way Next.js does.
loadEnvConfig(process.cwd());

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

@next/env ships with Next.js, so there is nothing extra to install. Add two scripts to package.json:

package.json
JSON
{
  "scripts": {
    "db:generate": "drizzle-kit generate",
    "db:migrate": "drizzle-kit migrate"
  }
}
Terminal
Shell
npm run db:generate   # writes drizzle/0000_*.sql from your schema
npm run db:migrate    # applies new migrations to the database

Open the generated SQL file and read it before you apply it. Commit the drizzle/ folder to git, so every environment runs the same migrations in the same order. You can check the new table on the Data tab of Open database in your CloudHike dashboard.

drizzle/0000_initial.sql (generated, shortened)
SQL
CREATE TABLE "todos" (
  "id" integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
  "title" text NOT NULL,
  "done" boolean DEFAULT false NOT NULL,
  "created_at" timestamp with time zone DEFAULT now() NOT NULL
);

drizzle-kit push applies the schema without migration files. It is handy for quick prototypes, but use generate and migrate for anything with real data, so you can review every change.

Step 5: Query from a Server Component

Server Components can be async, so you query the database right inside the component. There is no API route and no client fetch. Put the query in a small component wrapped in <Suspense>, so the rest of the page can render first.

app/todos/page.tsx
TSX
import { Suspense } from "react";
import { connection } from "next/server";
import { desc } from "drizzle-orm";
import { db } from "@/db";
import { todos } from "@/db/schema";
import { AddTodoForm } from "./add-todo-form";
import { toggleTodo } from "./actions";

async function TodoList() {
  // Wait for a real request, so the list is never baked in at build time.
  await connection();

  const rows = await db.select().from(todos).orderBy(desc(todos.createdAt)).limit(50);

  if (rows.length === 0) return <p>No todos yet. Add one above.</p>;

  return (
    <ul className="grid gap-2">
      {rows.map((todo) => (
        <li key={todo.id}>
          <form action={toggleTodo.bind(null, todo.id, !todo.done)}>
            <button>{todo.done ? "✅" : "⬜️"}</button> {todo.title}
          </form>
        </li>
      ))}
    </ul>
  );
}

export default function TodosPage() {
  return (
    <main className="mx-auto grid max-w-md gap-4 p-8">
      <h1>Todos</h1>
      <AddTodoForm />
      <Suspense fallback={<p>Loading…</p>}>
        <TodoList />
      </Suspense>
    </main>
  );
}

connection() tells Next.js this part depends on the request. Without it, a page with no cookies or headers could be prerendered once at build time and show stale rows forever. With Cache Components on (the create-next-app default in Next.js 16), the <Suspense> boundary lets the static shell stream first while the list loads.

Step 6: Insert from a Server Action

A Server Action runs on the server and can be passed straight to a form. After the write, call revalidatePath() so the page shows the new row on the same round trip.

app/todos/actions.ts
TypeScript
"use server";

import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { db } from "@/db";
import { todos } from "@/db/schema";

export type AddTodoState = { ok: boolean; message: string } | null;

export async function addTodo(_prev: AddTodoState, form: FormData): Promise<AddTodoState> {
  const title = String(form.get("title") ?? "").trim();

  if (title.length < 1 || title.length > 200) {
    return { ok: false, message: "Give your todo a title of 1 to 200 characters." };
  }

  try {
    await db.insert(todos).values({ title });
  } catch (err) {
    console.error(err);
    return { ok: false, message: "Could not save your todo. Please try again." };
  }

  revalidatePath("/todos");
  return { ok: true, message: "Added." };
}

export async function toggleTodo(id: number, done: boolean) {
  await db.update(todos).set({ done }).where(eq(todos.id, id));
  revalidatePath("/todos");
}
app/todos/add-todo-form.tsx
TSX
"use client";

import { useActionState } from "react";
import { addTodo } from "./actions";

export function AddTodoForm() {
  const [state, action, pending] = useActionState(addTodo, null);

  return (
    <form action={action} className="flex gap-2">
      <input name="title" placeholder="Buy milk" required maxLength={200} />
      <button disabled={pending}>{pending ? "Adding…" : "Add"}</button>
      {state && !state.ok && <p role="alert">{state.message}</p>}
    </form>
  );
}

Run npm run dev and open http://localhost:3000/todos. Add a few items, tick one off and reload: the data comes from Postgres every time.

Server Actions are public endpoints. Anyone can call them with any arguments. In a real app, check who the user is before every write. Protect Routes and Server Actions in Next.js 16 shows how.

Production checklist

  • Add DATABASE_URL and DIRECT_URL to your host's environment variables (Vercel: Project → Settings → Environment Variables). The environment docs cover other hosts.
  • Run npm run db:migrate as a deploy step before the new code goes live, not from inside a request.
  • Keep the pool small (3 to 5). On serverless hosts, each instance opens its own pool, and they all count toward the connection limit.
  • If you see too many connections for role, click Close idle connections in Open database, then check for pools created outside the globalThis pattern.
  • Add an index for every column you filter or sort on often, such as created_at here.
  • Nightly backups are on by default. Learn how to restore one in the backup docs.

Frequently asked questions

Should I use DATABASE_URL or DIRECT_URL with Drizzle?

Use DATABASE_URL, the pooled connection, for your app's queries. Use DIRECT_URL for drizzle-kit migrations, pg_dump, LISTEN and NOTIFY, and anything that needs one connection for longer than a transaction. If DIRECT_URL is not set, your database has no pooler and DATABASE_URL works for both.

Why do I get too many connections in Next.js development?

Each hot reload re-runs your modules. If the pool is created at module level, every save opens a new pool while the old one stays connected. Store the pool on globalThis in development so reloads reuse it.

Can I use Drizzle in a Next.js Client Component?

No. Drizzle needs a database connection and credentials, which must stay on the server. Query in a Server Component, or call a Server Action or Route Handler from the client.

Is Drizzle better than Prisma for Next.js?

Both work well. Drizzle has no code generation step or separate engine, so it starts fast on serverless and feels close to SQL. Prisma has a bigger ecosystem and a more abstract query API. The connection advice here applies to either: pooled URL for queries, direct URL for migrations.

Do I need drizzle-kit in production?

Only to apply migrations, which you run as a deploy step. Your running app imports drizzle-orm and pg, not drizzle-kit, so keep drizzle-kit in devDependencies.