How to Connect Postgres to a Next.js Admin Dashboard with Drizzle ORM (2026)
Step by step: replace mock data in a Next.js 16 shadcn/ui admin dashboard with a real Postgres database using Drizzle ORM, with server-side filtering, search, sorting and pagination.
Short answer: To connect Postgres to a Next.js admin dashboard, install drizzle-orm and pg, define your table in a Drizzle schema, push it with drizzle-kit push, and replace the mock functions in your data layer with Drizzle queries. In Shadcn Dashboard by Kiranism, that's one file per feature (service.ts). The tables, forms and TanStack Query cache keep working without changes.
"How do I add a Postgres adapter?" is one of the most asked questions on the starter's GitHub, so this guide walks through the whole thing with the products table as the example. Every code block here was typechecked against the starter and run against Postgres 17.
What you'll build: the products table at /dashboard/product, reading from Postgres, with search, category filters, sorting and pagination done in SQL instead of in memory.
Versions used: Next.js 16, Drizzle ORM 0.45, drizzle-kit 0.31, node-postgres 8, Postgres 17.
How the data layer is organized
Each feature in the starter has the same three files:
src/features/products/api/
├── types.ts # Response and filter types
├── service.ts # Data access. The ONLY file you change.
└── queries.ts # TanStack Query options (keys + fetchers)
queries.ts calls the functions in service.ts, and every component calls queries.ts. So when service.ts stops reading mock data and starts reading Postgres, nothing above it notices. That's the whole trick, and it's why this guide is short.
Step 1: Install Drizzle and the Postgres driver
bun add drizzle-orm pg
bun add -d drizzle-kit @types/pgAny Postgres works: local, Docker, Neon, Supabase, Railway or RDS. Add the connection string to .env.local:
DATABASE_URL=postgres://user:password@host:5432/dbnameStep 2: Define the products table
Match the column names to the starter's Product type, so the table and forms keep working as is:
// src/db/schema.ts
import { numeric, pgTable, serial, text, timestamp } from 'drizzle-orm/pg-core';
export const products = pgTable('products', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
description: text('description').notNull(),
category: text('category').notNull(),
price: numeric('price', { precision: 10, scale: 2, mode: 'number' }).notNull(),
photo_url: text('photo_url').notNull().default(''),
created_at: timestamp('created_at', { mode: 'string' }).notNull().defaultNow(),
updated_at: timestamp('updated_at', { mode: 'string' }).notNull().defaultNow()
});Two details that save you a debugging session:
mode: 'number'onnumeric. Postgres returnsnumericas a string by default, to avoid losing precision. Without this option,pricecomes back as"438.45"and anything formatting it as a number breaks.mode: 'string'on timestamps. The starter'sProducttype uses strings for dates, so this keeps the types identical.
Step 3: Create the database client
// src/db/index.ts
import { drizzle } from 'drizzle-orm/node-postgres';
import * as schema from './schema';
export const db = drizzle(process.env.DATABASE_URL!, { schema });Only import db from server code: service.ts, route handlers and Server Components. Never from a client component.
Step 4: Push the schema and seed some data
// drizzle.config.ts (project root)
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
schema: './src/db/schema.ts',
out: './drizzle',
dialect: 'postgresql',
dbCredentials: { url: process.env.DATABASE_URL! }
});bunx drizzle-kit pushpush is the fastest way to start. Once you have real users, switch to drizzle-kit generate and drizzle-kit migrate so every schema change is a reviewed migration file.
The starter already includes Faker for its mock data, so seeding takes a few lines:
// src/db/seed.ts
import { faker } from '@faker-js/faker';
import { drizzle } from 'drizzle-orm/node-postgres';
import { products } from './schema';
const db = drizzle(process.env.DATABASE_URL!);
const categories = ['Electronics', 'Furniture', 'Clothing', 'Toys', 'Groceries', 'Books'];
await db.insert(products).values(
Array.from({ length: 50 }, (_, i) => ({
name: faker.commerce.productName(),
description: faker.commerce.productDescription(),
category: faker.helpers.arrayElement(categories),
price: Number(faker.commerce.price({ min: 5, max: 500 })),
photo_url: `https://api.slingacademy.com/public/sample-products/${(i % 30) + 1}.png`
}))
);
console.log('Seeded 50 products');
process.exit(0);bun run src/db/seed.tsBun loads .env.local automatically. With Node, pass the variable yourself or use --env-file=.env.local.
Step 5: Replace the mock service with Drizzle queries
This is the main step. Replace the contents of src/features/products/api/service.ts:
// src/features/products/api/service.ts
'use server';
import { auth } from '@clerk/nextjs/server';
import { and, asc, count, desc, eq, ilike, inArray, or, type SQL } from 'drizzle-orm';
import { db } from '@/db';
import { products } from '@/db/schema';
import type {
ProductByIdResponse,
ProductFilters,
ProductMutationPayload,
ProductsResponse
} from './types';
// Server actions are public endpoints: check auth in every one.
async function requireUser() {
const { userId } = await auth();
if (!userId) throw new Error('Unauthorized');
}
// Only these columns can be sorted from the URL.
const sortableColumns = {
name: products.name,
price: products.price,
category: products.category,
created_at: products.created_at
};
function getOrderBy(sort?: string) {
try {
const [first] = JSON.parse(sort ?? '[]') as { id: string; desc: boolean }[];
const column = first && sortableColumns[first.id as keyof typeof sortableColumns];
if (column) return first.desc ? desc(column) : asc(column);
} catch {
// Invalid sort param: fall back to newest first
}
return desc(products.created_at);
}
export async function getProducts({
page = 1,
limit = 10,
categories,
search,
sort
}: ProductFilters): Promise<ProductsResponse> {
await requireUser();
const conditions: SQL[] = [];
if (categories) {
conditions.push(inArray(products.category, categories.split(/[.,]/)));
}
if (search) {
const pattern = `%${search}%`;
conditions.push(or(ilike(products.name, pattern), ilike(products.description, pattern))!);
}
const where = conditions.length > 0 ? and(...conditions) : undefined;
const offset = (page - 1) * limit;
const [rows, [{ total }]] = await Promise.all([
db.select().from(products).where(where).orderBy(getOrderBy(sort)).limit(limit).offset(offset),
db.select({ total: count() }).from(products).where(where)
]);
return {
success: true,
time: new Date().toISOString(),
message: 'Products loaded',
total_products: total,
offset,
limit,
products: rows
};
}
export async function getProductById(id: number): Promise<ProductByIdResponse> {
await requireUser();
const [product] = await db.select().from(products).where(eq(products.id, id)).limit(1);
// The detail page calls notFound() when success is false.
if (!product) {
return { success: false, message: `Product ${id} not found` } as ProductByIdResponse;
}
return { success: true, time: new Date().toISOString(), message: 'Product found', product };
}
export async function createProduct(data: ProductMutationPayload) {
await requireUser();
const [product] = await db.insert(products).values(data).returning();
return { success: true, message: 'Product created', product };
}
export async function updateProduct(id: number, data: ProductMutationPayload) {
await requireUser();
const [product] = await db
.update(products)
.set({ ...data, updated_at: new Date().toISOString() })
.where(eq(products.id, id))
.returning();
if (!product) return { success: false, message: `Product ${id} not found` };
return { success: true, message: 'Product updated', product };
}
export async function deleteProduct(id: number) {
await requireUser();
const deleted = await db
.delete(products)
.where(eq(products.id, id))
.returning({ id: products.id });
if (deleted.length === 0) return { success: false, message: `Product ${id} not found` };
return { success: true, message: 'Product deleted' };
}What's happening here:
'use server'turns every export into a server action. The Server Component prefetch calls these functions directly, and the client'suseSuspenseQueryrefetches and mutations call them over the network, with no API routes to write.requireUser()in every function. A server action is a public HTTP endpoint, even if only your UI calls it. Page-levelauth.protect()doesn't cover it, so each action checks auth itself.- The filters come from the URL. The table syncs search, filters, sorting and pagination to the URL with nuqs, and the starter passes them straight into
getProducts. Search usesilike, the category filter usesinArray, and pagination useslimitandoffset. - The sort whitelist matters. The sort value arrives from the URL, so only columns listed in
sortableColumnscan be sorted on. - The response shape stays the same (
success,total_products,productsand so on), which is why the table, pagination and detail page need no edits.
Step 6: Run it
bun run devOpen /dashboard/product. Search, filter by category, sort a column and change pages, and every one of those is now a SQL query. Create, edit and delete a product, and the list refreshes on its own, because the starter's mutations already invalidate the products query key.
When everything works, you can delete the fakeProducts object for products from src/constants/mock-api.ts, and point Product in types.ts at typeof products.$inferSelect so the type comes from your schema.
Prefer route handlers or an external API?
The comment at the top of service.ts lists four patterns, and server actions are just the first:
- Server actions + ORM (this guide)
- Route handlers + ORM: keep
service.tscallingapiClient('/products?...')and put the Drizzle queries insrc/app/api/products/route.ts, which already checks auth - Backend for frontend: route handlers proxy to a Laravel, Go or Django API, keeping tokens on the server
- Direct external API:
fetch()your API fromservice.ts, with no Next.js backend at all
Route handlers are a good choice if a mobile app or a third party will call the same endpoints. For how each pattern works, including auth and server rendering, read Next.js Shadcn Dashboard Data Fetching: Server Actions vs Route Handlers vs BFF.
Using the TanStack Start edition?
The TanStack Start edition has the same service.ts, but each export is already a server function with a Zod validator and authMiddleware. So you only swap the handler bodies. Keep the database client in a *.server.ts file so it never reaches the browser:
// src/db/index.server.ts
import { drizzle } from 'drizzle-orm/node-postgres';
import * as schema from './schema';
export const db = drizzle(process.env.DATABASE_URL!, { schema });// src/features/products/api/service.ts (TanStack Start)
export const getProductById = createServerFn({ method: 'GET' })
.middleware([authMiddleware])
.validator(z.number().int())
.handler(async ({ data: id }) => {
const [product] = await db.select().from(products).where(eq(products.id, id)).limit(1);
if (!product) throw notFound();
return { success: true, time: new Date().toISOString(), message: 'Product found', product };
});The schema from Step 2 works as is. Move the filter, sort and pagination code from Step 5 into the getProducts handler, and drop requireUser(), since authMiddleware already does that job. For a side-by-side look at the two editions, read Next.js vs TanStack Start for admin dashboards.
FAQ
How do I connect a database to a Next.js admin dashboard?
Install an ORM like Drizzle or Prisma, define your tables, and call the database from server-only code: server actions, route handlers or Server Components. In Shadcn Dashboard by Kiranism, you replace the mock functions in each feature's service.ts, and the tables and forms keep working.
Drizzle or Prisma for a Next.js dashboard?
Both work with this starter, because only service.ts changes. Drizzle is closer to SQL, has no generate step for the client and is light enough for serverless. Prisma has a more abstract query API and a mature migration workflow. If you like writing SQL, pick Drizzle.
Why does Postgres return my price as a string?
Postgres numeric values can be more precise than a JavaScript number, so drivers return them as strings. In Drizzle, set mode: 'number' on the column, as in this guide, or store money as integer cents.
Do I need to check auth inside every server action?
Yes. Server actions are exposed as HTTP endpoints, so anyone can call them, whether or not your UI shows the button. Protecting the page doesn't protect the action. Check the session at the start of each one.
Does this work with Neon or Supabase?
Yes. Both are Postgres, so use their connection string as DATABASE_URL. For Neon on serverless, you can switch to its HTTP driver (drizzle-orm/neon-http) without changing any queries.
How do I do server-side pagination with TanStack Table and Drizzle?
Read the page number and page size from the URL, then use .limit(pageSize).offset((page - 1) * pageSize) and run a separate count() query with the same where clause for the total. Return both, and let TanStack Table render the page count from the total.
Wrapping up
Mock data gets a dashboard on screen. A clean data layer means swapping it for Postgres takes one file per feature, not a rewrite. If this helped, a star on Shadcn Dashboard by Kiranism helps more people find it, and issues with your setup are welcome.
Choosing a starter first? Read Best Free Next.js SaaS Starter Kits.