From d1f059287d53bed23aef3532a0a81a1724e5666c Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Fri, 11 Sep 2026 15:37:46 -0600 Subject: [PATCH 1/3] docs(start): add tested PostgreSQL and Prisma recipe --- docs/start/framework/react/guide/databases.md | 105 ++++++-- examples/react/start-postgres/.env.example | 1 + examples/react/start-postgres/.gitignore | 9 + examples/react/start-postgres/README.md | 66 +++++ examples/react/start-postgres/compose.yaml | 18 ++ examples/react/start-postgres/package.json | 35 +++ .../react/start-postgres/playwright.config.ts | 12 + .../react/start-postgres/prisma.config.ts | 7 + .../20260911000000_notes/migration.sql | 11 + .../prisma/migrations/migration_lock.toml | 1 + .../react/start-postgres/prisma/schema.prisma | 20 ++ .../react/start-postgres/src/routeTree.gen.ts | 68 +++++ examples/react/start-postgres/src/router.tsx | 5 + .../start-postgres/src/routes/__root.tsx | 29 +++ .../react/start-postgres/src/routes/index.tsx | 89 +++++++ .../start-postgres/src/server/db.server.ts | 10 + .../react/start-postgres/src/server/notes.ts | 54 ++++ .../react/start-postgres/tests/notes.spec.ts | 91 +++++++ examples/react/start-postgres/tsconfig.json | 21 ++ examples/react/start-postgres/vite.config.ts | 8 + pnpm-lock.yaml | 243 ++++++++++++++++++ 21 files changed, 882 insertions(+), 21 deletions(-) create mode 100644 examples/react/start-postgres/.env.example create mode 100644 examples/react/start-postgres/.gitignore create mode 100644 examples/react/start-postgres/README.md create mode 100644 examples/react/start-postgres/compose.yaml create mode 100644 examples/react/start-postgres/package.json create mode 100644 examples/react/start-postgres/playwright.config.ts create mode 100644 examples/react/start-postgres/prisma.config.ts create mode 100644 examples/react/start-postgres/prisma/migrations/20260911000000_notes/migration.sql create mode 100644 examples/react/start-postgres/prisma/migrations/migration_lock.toml create mode 100644 examples/react/start-postgres/prisma/schema.prisma create mode 100644 examples/react/start-postgres/src/routeTree.gen.ts create mode 100644 examples/react/start-postgres/src/router.tsx create mode 100644 examples/react/start-postgres/src/routes/__root.tsx create mode 100644 examples/react/start-postgres/src/routes/index.tsx create mode 100644 examples/react/start-postgres/src/server/db.server.ts create mode 100644 examples/react/start-postgres/src/server/notes.ts create mode 100644 examples/react/start-postgres/tests/notes.spec.ts create mode 100644 examples/react/start-postgres/tsconfig.json create mode 100644 examples/react/start-postgres/vite.config.ts diff --git a/docs/start/framework/react/guide/databases.md b/docs/start/framework/react/guide/databases.md index 774a9df61b..6fff306975 100644 --- a/docs/start/framework/react/guide/databases.md +++ b/docs/start/framework/react/guide/databases.md @@ -1,7 +1,7 @@ --- id: databases title: Databases -description: Connect a database to TanStack Start through server functions and server routes, and compare supported database providers. +description: Build a TanStack Start app with PostgreSQL and Prisma, including migrations, server-only queries, validated mutations, transaction rollback, and deployment. --- Databases are at the core of any dynamic application, providing the necessary infrastructure to store, retrieve, and manage data. TanStack Start makes it easy to integrate with a variety of databases, offering a flexible approach to managing your application's data layer. @@ -10,31 +10,94 @@ Databases are at the core of any dynamic application, providing the necessary in TanStack Start is **designed to work with any database provider**, so if you already have a preferred database system, you can integrate it with TanStack Start using the provided full-stack APIs. Whether you're working with SQL, NoSQL, or other types of databases, TanStack Start can handle your needs. -## How simple is it to use a database with TanStack Start? +## Build a PostgreSQL app with Prisma -Using a database with TanStack Start is as simple as calling into your database's adapter/client/driver/service from a TanStack Start server function or server route. +The [PostgreSQL example](../examples/start-postgres) is a runnable shared notebook using Prisma 7. It includes a schema, committed migrations, loader reads, validated server functions, transaction rollback, and browser tests. It has no user accounts, so anyone with access can write to it. Add [endpoint authorization](./authentication-server-primitives#protect-data-first) before using the pattern for private data. -Here's an abstract example of how you might connect with a database and read/write to it: +### Create and migrate a local database -```tsx -import { createServerFn } from '@tanstack/react-start' +After installing the repository dependencies and building its framework packages as described in [Contributing](https://github.com/TanStack/router/blob/main/CONTRIBUTING.md), run: -const db = createMyDatabaseClient() - -export const getUser = createServerFn().handler(async ({ context }) => { - const user = await db.getUser(context.userId) - return user -}) - -export const createUser = createServerFn({ method: 'POST' }).handler( - async ({ data }) => { - const user = await db.createUser(data) - return user - }, -) +```sh +cd examples/react/start-postgres +cp .env.example .env +docker compose up -d --wait +pnpm db:generate +pnpm db:migrate +pnpm dev ``` -This is obviously contrived, but it demonstrates that you can use literally any database provider with TanStack Start as long as you can call into it from a server function or server route. +With Docker Compose v2 installed, the example's Compose file starts PostgreSQL 17 on localhost:5433. Its `.env.example` contains local demo credentials. Keep your own `.env` out of Git, and change the port and connection URL together if the port is occupied. The example README also includes native PostgreSQL initialization commands. An existing local PostgreSQL server works with a dedicated database and a matching `DATABASE_URL`. + +The schema relates each note to a category: + +```prisma +model Category { + name String @id + notes Note[] +} + +model Note { + slug String @id + title String + categoryName String + category Category @relation(fields: [categoryName], references: [name]) +} +``` + +`pnpm db:migrate` runs `prisma migrate deploy` to apply committed SQL. For subsequent schema changes, run `pnpm db:dev --name your_change` against a development database, then regenerate the client with `pnpm db:generate`. Review and commit the generated migration SQL. Do not use development reset commands against production data. + +### Keep the database on the server + +The example's `src/server/db.server.ts` creates one Prisma client per server module instance, backed by the PostgreSQL driver adapter. It reads `DATABASE_URL` only on the server and declares a server-only import boundary: + +```ts +import '@tanstack/react-start/server-only' +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from '../generated/prisma/client' + +const connectionString = process.env.DATABASE_URL +if (!connectionString) { + throw new Error('Set DATABASE_URL before starting the server') +} + +export const db = new PrismaClient({ + adapter: new PrismaPg({ connectionString, max: 5 }), +}) +``` + +A connection pool can be shared by requests. Account-specific query results must not be shared without appropriate isolation. Five connections is this example's setting, not a universal recommendation; budget connections across every application instance. + +Route loaders can run in the browser after navigation. Call a server function from the loader, then perform the database query inside that function. The example selects only `slug`, `title`, and `categoryName`, so it does not serialize the client or connection configuration. See [Import Protection](./import-protection) and [Server Functions](./server-functions). + +### Validate and write atomically + +The POST server function validates the slug format and bounds the title and category lengths before entering a transaction. Browser input attributes are only interface feedback; the server validates again. + +Inside the transaction, it upserts a category and creates a note. If the unique note slug already exists, PostgreSQL rejects the insert and Prisma rolls back both operations. A newly created category does not remain behind. The handler catches Prisma's `P2002` unique-constraint error and returns a specific message. Unexpected errors reach the generic error interface instead of exposing database details. + +After a successful write, the component awaits `router.invalidate()` to reload its Router-owned data. It keeps the form pending through the write and reload, and disables its JavaScript-dependent form until hydration. If Query owns your data instead, invalidate the relevant Query keys. + +See the example's [server functions](https://github.com/TanStack/router/blob/main/examples/react/start-postgres/src/server/notes.ts) and [form route](https://github.com/TanStack/router/blob/main/examples/react/start-postgres/src/routes/index.tsx) for the complete implementation. Keep transactions short; do not hold one open while waiting for external APIs. + +### Test the production build + +```sh +pnpm exec playwright install chromium +pnpm test:e2e +pnpm build +POSTGRES_EXAMPLE_PRODUCTION=1 pnpm test:e2e +``` + +The tests use a dedicated database, create unique records, and clean up only those records. They verify initial HTML contains persisted notes, data survives reload, whitespace-only titles fail server validation, and duplicate-note failure rolls back its new category. + +Also build with a harmless test credential and search client assets and any published source maps for it. Inspect response bodies too. A successful connection does not prove the credentials stayed on the server. + +### Deploy with an explicit migration step + +This example targets a Node-compatible host using Nitro and Prisma's `pg` adapter. Set `DATABASE_URL` in the production server environment; do not assume `.env` is loaded by the Node entry point. Generate the Prisma client at build time. Apply committed migrations once as a release step, not during requests or independently on every instance startup. + +For a hosted database, follow its TLS and pooling instructions. A transaction pooler may require a separate direct migration connection. Other runtimes may require a different adapter. Retain backups and plan schema compatibility before deploying changes, because rolling back application code does not roll back the database. See [Hosting](./hosting), [Environment Variables](./environment-variables), and [Prisma's PostgreSQL connector](https://www.prisma.io/docs/orm/v7/core-concepts/supported-databases/postgresql). ## Recommended Database Providers @@ -106,4 +169,4 @@ Instant Postgres, Zero Setup: Get a production-ready Postgres database in second ## Documentation & APIs -Documentation for integrating different databases with TanStack Start is coming soon! In the meantime, keep an eye on our examples and guide to learn how to fully leverage your data layer across your TanStack Start application. +Use the runnable PostgreSQL example above for the complete setup-to-mutation workflow. The same server boundary applies to other providers: keep credentials and privileged queries in server functions or server routes, validate inputs, and authorize private operations at their endpoint. diff --git a/examples/react/start-postgres/.env.example b/examples/react/start-postgres/.env.example new file mode 100644 index 0000000000..2130ccb7c6 --- /dev/null +++ b/examples/react/start-postgres/.env.example @@ -0,0 +1 @@ +DATABASE_URL="postgresql://start_demo:start_demo@localhost:5433/start_demo" diff --git a/examples/react/start-postgres/.gitignore b/examples/react/start-postgres/.gitignore new file mode 100644 index 0000000000..02d6049242 --- /dev/null +++ b/examples/react/start-postgres/.gitignore @@ -0,0 +1,9 @@ +node_modules +.env +.output +.tanstack +src/generated/ +test-results/ +playwright-report/ +.postgres/ +.postgres-password diff --git a/examples/react/start-postgres/README.md b/examples/react/start-postgres/README.md new file mode 100644 index 0000000000..8b134d2776 --- /dev/null +++ b/examples/react/start-postgres/README.md @@ -0,0 +1,66 @@ +# TanStack Start + PostgreSQL + +A shared notebook using Prisma 7 and PostgreSQL. It demonstrates migrations, server-only database access, loader reads, server validation, and a transaction that rolls back a category when its note cannot be created. + +This example has no user accounts. Anyone with access can create notes. Add endpoint authorization and your application's abuse controls before making it public. + +## Run locally + +With Docker Compose v2 available, install repository dependencies and build the framework packages as described in [Contributing](https://github.com/TanStack/router/blob/main/CONTRIBUTING.md), then run from this directory: + +```sh +cp .env.example .env +docker compose up -d --wait +pnpm db:generate +pnpm db:migrate +pnpm dev +``` + +Open http://localhost:3120. The Compose service listens only on localhost:5433 and stores its database in a named volume. If that port is in use, change the port mapping and `.env` together. You can instead use an existing local PostgreSQL server with a dedicated database and update `DATABASE_URL`. + +`db:migrate` applies the committed migrations to an empty database. After changing `prisma/schema.prisma`, run `pnpm db:dev --name your_change` to generate and apply a development migration, then `pnpm db:generate`. Commit the schema and migration SQL, not generated client files or `.env`. + +Stop the local database with `docker compose down`. Its named volume remains available for the next run. + +### Native PostgreSQL alternative + +If PostgreSQL tools are installed locally, initialize a separate development cluster instead of starting Compose. These commands use the same `.env.example` connection settings and must run only once for a new cluster: + +```sh +printf '%s\n' 'start_demo' > .postgres-password +initdb -D .postgres -U start_demo --auth-local=trust --auth-host=scram-sha-256 --pwfile=.postgres-password +pg_ctl -D .postgres -l .postgres/server.log -o '-p 5433 -h 127.0.0.1' start +PGPASSWORD=start_demo createdb -h 127.0.0.1 -p 5433 -U start_demo start_demo +``` + +Then run the same generation, migration, and application commands above. Stop this cluster with `pg_ctl -D .postgres stop`. Use separate credentials and a managed lifecycle for production; these are local demo settings. + +## What happens on a write + +1. The POST server function validates the slug, title and category. +2. A Prisma transaction upserts the category and inserts the note. +3. A duplicate slug rolls back the whole transaction, including a newly created category. The interface receives a specific duplicate-slug message. +4. After success, Router invalidation reloads the list from PostgreSQL. + +The server-only module owns the Prisma client and a bounded connection pool. The loader calls a server function instead of importing the database into browser code. The response only includes the selected note fields. Unexpected database failures use a generic UI error rather than exposing database details. + +## Verify + +Use a dedicated test database. Tests create unique records and remove only those records afterward. + +```sh +pnpm exec playwright install chromium +pnpm test:e2e +pnpm build +POSTGRES_EXAMPLE_PRODUCTION=1 pnpm test:e2e +``` + +The tests check persisted SSR data, reloads, server validation and database rollback. For a manual production start, export `DATABASE_URL` in the server environment and run `PORT=3120 pnpm start`. Do not assume a production Node process will load `.env`; the Prisma CLI, Vite development server, and Playwright configuration load it for their own processes. + +## Deploy + +Use a Node-compatible host for this `pg` adapter and Nitro build. Generate the Prisma client during the build. Apply `prisma migrate deploy` once as a release step before starting compatible application instances, rather than running migrations in each request. Use a separate migration connection if your provider's pooler requires it. + +Set `DATABASE_URL` as a server secret. Never prefix it with `VITE_`, serialize it to a loader response, or commit it. Configure TLS using your provider's certificate guidance. Size the pool for the total number of processes and database connection limit. Edge runtimes may need a different supported adapter. + +Back up production data and plan compatibility between old and new application versions before schema changes. Rolling back application code does not undo a database migration. diff --git a/examples/react/start-postgres/compose.yaml b/examples/react/start-postgres/compose.yaml new file mode 100644 index 0000000000..06a11c79c8 --- /dev/null +++ b/examples/react/start-postgres/compose.yaml @@ -0,0 +1,18 @@ +services: + postgres: + image: postgres:17 + environment: + POSTGRES_USER: start_demo + POSTGRES_PASSWORD: start_demo + POSTGRES_DB: start_demo + ports: + - '127.0.0.1:5433:5432' + volumes: + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: ['CMD-SHELL', 'pg_isready -U start_demo -d start_demo'] + interval: 2s + timeout: 5s + retries: 15 +volumes: + postgres-data: diff --git a/examples/react/start-postgres/package.json b/examples/react/start-postgres/package.json new file mode 100644 index 0000000000..09060c3330 --- /dev/null +++ b/examples/react/start-postgres/package.json @@ -0,0 +1,35 @@ +{ + "name": "tanstack-start-example-postgres", + "private": true, + "type": "module", + "scripts": { + "dev": "vite dev --port 3120", + "build": "prisma generate && vite build && tsc --noEmit", + "start": "node .output/server/index.mjs", + "db:generate": "prisma generate", + "db:migrate": "prisma migrate deploy", + "db:dev": "prisma migrate dev", + "test:e2e": "playwright test" + }, + "dependencies": { + "@prisma/adapter-pg": "7.0.0", + "@prisma/client": "7.0.0", + "@tanstack/react-router": "workspace:^", + "@tanstack/react-start": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "zod": "^4.4.3" + }, + "devDependencies": { + "@types/node": "^22.5.4", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "nitro": "^3.0.260311-beta", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "prisma": "7.0.0", + "dotenv": "^17.2.3", + "@playwright/test": "^1.61.0" + } +} diff --git a/examples/react/start-postgres/playwright.config.ts b/examples/react/start-postgres/playwright.config.ts new file mode 100644 index 0000000000..262b7abab0 --- /dev/null +++ b/examples/react/start-postgres/playwright.config.ts @@ -0,0 +1,12 @@ +import 'dotenv/config' +import { defineConfig } from '@playwright/test' +const production = process.env.POSTGRES_EXAMPLE_PRODUCTION === '1' +export default defineConfig({ + testDir: './tests', + use: { browserName: 'chromium', baseURL: 'http://localhost:3120' }, + webServer: { + command: production ? 'PORT=3120 pnpm start' : 'pnpm dev', + url: 'http://localhost:3120', + timeout: 120_000, + }, +}) diff --git a/examples/react/start-postgres/prisma.config.ts b/examples/react/start-postgres/prisma.config.ts new file mode 100644 index 0000000000..0daa8973bf --- /dev/null +++ b/examples/react/start-postgres/prisma.config.ts @@ -0,0 +1,7 @@ +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' +export default defineConfig({ + schema: './prisma/schema.prisma', + migrations: { path: './prisma/migrations' }, + datasource: { url: env('DATABASE_URL') }, +}) diff --git a/examples/react/start-postgres/prisma/migrations/20260911000000_notes/migration.sql b/examples/react/start-postgres/prisma/migrations/20260911000000_notes/migration.sql new file mode 100644 index 0000000000..33e630350b --- /dev/null +++ b/examples/react/start-postgres/prisma/migrations/20260911000000_notes/migration.sql @@ -0,0 +1,11 @@ +CREATE TABLE "Category" ( + "name" TEXT NOT NULL, + CONSTRAINT "Category_pkey" PRIMARY KEY ("name") +); +CREATE TABLE "Note" ( + "slug" TEXT NOT NULL, + "title" TEXT NOT NULL, + "categoryName" TEXT NOT NULL, + CONSTRAINT "Note_pkey" PRIMARY KEY ("slug") +); +ALTER TABLE "Note" ADD CONSTRAINT "Note_categoryName_fkey" FOREIGN KEY ("categoryName") REFERENCES "Category"("name") ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/examples/react/start-postgres/prisma/migrations/migration_lock.toml b/examples/react/start-postgres/prisma/migrations/migration_lock.toml new file mode 100644 index 0000000000..2fe25d87cc --- /dev/null +++ b/examples/react/start-postgres/prisma/migrations/migration_lock.toml @@ -0,0 +1 @@ +provider = "postgresql" diff --git a/examples/react/start-postgres/prisma/schema.prisma b/examples/react/start-postgres/prisma/schema.prisma new file mode 100644 index 0000000000..6fb5305714 --- /dev/null +++ b/examples/react/start-postgres/prisma/schema.prisma @@ -0,0 +1,20 @@ +generator client { + provider = "prisma-client" + output = "../src/generated/prisma" +} + +datasource db { + provider = "postgresql" +} + +model Category { + name String @id + notes Note[] +} + +model Note { + slug String @id + title String + categoryName String + category Category @relation(fields: [categoryName], references: [name]) +} diff --git a/examples/react/start-postgres/src/routeTree.gen.ts b/examples/react/start-postgres/src/routeTree.gen.ts new file mode 100644 index 0000000000..dceedffdc1 --- /dev/null +++ b/examples/react/start-postgres/src/routeTree.gen.ts @@ -0,0 +1,68 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' + fileRoutesByTo: FileRoutesByTo + to: '/' + id: '__root__' | '/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/react-start' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/examples/react/start-postgres/src/router.tsx b/examples/react/start-postgres/src/router.tsx new file mode 100644 index 0000000000..bb899b1fdf --- /dev/null +++ b/examples/react/start-postgres/src/router.tsx @@ -0,0 +1,5 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +export function getRouter() { + return createRouter({ routeTree }) +} diff --git a/examples/react/start-postgres/src/routes/__root.tsx b/examples/react/start-postgres/src/routes/__root.tsx new file mode 100644 index 0000000000..f67f9b192a --- /dev/null +++ b/examples/react/start-postgres/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' +import type { ReactNode } from 'react' +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'Postgres notes | TanStack Start' }, + ], + }), + shellComponent: ({ children }: { children: ReactNode }) => ( + + + + + + {children} + + + + ), + errorComponent: () => ( +
+

