Updated
Build a TanStack and Drizzle app with Postgres Database
Build a TanStack Start app with Drizzle ORM. Define a schema, run migrations, and query data from server functions, using Supabase as your Postgres database.
This tutorial shows how to build a to-do app with TanStack Start, Drizzle ORM, and a Postgres database. TanStack Start is a full-stack React framework, and Drizzle is a TypeScript ORM for SQL databases. You define your schema in TypeScript, migrate it with Drizzle Kit, and query it from server functions.
Drizzle needs a Postgres database, and Supabase is an excellent place to host one. Every Supabase project is a full Postgres database, so Drizzle works with it through a standard driver and a connection string. You develop against a local Postgres database that runs on your machine.
If you want to use more features of Supabase together with Drizzle (such as the REST or GraphQL Data APIs), see Connecting with Drizzle.
Prerequisites
- Node.js 22 or later
- pnpm and psql installed
- A container runtime on your machine.
Set up the project
Create the app, install Drizzle, and start a local Postgres database.
Create the app
-
Create a TanStack Start app and move into its directory:
pnpm dlx @tanstack/cli@latest create my-app --package-manager pnpm --yes --no-intentcd my-appThe
--yesflag accepts the default options instead of prompting for them. The--no-intentflag skips TanStack’s optional setup for AI coding agents. -
Install Drizzle ORM, the
postgresdriver, anddotenv:pnpm add drizzle-orm postgres dotenv -
Install Drizzle Kit, which generates and runs migrations:
pnpm add -D drizzle-kit
Start Postgres locally
Drizzle only needs a Postgres connection string, so any local Postgres works. This guide uses the Supabase CLI as a convenient way to run one. It starts Postgres in a container without any Docker configuration on your part, with the same Postgres version that hosted Supabase projects run. You use the CLI only to start and stop the database. Drizzle handles your schema, migrations, and queries.
Install the CLI as a development dependency, then create its configuration file:
pnpm add -D supabasepnpm supabase initTurn off the Data API
Supabase projects expose the public schema through an HTTP API, called the Data API. This app reads and writes data through Drizzle only, so turn the Data API off. Then your tables are reachable only through your database connection.
-
In
supabase/config.toml, setenabledtofalsein the[api]section:[api]enabled = false -
Start your container runtime.
-
Start the local database. The CLI prints its connection details when it’s ready:
pnpm supabase startThe local database URL is:
postgresql://postgres:postgres@127.0.0.1:54322/postgres
Set the database URL
In your project root, create a .env file with the local database URL:
DATABASE_URL=postgresql://postgres:postgres@127.0.0.1:54322/postgresDefine and migrate your schema
Drizzle describes your tables in TypeScript. Drizzle Kit compares that schema with your previous migrations and writes the difference as SQL.
Define a table
Create src/db/schema.ts:
import { bigint, boolean, pgTable, text, timestamp } from 'drizzle-orm/pg-core'export const todos = pgTable('todos', { id: bigint('id', { mode: 'number' }).primaryKey().generatedAlwaysAsIdentity(), title: text('title').notNull(), isComplete: boolean('is_complete').notNull().default(false), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),})The table uses an identity column for its primary key and timestamptz for timestamps, which are the recommended Postgres defaults.
Configure Drizzle Kit
Create drizzle.config.ts in your project root:
import 'dotenv/config'import { defineConfig } from 'drizzle-kit'export default defineConfig({ dialect: 'postgresql', schema: './src/db/schema.ts', out: './drizzle', dbCredentials: { url: process.env.DATABASE_URL!, },})Generate and apply the migration
-
Generate a migration from your schema, then apply it to your local database:
pnpm drizzle-kit generate --name create_todospnpm drizzle-kit migrateDrizzle Kit writes the SQL migration to the
drizzle/directory. It records applied migrations in thedrizzle.__drizzle_migrationstable. -
Confirm that the table exists. Use any Postgres client, such as
psql:psql 'postgresql://postgres:postgres@127.0.0.1:54322/postgres' -c 'select count(*) from public.todos' -
Commit the
drizzle/directory.
Query data from server functions
Connect Drizzle to the database, then expose queries to your pages through TanStack Start server functions. Server functions run only on the server, so your database credentials never reach the browser.
Connect to the database
Create src/db/index.ts:
import 'dotenv/config'import { drizzle } from 'drizzle-orm/postgres-js'import postgres from 'postgres'const databaseUrl = process.env.DATABASE_URLif (!databaseUrl) throw new Error('DATABASE_URL is not set')const client = postgres(databaseUrl)export const db = drizzle(client)If you later connect through a transaction-mode connection pooler, such as the Supabase shared pooler, pass { prepare: false } as the second argument to postgres(). For details, see Connect to your database.
Create the server functions
Create src/lib/todos.functions.ts with functions to list, add, toggle, and delete to-dos:
import { createServerFn } from '@tanstack/react-start'import { desc, eq, not } from 'drizzle-orm'import { db } from '@/db'import { todos } from '@/db/schema'export const getTodos = createServerFn({ method: 'GET' }).handler(async () => { return db.select().from(todos).orderBy(desc(todos.createdAt))})export const addTodo = createServerFn({ method: 'POST' }) .validator((data: { title: string }) => data) .handler(async ({ data }) => { await db.insert(todos).values({ title: data.title }) })export const toggleTodo = createServerFn({ method: 'POST' }) .validator((data: { id: number }) => data) .handler(async ({ data }) => { await db .update(todos) .set({ isComplete: not(todos.isComplete) }) .where(eq(todos.id, data.id)) })export const deleteTodo = createServerFn({ method: 'POST' }) .validator((data: { id: number }) => data) .handler(async ({ data }) => { await db.delete(todos).where(eq(todos.id, data.id)) })Drizzle’s query builder maps to SQL, and the todos table gives each query typed columns and results.
Build the page
Replace src/routes/index.tsx with a page that loads the to-dos on the server and calls the other functions from the browser. It uses Tailwind CSS classes, which the TanStack Start starter includes:
import { createFileRoute, useRouter } from '@tanstack/react-router'import { useState } from 'react'import { addTodo, deleteTodo, getTodos, toggleTodo } from '@/lib/todos.functions'export const Route = createFileRoute('/')({ loader: () => getTodos(), component: Home,})function Home() { const todos = Route.useLoaderData() const router = useRouter() const [title, setTitle] = useState('') async function handleAdd(e: React.FormEvent) { e.preventDefault() if (!title.trim()) return await addTodo({ data: { title } }) setTitle('') router.invalidate() } return ( <main className="mx-auto my-16 max-w-sm rounded-lg border border-neutral-200 bg-white p-6 text-neutral-900 shadow-sm"> <h1 className="mb-4 text-lg font-semibold">To-dos</h1> <form onSubmit={handleAdd} className="mb-4 flex gap-2"> <input className="min-w-0 flex-1 rounded-md border border-neutral-300 px-3 py-2 text-sm" placeholder="What needs doing?" value={title} onChange={(e) => setTitle(e.target.value)} /> <button className="shrink-0 rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white hover:bg-neutral-700"> Add </button> </form> <ul className="flex flex-col gap-2"> {todos.map((todo) => ( <li key={todo.id} className="flex items-center gap-2 text-sm"> <input type="checkbox" checked={todo.isComplete} onChange={async () => { await toggleTodo({ data: { id: todo.id } }) router.invalidate() }} /> <span className={todo.isComplete ? 'flex-1 text-neutral-400 line-through' : 'flex-1'}> {todo.title} </span> <button className="text-neutral-500 hover:text-red-600" onClick={async () => { await deleteTodo({ data: { id: todo.id } }) router.invalidate() }} > Delete </button> </li> ))} </ul> </main> )}Test the app locally
-
Start the dev server:
pnpm dev -
Open your app at
http://localhost:3000. Add a to-do, mark it complete, and delete it.
Update the schema
When your data model changes, generate a new migration and apply it.
-
In
src/db/schema.ts, change the schema. For example, add a column totodos:dueDate: timestamp('due_date', { withTimezone: true }), -
Generate and apply the migration locally:
pnpm drizzle-kit generate --name add_due_datepnpm drizzle-kit migrate -
Commit the new migration.
The drizzle-kit push command applies schema changes directly and doesn’t create migration files. Use it for prototyping against a local database, and use generate and migrate to keep a record of your changes.
To generate a Drizzle schema from tables that already exist in your database, run pnpm drizzle-kit pull.
Resources
- Drizzle ORM with PostgreSQL
- Drizzle Kit migrations
- TanStack Start server functions
- Drizzle quickstart
- Connect to your database
- Supabase CLI configuration