Use PostgreSQL with TanStack Start

Connect TanStack Start to PostgreSQL with Drizzle, keep the database client on the server, and verify a saved record.

By Antoine RossPublished

You can save application data in PostgreSQL from a TanStack Start server function without giving the browser your database credentials. This guide creates a small notes table, inserts a row, and reads it back. The example uses a Node server and a disposable development database; it does not add user accounts or access control.

Before you start

You need an existing TypeScript TanStack Start app, a PostgreSQL database you can change, and a server-side DATABASE_URL for that database. Back up an existing database and review migrations before applying them. Install the packages with your project's package manager:

bun add drizzle-orm postgres
bun add -d drizzle-kit

TanStack Start does not include a database client, so you need one. This guide uses Drizzle ORM with postgres.js because together they give typed queries and generated SQL migrations while keeping the SQL visible; any PostgreSQL client that runs on the server works with the same server-function boundary. Drizzle's PostgreSQL guide covers the driver and migration options. This example uses postgres-js; a serverless or edge host may require a different connection strategy.

Define and create the table

Create :

import { pgTable, serial, text } from 'drizzle-orm/pg-core'

export const notes = pgTable('notes', {
  id: serial('id').primaryKey(),
  body: text('body').notNull(),
})

Create at the project root:

import { defineConfig } from 'drizzle-kit'

if (!process.env.DATABASE_URL) throw new Error('DATABASE_URL is required')

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

Set DATABASE_URL in the environment used by both the migration commands and the app server. Keep its value out of source control, browser-exposed variables, logs, and screenshots. Then create and apply the migration to the development database:

bunx drizzle-kit generate
bunx drizzle-kit migrate

Inspect the generated SQL before applying it to a shared database. Drizzle's migration guide explains how migration files track schema changes.

Connect only on the server

Create :

import '@tanstack/react-start/server-only'
import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
import * as schema from './schema'

const url = process.env.DATABASE_URL
if (!url) throw new Error('DATABASE_URL is required')

const sql = postgres(url, { max: 5, prepare: false })
export const db = drizzle(sql, { schema })

The server-only marker prevents this module from being imported into browser code. A module-level pool can be reused by a long-lived Node process, but its connection limit is per process. Multiple instances can exhaust a database's limit. For other deployment runtimes, follow the host's pooling and connection-lifecycle guidance rather than copying this pool unchanged. See TanStack Start's server-only modules.

Protect server-function mutations

The insert is a server-function mutation. Configure the CSRF middleware and APP_ORIGIN as shown in Protect server-function mutations before exposing this example. The middleware checks Fetch Metadata first and uses the configured origin as a fallback when that header is absent. It does not authenticate users or authorize access to notes.

Write and read a note

Create :

import { createFileRoute } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
import { useState } from 'react'

const listNotes = createServerFn({ method: 'GET' }).handler(async () => {
  const { db } = await import('../db/client')
  const { notes } = await import('../db/schema')
  return db.select().from(notes).orderBy(notes.id)
})

const addNote = createServerFn({ method: 'POST' })
  .validator((value: unknown) => {
    if (typeof value !== 'string' || !value.trim() || value.trim().length > 200) {
      throw new Error('Enter a note of 1 to 200 characters')
    }
    return value.trim()
  })
  .handler(async ({ data }) => {
    const { db } = await import('../db/client')
    const { notes } = await import('../db/schema')
    await db.insert(notes).values({ body: data })
  })

export const Route = createFileRoute('/notes')({ component: NotesPage })

function NotesPage() {
  const [body, setBody] = useState('')
  const [rows, setRows] = useState<Array<{ id: number; body: string }>>([])
  const [error, setError] = useState('')

  async function refresh() {
    setRows(await listNotes())
  }

  return (
    <main>
      <h1>Notes</h1>
      <form onSubmit={async (event) => {
        event.preventDefault()
        setError('')
        try {
          await addNote({ data: body })
          setBody('')
          await refresh()
        } catch {
          setError('Could not save the note. Check its length and try again.')
        }
      }}>
        <label>Note <input value={body} onChange={(event) => setBody(event.target.value)} /></label>
        <button type="submit">Save</button>
      </form>
      <button type="button" onClick={() => void refresh()}>Load notes</button>
      {error && <p role="alert">{error}</p>}
      <ul>{rows.map((row) => <li key={row.id}>{row.body}</li>)}</ul>
    </main>
  )
}

Start your app, visit /notes, save a short note, and select Load notes after a reload. The note should appear again. A blank or overlong note should not be saved. A successful render alone does not prove persistence; the reload and read check do.

This deliberately public demonstration lets any visitor read and write notes. Before using real data, authenticate each request, check the actor's permission in the server operation, enable the appropriate CSRF protection, and restrict database credentials. See TanStack Start server functions for their request boundary. If the table is missing, check that migrations ran against the same database the server uses; do not print the connection string to diagnose it.

The CoreMVP TanStack Start premium template already separates its server-only Drizzle connection, repositories, and application services. Projects are scoped to an organization and checked on the server. You still own your database, credentials, and migrations. See project structure for the product-specific paths.