Could not load notes

+

Try again after the database is available.

+ Reload +
+ ), +}) diff --git a/examples/react/start-postgres/src/routes/index.tsx b/examples/react/start-postgres/src/routes/index.tsx new file mode 100644 index 0000000000..353e44b5df --- /dev/null +++ b/examples/react/start-postgres/src/routes/index.tsx @@ -0,0 +1,89 @@ +import { createFileRoute, useHydrated, useRouter } from '@tanstack/react-router' +import { useServerFn } from '@tanstack/react-start' +import { useState } from 'react' +import { createNote, listNotes } from '../server/notes' +export const Route = createFileRoute('/')({ + loader: () => listNotes(), + headers: () => ({ 'Cache-Control': 'no-store' }), + component: Notes, +}) +function Notes() { + const notes = Route.useLoaderData() + const save = useServerFn(createNote) + const router = useRouter() + const hydrated = useHydrated() + const [pending, setPending] = useState(false) + const [error, setError] = useState('') + return ( +
+

Postgres notes

+

+ A shared local database example. Anyone who can access this app can + create notes. +

+
{ + event.preventDefault() + const form = event.currentTarget + const fields = new FormData(form) + setPending(true) + setError('') + try { + const result = await save({ + data: { + slug: String(fields.get('slug') ?? ''), + title: String(fields.get('title') ?? ''), + category: String(fields.get('category') ?? ''), + }, + }) + if (result.error) { + setError(result.error) + } else { + await router.invalidate() + form.reset() + } + } catch { + setError('Could not save. Check your input and try again.') + } finally { + setPending(false) + } + }} + > +
+ Create a note +

+ +

+

+ +

+

+ +

+ +
+ {error ?

{error}

: null} +
+
    + {notes.map((note) => ( +
  • + {note.title} ({note.categoryName}) +
  • + ))} +
+
+ ) +} diff --git a/examples/react/start-postgres/src/server/db.server.ts b/examples/react/start-postgres/src/server/db.server.ts new file mode 100644 index 0000000000..19959c5a2e --- /dev/null +++ b/examples/react/start-postgres/src/server/db.server.ts @@ -0,0 +1,10 @@ +import '@tanstack/react-start/server-only' +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from '../generated/prisma/client' +const connectionString = process.env.DATABASE_URL +if (!connectionString) { + throw new Error('Set DATABASE_URL before starting the server') +} +export const db = new PrismaClient({ + adapter: new PrismaPg({ connectionString, max: 5 }), +}) diff --git a/examples/react/start-postgres/src/server/notes.ts b/examples/react/start-postgres/src/server/notes.ts new file mode 100644 index 0000000000..178a68a536 --- /dev/null +++ b/examples/react/start-postgres/src/server/notes.ts @@ -0,0 +1,54 @@ +import { createServerFn } from '@tanstack/react-start' +import { setResponseHeader } from '@tanstack/react-start/server' +import { z } from 'zod' +import { Prisma } from '../generated/prisma/client' +import { db } from './db.server' + +export const listNotes = createServerFn({ method: 'GET' }).handler(async () => { + setResponseHeader('Cache-Control', 'no-store') + return db.note.findMany({ + select: { slug: true, title: true, categoryName: true }, + orderBy: { slug: 'asc' }, + }) +}) + +export const createNote = createServerFn({ method: 'POST' }) + .validator( + z.object({ + slug: z + .string() + .min(1) + .max(80) + .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/), + title: z.string().trim().min(1).max(120), + category: z.string().trim().min(1).max(40), + }), + ) + .handler(async ({ data }) => { + setResponseHeader('Cache-Control', 'no-store') + try { + await db.$transaction(async (tx) => { + await tx.category.upsert({ + where: { name: data.category }, + create: { name: data.category }, + update: {}, + }) + await tx.note.create({ + data: { + slug: data.slug, + title: data.title, + categoryName: data.category, + }, + }) + }) + return { error: '' } + } catch (error) { + if ( + error instanceof Prisma.PrismaClientKnownRequestError && + error.code === 'P2002' + ) { + return { error: 'That slug is already used. Choose another one.' } + } + throw error + } + }) diff --git a/examples/react/start-postgres/tests/notes.spec.ts b/examples/react/start-postgres/tests/notes.spec.ts new file mode 100644 index 0000000000..e2e6534b8b --- /dev/null +++ b/examples/react/start-postgres/tests/notes.spec.ts @@ -0,0 +1,91 @@ +import { randomUUID } from 'node:crypto' +import { PrismaPg } from '@prisma/adapter-pg' +import { expect, test } from '@playwright/test' +import { PrismaClient } from '../src/generated/prisma/client' +const db = new PrismaClient({ + adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }), +}) +test.afterAll(async () => { + await db.$disconnect() +}) + +test('loader renders persisted notes and a failed write rolls back its category', async ({ + page, + request, +}) => { + const slug = randomUUID() + const category = `cat-${slug.slice(0, 8)}` + const rolledBack = `rollback-${slug.slice(0, 8)}` + try { + await page.goto('/') + await page.getByLabel('Slug', { exact: true }).fill(slug) + await page.getByLabel('Title', { exact: true }).fill(`Note ${slug}`) + await page.getByLabel('Category', { exact: true }).fill(category) + await page.getByRole('button', { name: 'Create note', exact: true }).click() + await expect( + page.getByRole('listitem').filter({ hasText: `Note ${slug}` }), + ).toBeVisible() + const response = await request.get('/') + expect(response.status()).toBe(200) + const html = await response.text() + expect(html).toContain(`Note ${slug}`) + const databaseUrl = process.env.DATABASE_URL + if (!databaseUrl) { + throw new Error('Set DATABASE_URL for the database tests') + } + expect(html).not.toContain(databaseUrl) + const password = new URL(databaseUrl).password + if (password) { + expect(html).not.toContain(password) + } + expect(response.headers()['cache-control']).toContain('no-store') + await page.reload() + await expect( + page.getByRole('listitem').filter({ hasText: `Note ${slug}` }), + ).toBeVisible() + + await page.getByLabel('Slug', { exact: true }).fill(slug) + await page.getByLabel('Title', { exact: true }).fill('Duplicate') + await page.getByLabel('Category', { exact: true }).fill(rolledBack) + await page.getByRole('button', { name: 'Create note', exact: true }).click() + await expect(page.getByRole('alert')).toHaveText( + 'That slug is already used. Choose another one.', + ) + expect( + await db.category.findUnique({ where: { name: rolledBack } }), + ).toBeNull() + expect(await db.note.findUnique({ where: { slug } })).toMatchObject({ + title: `Note ${slug}`, + categoryName: category, + }) + } finally { + await db.note.deleteMany({ where: { slug } }) + await db.category.deleteMany({ + where: { name: { in: [category, rolledBack] } }, + }) + } +}) + +test('server validation rejects whitespace titles before a write', async ({ + page, +}) => { + const slug = randomUUID() + const category = `invalid-${slug.slice(0, 8)}` + try { + await page.goto('/') + await page.getByLabel('Slug', { exact: true }).fill(slug) + await page.getByLabel('Title', { exact: true }).fill(' ') + await page.getByLabel('Category', { exact: true }).fill(category) + await page.getByRole('button', { name: 'Create note', exact: true }).click() + await expect(page.getByRole('alert')).toHaveText( + 'Could not save. Check your input and try again.', + ) + expect(await db.note.findUnique({ where: { slug } })).toBeNull() + expect( + await db.category.findUnique({ where: { name: category } }), + ).toBeNull() + } finally { + await db.note.deleteMany({ where: { slug } }) + await db.category.deleteMany({ where: { name: category } }) + } +}) diff --git a/examples/react/start-postgres/tsconfig.json b/examples/react/start-postgres/tsconfig.json new file mode 100644 index 0000000000..cc479423a1 --- /dev/null +++ b/examples/react/start-postgres/tsconfig.json @@ -0,0 +1,21 @@ +{ + "include": ["**/*.ts", "**/*.tsx", "**/*.d.ts"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2024"], + "isolatedModules": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "target": "ES2024", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true + } +} diff --git a/examples/react/start-postgres/vite.config.ts b/examples/react/start-postgres/vite.config.ts new file mode 100644 index 0000000000..e7dc90847a --- /dev/null +++ b/examples/react/start-postgres/vite.config.ts @@ -0,0 +1,8 @@ +import 'dotenv/config' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { nitro } from 'nitro/vite' +export default defineConfig({ + plugins: [tanstackStart(), viteReact(), nitro()], +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fe6d5f7342..3c37c897fc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -15579,6 +15579,61 @@ importers: specifier: ^3.24.2 version: 3.25.57 + examples/react/start-postgres: + dependencies: + '@prisma/adapter-pg': + specifier: 7.0.0 + version: 7.0.0 + '@prisma/client': + specifier: 7.0.0 + version: 7.0.0(@typescript/typescript6@6.0.2)(prisma@7.0.0(@types/react@19.2.9)(@typescript/typescript6@6.0.2)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)) + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../packages/react-router + '@tanstack/react-start': + specifier: workspace:* + version: link:../../../packages/react-start + react: + specifier: ^19.2.3 + version: 19.2.3 + react-dom: + specifier: ^19.2.3 + version: 19.2.3(react@19.2.3) + zod: + specifier: ^4.4.3 + version: 4.5.4 + devDependencies: + '@playwright/test': + specifier: ^1.61.0 + version: 1.61.1 + '@types/node': + specifier: 25.0.9 + version: 25.0.9 + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.9) + '@vitejs/plugin-react': + specifier: ^6.0.1 + version: 6.0.1(@rolldown/plugin-babel@0.2.3(@babel/core@7.29.7(supports-color@10.2.2))(rolldown@1.0.2)(vite@8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)))(babel-plugin-react-compiler@1.0.0)(vite@8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + dotenv: + specifier: ^17.2.3 + version: 17.4.2 + nitro: + specifier: ^3.0.260311-beta + version: 3.0.260311-beta(@electric-sql/pglite@0.3.2)(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)(@libsql/client@0.15.15)(@netlify/blobs@10.1.0)(chokidar@5.0.0)(dotenv@17.4.2)(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(jiti@2.7.0)(lru-cache@11.5.1)(miniflare@4.20260317.0)(mysql2@3.15.3)(rollup@4.63.1)(vite@8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + prisma: + specifier: 7.0.0 + version: 7.0.0(@types/react@19.2.9)(@typescript/typescript6@6.0.2)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) + typescript: + specifier: npm:@typescript/typescript6@^6.0.2 + version: '@typescript/typescript6@6.0.2' + vite: + specifier: ^8.0.14 + version: 8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + packages: '@adobe/css-tools@4.4.1': @@ -29453,6 +29508,67 @@ packages: use-sync-external-store: optional: true + '@prisma/adapter-pg@7.0.0': + resolution: {integrity: sha512-cis1Ib+TVbtSi2VU5Zm1fSmAcA8jg7KwUTbJ6LcWIm1eww380utXM8G23F3UCEPOJO4HiKt6adP/Q1hukjAkgw==} + + pg@8.23.0: + resolution: {integrity: sha512-Ip2EQCngowJLGOfCwkFhPXU7/ljlhn6Rxlmy4XYfL2Y+vyRM59+8uR2xqRWKdYmbXmxCFOAmKxBuSUCdF34qLg==} + engines: {node: '>= 16.0.0'} + peerDependencies: + pg-native: '>=3.0.1' + peerDependenciesMeta: + pg-native: + optional: true + + pg-connection-string@2.14.0: + resolution: {integrity: sha512-XwWDGcLRGCXAR8F/AM5bG7Q+A3Wm2s6QeEjlOKZLlH3UYcguiqCWKyWXVag5TLTIjR7oOJUY8kcADaZgWPyLeg==} + + pg-pool@3.14.0: + resolution: {integrity: sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==} + peerDependencies: + pg: '>=8.0' + + pg-protocol@1.16.0: + resolution: {integrity: sha512-sILXutLVjCLjcDuOmvhX5e2Z4cS5qG/6Bu3VkpFwdf/633ElGLpEh9bgmuI5I4sqKqkifQiGyiCcx1HdtrK7tg==} + + pg-types@2.2.0: + resolution: {integrity: sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==} + engines: {node: '>=4'} + + pg-int8@1.0.1: + resolution: {integrity: sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==} + engines: {node: '>=4.0.0'} + + postgres-array@2.0.0: + resolution: {integrity: sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==} + engines: {node: '>=4'} + + postgres-bytea@1.0.1: + resolution: {integrity: sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==} + engines: {node: '>=0.10.0'} + + postgres-date@1.0.7: + resolution: {integrity: sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==} + engines: {node: '>=0.10.0'} + + postgres-interval@1.2.0: + resolution: {integrity: sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==} + engines: {node: '>=0.10.0'} + + xtend@4.0.2: + resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} + engines: {node: '>=0.4'} + + pgpass@1.0.5: + resolution: {integrity: sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==} + + pg-cloudflare@1.4.0: + resolution: {integrity: sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A==} + + postgres-array@3.0.4: + resolution: {integrity: sha512-nAUSGfSDGOaOAEGwqsRY27GPOea7CNipJPOA7lPbdEpx5Kg3qzdP0AaWC5MlhTWV9s4hFX39nomVZ+C4tnGOJQ==} + engines: {node: '>=12'} + snapshots: '@adobe/css-tools@4.4.1': {} @@ -45433,3 +45549,130 @@ snapshots: immer: 10.1.1 react: 19.2.3 use-sync-external-store: 1.6.0(react@19.2.3) + '@prisma/adapter-pg@7.0.0': + dependencies: + '@prisma/driver-adapter-utils': 7.0.0 + pg: 8.23.0 + postgres-array: 3.0.4 + transitivePeerDependencies: + - pg-native + + pg@8.23.0: + dependencies: + pg-connection-string: 2.14.0 + pg-pool: 3.14.0(pg@8.23.0) + pg-protocol: 1.16.0 + pg-types: 2.2.0 + pgpass: 1.0.5 + optionalDependencies: + pg-cloudflare: 1.4.0 + + pg-connection-string@2.14.0: {} + + pg-pool@3.14.0(pg@8.23.0): + dependencies: + pg: 8.23.0 + + pg-protocol@1.16.0: {} + + pg-types@2.2.0: + dependencies: + pg-int8: 1.0.1 + postgres-array: 2.0.0 + postgres-bytea: 1.0.1 + postgres-date: 1.0.7 + postgres-interval: 1.2.0 + + pg-int8@1.0.1: {} + + postgres-array@2.0.0: {} + + postgres-bytea@1.0.1: {} + + postgres-date@1.0.7: {} + + postgres-interval@1.2.0: + dependencies: + xtend: 4.0.2 + + xtend@4.0.2: {} + + pgpass@1.0.5: + dependencies: + split2: 4.2.0 + + pg-cloudflare@1.4.0: + optional: true + + postgres-array@3.0.4: {} + + '@vitejs/plugin-react@6.0.1(@rolldown/plugin-babel@0.2.3(@babel/core@7.29.7(supports-color@10.2.2))(rolldown@1.0.2)(vite@8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)))(babel-plugin-react-compiler@1.0.0)(vite@8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))': + dependencies: + '@rolldown/pluginutils': 1.0.0-rc.7 + vite: 8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + optionalDependencies: + '@rolldown/plugin-babel': 0.2.3(@babel/core@7.29.7(supports-color@10.2.2))(rolldown@1.0.2)(vite@8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + babel-plugin-react-compiler: 1.0.0 + + '@rolldown/plugin-babel@0.2.3(@babel/core@7.29.7(supports-color@10.2.2))(rolldown@1.0.2)(vite@8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))': + dependencies: + '@babel/core': 7.29.7(supports-color@10.2.2) + picomatch: 4.0.7 + rolldown: 1.0.2 + optionalDependencies: + vite: 8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + optional: true + + nitro@3.0.260311-beta(@electric-sql/pglite@0.3.2)(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)(@libsql/client@0.15.15)(@netlify/blobs@10.1.0)(chokidar@5.0.0)(dotenv@17.4.2)(giget@3.3.1)(ioredis@5.11.1(supports-color@10.2.2))(jiti@2.7.0)(lru-cache@11.5.1)(miniflare@4.20260317.0)(mysql2@3.15.3)(rollup@4.63.1)(vite@8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): + dependencies: + consola: 3.4.2 + crossws: 0.4.4(srvx@0.11.22) + db0: 0.3.4(@electric-sql/pglite@0.3.2)(@libsql/client@0.15.15)(mysql2@3.15.3) + env-runner: 0.1.6(miniflare@4.20260317.0) + h3: 2.0.1-rc.16(crossws@0.4.4(srvx@0.11.22)) + hookable: 6.1.0 + nf3: 0.3.11 + ocache: 0.1.2 + ofetch: 2.0.0-alpha.3 + ohash: 2.0.11 + rolldown: 1.0.0-rc.9(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3) + srvx: 0.11.22 + unenv: 2.0.0-rc.24 + unstorage: 2.0.0-alpha.6(@netlify/blobs@10.1.0)(chokidar@5.0.0)(db0@0.3.4(@electric-sql/pglite@0.3.2)(@libsql/client@0.15.15)(mysql2@3.15.3))(ioredis@5.11.1(supports-color@10.2.2))(lru-cache@11.5.1)(ofetch@2.0.0-alpha.3) + optionalDependencies: + dotenv: 17.4.2 + giget: 3.3.1 + jiti: 2.7.0 + rollup: 4.63.1 + vite: 8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + transitivePeerDependencies: + - '@azure/app-configuration' + - '@azure/cosmos' + - '@azure/data-tables' + - '@azure/identity' + - '@azure/keyvault-secrets' + - '@azure/storage-blob' + - '@capacitor/preferences' + - '@deno/kv' + - '@electric-sql/pglite' + - '@emnapi/core' + - '@emnapi/runtime' + - '@libsql/client' + - '@netlify/blobs' + - '@planetscale/database' + - '@upstash/redis' + - '@vercel/blob' + - '@vercel/functions' + - '@vercel/kv' + - aws4fetch + - better-sqlite3 + - chokidar + - drizzle-orm + - idb-keyval + - ioredis + - lru-cache + - miniflare + - mongodb + - mysql2 + - sqlite3 + - uploadthing From c8ab1f7e1b018225b4ce1a59562917245f01e4ae Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Fri, 11 Sep 2026 15:40:45 -0600 Subject: [PATCH 2/3] fix(examples): protect Postgres server functions from cross-site calls --- docs/start/framework/react/guide/databases.md | 2 +- examples/react/start-postgres/README.md | 2 ++ examples/react/start-postgres/src/routeTree.gen.ts | 3 ++- examples/react/start-postgres/src/start.ts | 9 +++++++++ examples/react/start-postgres/tests/notes.spec.ts | 13 +++++++++++++ 5 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 examples/react/start-postgres/src/start.ts diff --git a/docs/start/framework/react/guide/databases.md b/docs/start/framework/react/guide/databases.md index 6fff306975..5527011769 100644 --- a/docs/start/framework/react/guide/databases.md +++ b/docs/start/framework/react/guide/databases.md @@ -72,7 +72,7 @@ Route loaders can run in the browser after navigation. Call a server function fr ### Validate and write atomically -The POST server function validates the slug format and bounds the title and category lengths before entering a transaction. Browser input attributes are only interface feedback; the server validates again. +The POST server function validates the slug format and bounds the title and category lengths before entering a transaction. Browser input attributes are only interface feedback; the server validates again. The example also enables Start's CSRF middleware in `src/start.ts` for server-function requests and tests that a cross-site call is rejected. CSRF protection does not replace endpoint authorization. Inside the transaction, it upserts a category and creates a note. If the unique note slug already exists, PostgreSQL rejects the insert and Prisma rolls back both operations. A newly created category does not remain behind. The handler catches Prisma's `P2002` unique-constraint error and returns a specific message. Unexpected errors reach the generic error interface instead of exposing database details. diff --git a/examples/react/start-postgres/README.md b/examples/react/start-postgres/README.md index 8b134d2776..3f9ae2d3f2 100644 --- a/examples/react/start-postgres/README.md +++ b/examples/react/start-postgres/README.md @@ -42,6 +42,8 @@ Then run the same generation, migration, and application commands above. Stop th 3. A duplicate slug rolls back the whole transaction, including a newly created category. The interface receives a specific duplicate-slug message. 4. After success, Router invalidation reloads the list from PostgreSQL. +`src/start.ts` enables Start's CSRF middleware for server-function requests. Browser calls from the same origin work; cross-site calls are rejected. This does not replace endpoint authorization. + The server-only module owns the Prisma client and a bounded connection pool. The loader calls a server function instead of importing the database into browser code. The response only includes the selected note fields. Unexpected database failures use a generic UI error rather than exposing database details. ## Verify diff --git a/examples/react/start-postgres/src/routeTree.gen.ts b/examples/react/start-postgres/src/routeTree.gen.ts index dceedffdc1..20a48e5180 100644 --- a/examples/react/start-postgres/src/routeTree.gen.ts +++ b/examples/react/start-postgres/src/routeTree.gen.ts @@ -59,10 +59,11 @@ export const routeTree = rootRouteImport ._addFileTypes() import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' +import type { startInstance } from './start.ts' declare module '@tanstack/react-start' { interface Register { ssr: true router: Awaited> + config: Awaited> } } diff --git a/examples/react/start-postgres/src/start.ts b/examples/react/start-postgres/src/start.ts new file mode 100644 index 0000000000..5fb1e247fb --- /dev/null +++ b/examples/react/start-postgres/src/start.ts @@ -0,0 +1,9 @@ +import { createCsrfMiddleware, createStart } from '@tanstack/react-start' + +export const startInstance = createStart(() => ({ + requestMiddleware: [ + createCsrfMiddleware({ + filter: (ctx) => ctx.handlerType === 'serverFn', + }), + ], +})) diff --git a/examples/react/start-postgres/tests/notes.spec.ts b/examples/react/start-postgres/tests/notes.spec.ts index e2e6534b8b..1e97fecccd 100644 --- a/examples/react/start-postgres/tests/notes.spec.ts +++ b/examples/react/start-postgres/tests/notes.spec.ts @@ -21,10 +21,23 @@ test('loader renders persisted notes and a failed write rolls back its category' await page.getByLabel('Slug', { exact: true }).fill(slug) await page.getByLabel('Title', { exact: true }).fill(`Note ${slug}`) await page.getByLabel('Category', { exact: true }).fill(category) + const mutation = page.waitForRequest( + (request) => request.method() === 'POST', + ) await page.getByRole('button', { name: 'Create note', exact: true }).click() await expect( page.getByRole('listitem').filter({ hasText: `Note ${slug}` }), ).toBeVisible() + const savedRequest = await mutation + const headers = await savedRequest.allHeaders() + delete headers['content-length'] + headers.origin = 'https://untrusted.example' + headers['sec-fetch-site'] = 'cross-site' + const rejected = await request.post(savedRequest.url(), { + headers, + data: savedRequest.postData() ?? '', + }) + expect(rejected.status()).toBe(403) const response = await request.get('/') expect(response.status()).toBe(200) const html = await response.text() From 8455abaa8aaf0b2424f0114e0c5cf1d68dd962be Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Fri, 11 Sep 2026 17:13:12 -0600 Subject: [PATCH 3/3] test(start): run database recipe with disposable PostgreSQL --- docs/start/framework/react/guide/databases.md | 2 +- examples/react/start-postgres/README.md | 4 +- examples/react/start-postgres/package.json | 5 +- .../react/start-postgres/prisma.config.ts | 6 +- examples/react/start-postgres/tests/run.mjs | 38 +++++++ pnpm-lock.yaml | 102 ++++++++++++++++++ pnpm-workspace.yaml | 9 ++ 7 files changed, 160 insertions(+), 6 deletions(-) create mode 100644 examples/react/start-postgres/tests/run.mjs diff --git a/docs/start/framework/react/guide/databases.md b/docs/start/framework/react/guide/databases.md index 5527011769..47f55721ab 100644 --- a/docs/start/framework/react/guide/databases.md +++ b/docs/start/framework/react/guide/databases.md @@ -89,7 +89,7 @@ pnpm build POSTGRES_EXAMPLE_PRODUCTION=1 pnpm test:e2e ``` -The tests use a dedicated database, create unique records, and clean up only those records. They verify initial HTML contains persisted notes, data survives reload, whitespace-only titles fail server validation, and duplicate-note failure rolls back its new category. +The test script starts an isolated PostgreSQL 17 server on localhost:3121, generates the client, applies migrations, and removes the database after the run. It supplies the test connection string automatically. Keep ports 3120 and 3121 free. The tests verify initial HTML contains persisted notes, data survives reload, whitespace-only titles fail server validation, and duplicate-note failure rolls back its new category. Also build with a harmless test credential and search client assets and any published source maps for it. Inspect response bodies too. A successful connection does not prove the credentials stayed on the server. diff --git a/examples/react/start-postgres/README.md b/examples/react/start-postgres/README.md index 3f9ae2d3f2..b33185fd3e 100644 --- a/examples/react/start-postgres/README.md +++ b/examples/react/start-postgres/README.md @@ -57,11 +57,13 @@ pnpm build POSTGRES_EXAMPLE_PRODUCTION=1 pnpm test:e2e ``` +Each test run starts a disposable PostgreSQL 17 server on localhost:3121, generates the client, applies migrations, and stops and removes the database afterward, including when tests fail. The runner supplies its own database URL, so tests do not need a `.env` file or a running Compose service. Keep application port 3120 and database port 3121 free. The pinned `embedded-postgres` development dependency provides the database binaries; its platform package install script restores required native-library links. + The tests check persisted SSR data, reloads, server validation and database rollback. For a manual production start, export `DATABASE_URL` in the server environment and run `PORT=3120 pnpm start`. Do not assume a production Node process will load `.env`; the Prisma CLI, Vite development server, and Playwright configuration load it for their own processes. ## Deploy -Use a Node-compatible host for this `pg` adapter and Nitro build. Generate the Prisma client during the build. Apply `prisma migrate deploy` once as a release step before starting compatible application instances, rather than running migrations in each request. Use a separate migration connection if your provider's pooler requires it. +Use a Node-compatible host for this `pg` adapter and Nitro build. Generate the Prisma client during the build. Client generation and the build do not need a database URL; migrations and the running server do. Apply `prisma migrate deploy` once as a release step before starting compatible application instances, rather than running migrations in each request. Use a separate migration connection if your provider's pooler requires it. Set `DATABASE_URL` as a server secret. Never prefix it with `VITE_`, serialize it to a loader response, or commit it. Configure TLS using your provider's certificate guidance. Size the pool for the total number of processes and database connection limit. Edge runtimes may need a different supported adapter. diff --git a/examples/react/start-postgres/package.json b/examples/react/start-postgres/package.json index 09060c3330..b68f261dcd 100644 --- a/examples/react/start-postgres/package.json +++ b/examples/react/start-postgres/package.json @@ -9,7 +9,7 @@ "db:generate": "prisma generate", "db:migrate": "prisma migrate deploy", "db:dev": "prisma migrate dev", - "test:e2e": "playwright test" + "test:e2e": "node tests/run.mjs" }, "dependencies": { "@prisma/adapter-pg": "7.0.0", @@ -30,6 +30,7 @@ "vite": "^8.0.14", "prisma": "7.0.0", "dotenv": "^17.2.3", - "@playwright/test": "^1.61.0" + "@playwright/test": "^1.61.0", + "embedded-postgres": "17.10.0-beta.17" } } diff --git a/examples/react/start-postgres/prisma.config.ts b/examples/react/start-postgres/prisma.config.ts index 0daa8973bf..9b1ca4b9d0 100644 --- a/examples/react/start-postgres/prisma.config.ts +++ b/examples/react/start-postgres/prisma.config.ts @@ -1,7 +1,9 @@ import 'dotenv/config' -import { defineConfig, env } from 'prisma/config' +import { defineConfig } from 'prisma/config' export default defineConfig({ schema: './prisma/schema.prisma', migrations: { path: './prisma/migrations' }, - datasource: { url: env('DATABASE_URL') }, + datasource: process.env.DATABASE_URL + ? { url: process.env.DATABASE_URL } + : undefined, }) diff --git a/examples/react/start-postgres/tests/run.mjs b/examples/react/start-postgres/tests/run.mjs new file mode 100644 index 0000000000..2670f830bb --- /dev/null +++ b/examples/react/start-postgres/tests/run.mjs @@ -0,0 +1,38 @@ +import { execFileSync } from 'node:child_process' +import { randomUUID } from 'node:crypto' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import EmbeddedPostgres from 'embedded-postgres' + +const databaseDir = await mkdtemp(join(tmpdir(), 'start-postgres-test-')) +const password = randomUUID() +const port = 3121 +const database = new EmbeddedPostgres({ + databaseDir, + port, + user: 'start_test', + password, + persistent: false, + postgresFlags: ['-h', '127.0.0.1'], +}) + +try { + await database.initialise() + await database.start() + await database.createDatabase('start_test') + const env = { + ...process.env, + DATABASE_URL: `postgresql://start_test:${password}@127.0.0.1:${port}/start_test`, + } + for (const args of [ + ['exec', 'prisma', 'generate'], + ['exec', 'prisma', 'migrate', 'deploy'], + ['exec', 'playwright', 'test', ...process.argv.slice(2)], + ]) { + execFileSync('pnpm', args, { env, stdio: 'inherit' }) + } +} finally { + await database.stop() + await rm(databaseDir, { recursive: true, force: true }) +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3c37c897fc..4d673f3bdc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -15633,6 +15633,9 @@ importers: vite: specifier: ^8.0.14 version: 8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + embedded-postgres: + specifier: 17.10.0-beta.17 + version: 17.10.0-beta.17 packages: @@ -29569,6 +29572,63 @@ packages: resolution: {integrity: sha512-nAUSGfSDGOaOAEGwqsRY27GPOea7CNipJPOA7lPbdEpx5Kg3qzdP0AaWC5MlhTWV9s4hFX39nomVZ+C4tnGOJQ==} engines: {node: '>=12'} + '@embedded-postgres/darwin-arm64@17.10.0-beta.17': + resolution: {integrity: sha512-E2dxhSllrcyAJBHuvgTrBTx2BaPlX2vvjXClPKHxfwBezk+nTZ01uAEraKiRJMpzHSCyN8J1dTjKh4q/uTsBLQ==} + engines: {node: '>=16'} + cpu: [arm64] + os: [darwin] + + '@embedded-postgres/darwin-x64@17.10.0-beta.17': + resolution: {integrity: sha512-gXk65MIyttD/PWo6NDSmu/n4vzPcqZQmxVWjEKuecwlyGmWO984AZ3Ljb7F0bwPvXhqcovH4FGN4ydr0fGeJxg==} + engines: {node: '>=16'} + cpu: [x64] + os: [darwin] + + '@embedded-postgres/linux-arm64@17.10.0-beta.17': + resolution: {integrity: sha512-mC+bQvaBEf0WDD0nPWW3eGUXDUVzoyCzMtgl+Fw6Jy9DkQFK+jcPtzkzqhhrS/fGzn5telNpKInl8xPqDh71Ig==} + engines: {node: '>=16'} + cpu: [arm64] + os: [linux] + + '@embedded-postgres/linux-arm@17.10.0-beta.17': + resolution: {integrity: sha512-XQrRydqjgPrvvCKF1PrLvMljMbeXXT4GbB70+z7viqUWg3bgq31nGMkupa2TXHLqRnfmEhz1u3gn3xgQIphLZQ==} + engines: {node: '>=16'} + cpu: [arm] + os: [linux] + + '@embedded-postgres/linux-ia32@17.10.0-beta.17': + resolution: {integrity: sha512-ck2QlYCPmmNRJotXp0cJnnB5Yn/bk89qT3cjVCxUfkS1b/56Odu9ID6zvAYFebvYeHU69UwOEbplikV4saRYWw==} + engines: {node: '>=16'} + cpu: [ia32] + os: [linux] + + '@embedded-postgres/linux-ppc64@17.10.0-beta.17': + resolution: {integrity: sha512-+Mb0E41rvlwBhAV11eZf51rlxSHA8ancPHPFxhyljg+ZJ62QB1YryBf+rIkphpG2bnt4aJwxd1JOUk3PonlrLA==} + engines: {node: '>=16'} + cpu: [ppc64] + os: [linux] + + '@embedded-postgres/linux-x64@17.10.0-beta.17': + resolution: {integrity: sha512-hU4Sgna19ixDP/l3P/zkHhQ9B0JDV39qA97RNz55QcngeRjFC5/1G36LZjODVJ84kVJHUTQMmly7nzWO8js8kg==} + engines: {node: '>=16'} + cpu: [x64] + os: [linux] + + '@embedded-postgres/windows-x64@17.10.0-beta.17': + resolution: {integrity: sha512-q6xIETTkv67i1QlTWz1LAKb3Z+vG2V3qrp+BjLEWhCQ9jE4hbbsQ/J/3wiOPFLJbuwak7CfHC9EUJG7txAbGKw==} + engines: {node: '>=16'} + cpu: [x64] + os: [win32] + + async-exit-hook@2.0.1: + resolution: {integrity: sha512-NW2cX8m1Q7KPA7a5M2ULQeZ2wR5qI5PAbw5L0UOMxdioVk9PMZ0h1TmyZEkPYrCvYjDlFICusOu1dlEKAAeXBw==} + engines: {node: '>=0.12.0'} + + embedded-postgres@17.10.0-beta.17: + resolution: {integrity: sha512-s9ITJA41OTIQmn91RLqQ5X2MVP2BCZ8pb4tQX3MY8VOd8xNCzzlgfHGcXuitDzK800FhbG/3YufFk21KTTvpzA==} + engines: {node: '>=16'} + + snapshots: '@adobe/css-tools@4.4.1': {} @@ -45676,3 +45736,45 @@ snapshots: - mysql2 - sqlite3 - uploadthing + + '@embedded-postgres/darwin-arm64@17.10.0-beta.17': + optional: true + + '@embedded-postgres/darwin-x64@17.10.0-beta.17': + optional: true + + '@embedded-postgres/linux-arm64@17.10.0-beta.17': + optional: true + + '@embedded-postgres/linux-arm@17.10.0-beta.17': + optional: true + + '@embedded-postgres/linux-ia32@17.10.0-beta.17': + optional: true + + '@embedded-postgres/linux-ppc64@17.10.0-beta.17': + optional: true + + '@embedded-postgres/linux-x64@17.10.0-beta.17': + optional: true + + '@embedded-postgres/windows-x64@17.10.0-beta.17': + optional: true + + async-exit-hook@2.0.1: {} + + embedded-postgres@17.10.0-beta.17: + dependencies: + async-exit-hook: 2.0.1 + pg: 8.23.0 + optionalDependencies: + '@embedded-postgres/darwin-arm64': 17.10.0-beta.17 + '@embedded-postgres/darwin-x64': 17.10.0-beta.17 + '@embedded-postgres/linux-arm': 17.10.0-beta.17 + '@embedded-postgres/linux-arm64': 17.10.0-beta.17 + '@embedded-postgres/linux-ia32': 17.10.0-beta.17 + '@embedded-postgres/linux-ppc64': 17.10.0-beta.17 + '@embedded-postgres/linux-x64': 17.10.0-beta.17 + '@embedded-postgres/windows-x64': 17.10.0-beta.17 + transitivePeerDependencies: + - pg-native diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 3cff53a1b8..c67bfbc299 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -130,6 +130,15 @@ overrides: '@tanstack/nitro-v2-vite-plugin': 'workspace:*' allowBuilds: + # Embedded PostgreSQL restores native-library symlinks for database tests. + '@embedded-postgres/darwin-arm64': true + '@embedded-postgres/darwin-x64': true + '@embedded-postgres/linux-arm': true + '@embedded-postgres/linux-arm64': true + '@embedded-postgres/linux-ia32': true + '@embedded-postgres/linux-ppc64': true + '@embedded-postgres/linux-x64': true + '@embedded-postgres/windows-x64': true # root dependency '@swc/core': true # required for TypeScript compilation nx: true