Modern full-stack React starter. Postgres + better-auth + Drizzle ORM, deployed to Cloudflare Workers.
| Category | Technology |
|---|---|
| Framework | React 19 |
| Routing | TanStack Router |
| Data Fetching | TanStack Query |
| Auth | better-auth |
| Database | Any Postgres (default: Neon) |
| ORM | Drizzle ORM |
| DB Driver | pg through Cloudflare Hyperdrive |
| API Server | Hono |
| Deployment | Cloudflare Workers |
| UI Library | ZUI (CSS-first) |
| Icons | Phosphor Icons |
| Validation | Zod |
| Linting & Formatting | Biome |
| Testing | Vitest |
- Node.js 22.22.2+, 24.15+ or 26+ (vitest and jsdom need these;
enginesinpackage.jsonhas the exact range), and pnpm - A Postgres database — Neon recommended (free tier works)
- A Cloudflare account (for deployment)
pnpm installSign up at Neon, create a project, and copy the direct (not pooled) connection string. In production, Hyperdrive does the pooling. Local dev has no pooling and opens one connection per request. It looks like:
postgresql://USER:PASSWORD@ep-xxx.region.aws.neon.tech/DBNAME?sslmode=require
Any Postgres works — Supabase, RDS, Railway, local Docker, etc. Just pass a valid connection string.
Copy .env.example → .env and fill in:
DATABASE_URL=postgresql://... # drizzle-kit (migrations)
CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE=postgresql://... # the Worker in local dev
BETTER_AUTH_SECRET= # see below
BETTER_AUTH_URL=http://localhost:3450Use the same connection string for both database variables.
Generate a secret:
openssl rand -hex 32pnpm run db:migrateThis applies the SQL files in drizzle/ to your database. Tables created: user, session, account, verification, jwks, profiles.
pnpm run devApp runs at http://localhost:3450 (proxied as [ras.localhost](http://ras.localhost:1355) via portless).
db/ # Drizzle schema + client
├── schema.ts # Auth tables + profiles
└── client.ts # pg client + Drizzle (Hyperdrive or DATABASE_URL)
drizzle/ # Generated migration SQL
drizzle.config.ts # Drizzle Kit config
src/
├── components/ # AuthProvider, login/signup/password forms, LogoutButton
├── lib/
│ ├── auth/
│ │ ├── server.ts # better-auth server config
│ │ └── client.ts # better-auth React client
│ ├── fetching/
│ │ ├── user.ts # session + profile queries
│ │ └── error-response.ts
│ ├── create-title.ts
│ └── get-error-message.ts
├── routes/ # TanStack Router file-based
│ ├── __root.tsx
│ ├── _authed/ # protected
│ ├── _public/ # login / signup / forgot-password
│ └── index.tsx
├── worker/ # Hono on Cloudflare Workers
│ ├── index.ts # entry
│ ├── hono.ts # routes
│ ├── env.ts # typed env bindings
│ ├── context.ts # request context (session + DB)
│ ├── middleware/db.ts # opens one DB connection per request
│ └── profile.ts # /api/me endpoints
├── constants.ts
├── main.tsx
└── styles.css # imports @mrmartineau/zui/css
Quick recipes for the most common things you'll want to add. Agents: see AGENTS.md for the same recipes plus project conventions.
Routes are file-based via TanStack Router. Drop a file into src/routes and the route tree (src/routeTree.gen.ts) regenerates automatically while pnpm run dev is running.
// src/routes/about.tsx
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/about')({
component: About,
})
function About() {
return <h1>About</h1>
}Folder conventions used here:
src/routes/_public/*— unauthenticated pages (login, sign-up, forgot-password). The_publicsegment is a pathless layout route, so files inside resolve at/login,/sign-up, etc.src/routes/_authed/*— pages behind auth._authed/route.tsxrunsgetSession()inbeforeLoadand redirects to/loginwhen there's no session. Anything under_authed/is protected by inheritance.src/routes/_authed/app/*— the app shell. Files here resolve at/app/....
To add a protected page, create src/routes/_authed/app/billing.tsx and it's live at /app/billing with auth already enforced by the parent layout.
Use Link from @tanstack/react-router for SPA navigation. Prefer route constants from src/constants.ts rather than hard-coding paths:
import { Link } from '@tanstack/react-router'
import { ROUTE_APP_HOME } from '@/constants'
;<Link to={ROUTE_APP_HOME}>App</Link>When you add a new top-level route, add a matching ROUTE_* constant so links stay refactor-safe.
src/routes/__root.tsx is the app-wide shell — anything you put there appears on every page, with route content rendered at <Outlet />.
For section-level layouts (e.g. an authed sidebar), edit src/routes/_authed/route.tsx — its JSX wraps every authed child route.
Hono is mounted at /api. Edit src/worker/hono.ts:
import { requireRequestContext } from './context'
app.get('/widgets', async (c) => {
const ctx = await requireRequestContext(c)
if (ctx instanceof Response) return ctx // 401
const { db, user } = ctx
const rows = await db
.select()
.from(widgets)
.where(eq(widgets.ownerId, user.id))
return c.json(rows)
})requireRequestContext(c) returns either {db, user, profile} or a 401 Response. Use createRequestContext(c) instead if the route is optionally authenticated.
For anything bigger than a couple of handlers, extract to its own file in src/worker/ (see profile.ts for the shape) and import it into hono.ts.
- Edit
db/schema.ts— add the table with Drizzle'spgTable. pnpm run db:generate— emits a new SQL file indrizzle/.- Commit the SQL.
pnpm run db:migrate— applies it to whateverDATABASE_URLpoints at.
Re-run pnpm run cf-typegen only if you change wrangler.jsonc bindings — schema changes don't need it.
The QueryClient is already provided in src/main.tsx. Use useQuery directly in a component, or call it from inside a route loader to prefetch.
import { useQuery } from '@tanstack/react-query'
function Widgets() {
const { data } = useQuery({
queryKey: ['widgets'],
queryFn: () => fetch('/api/widgets').then((r) => r.json()),
})
return (
<ul>
{data?.map((w) => (
<li key={w.id}>{w.name}</li>
))}
</ul>
)
}For session-aware data, see src/lib/fetching/user.ts for the existing getSession() / profile patterns.
Plain React components live in src/components/. UI primitives come from ZUI — use zui-button, zui-card, zui-input classes on regular HTML elements rather than wrapping anything. Tokens (--space-*, --color-*, --step-*) are CSS custom properties, available in any stylesheet.
- Add to
.envfor local dev. - Add to
wrangler.jsoncvars(non-secret) orpnpm exec wrangler secret put NAME(secret). - Add to
WorkerEnvinsrc/worker/env.tsso it's typed inside Hono handlers. - Run
pnpm run cf-typegento refreshworker-configuration.d.ts.
Email/password via better-auth:
- Sign up —
authClient.signUp.email({email, password, name}) - Sign in —
authClient.signIn.email({email, password}) - Sign out —
authClient.signOut() - Session —
authClient.useSession()(live React hook) - Forgot password — POST
/api/auth/forget-password(server needssendResetPasswordconfigured to actually send mail; seesrc/lib/auth/server.ts)
A profiles row is auto-inserted via databaseHooks.user.create.after on sign up.
src/routes/_authed/route.tsx calls getSession() in beforeLoad and redirects to /login if missing.
src/worker/context.ts exposes:
createRequestContext(c)— pulls session from request headers, returns{db, user, profile}requireRequestContext(c)— same, returns 401 Response if no auth
Supports both cookie sessions and Authorization: Bearer <api_key> (where api_key is the UUID stored in profiles.api_key).
Hono mounted at /api. Defined in src/worker/hono.ts:
app.on(['GET', 'POST'], '/auth/*', ...) // better-auth handler
app.get('/me', getCurrentProfile)
app.patch('/me', updateCurrentProfile)Add new routes in hono.ts. Use requireRequestContext(c) inside handlers needing auth.
Drizzle ORM with the pg driver. In the Worker, pg connects through Cloudflare Hyperdrive, which pools connections near the database. dbMiddleware opens one connection per request and closes it after the response. Full guide in docs/DATABASE.md: conventions, safe vs. destructive migrations, hand-editing SQL, switching providers, prod migrations.
- Edit
db/schema.ts pnpm run db:generate→ emits SQL indrizzle/- Inspect the SQL — stop if it drops or renames anything you didn't intend
- Commit
db/schema.ts+ the SQL +drizzle/meta/together pnpm run db:migrate→ applies to your DB
import { eq } from 'drizzle-orm'
import { createDbClient, type DbEnv } from '../../db/client'
import { profiles } from '../../db/schema'
// getProfile opens its own connection and always closes it. Callers do not
// connect or close anything.
export const getProfile = async (env: DbEnv, userId: string) => {
const { client, db } = createDbClient(env)
await client.connect()
try {
const [profile] = await db
.select()
.from(profiles)
.where(eq(profiles.id, userId))
return profile ?? null
} finally {
await client.end()
}
}The driver is plain pg, so any Postgres works (Neon, Supabase, RDS, local Docker). Create a Hyperdrive config for the new connection string, put its id in wrangler.jsonc, and set the same string as DATABASE_URL and CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE in .env.
To run without Hyperdrive, remove the hyperdrive block from wrangler.jsonc and set a DATABASE_URL secret. It works, but each request then pays the full connection setup.
# Paste the connection string at the prompt. `read -s` keeps it off the
# screen and out of your shell history. (bash or zsh; printf, not read -p,
# because zsh's read -p means something else.)
printf 'Connection string: '; read -rs DB_URL; printf '\n'
pnpm exec wrangler hyperdrive create zed-stack-starter-db --connection-string="$DB_URL"
unset DB_URLOr create it in the Cloudflare dashboard: Storage & Databases → Hyperdrive.
Put the returned id in the hyperdrive block of wrangler.jsonc. The Worker reads the database through this binding, so it needs no DATABASE_URL secret.
pnpm exec wrangler secret put BETTER_AUTH_SECRETUpdate BETTER_AUTH_URL in wrangler.jsonc vars to your production URL.
pnpm run deployAuthenticate first if needed: pnpm exec wrangler login.
wrangler.jsonc:
nodejs_compatflag — required for bcryptjs + better-auth internalsassets.not_found_handling: "single-page-application"— SPA fallbackplacement.mode: "smart"— Worker runs near your DBai.binding: "AI"— Workers AI available asenv.AI
| Script | What it does |
|---|---|
pnpm run dev |
Start dev server on port 3450 |
pnpm run build |
Vite build + tsc |
pnpm run preview |
Preview production build |
pnpm run deploy |
Build + wrangler deploy |
pnpm run db:generate |
Generate Drizzle migrations from schema |
pnpm run db:migrate |
Apply migrations to DATABASE_URL |
pnpm run db:studio |
Open Drizzle Studio |
pnpm run test |
Run Vitest |
pnpm run type-check |
TypeScript check |
pnpm run cf-typegen |
Regenerate worker-configuration.d.ts |
pnpm run check |
Biome check + autofix |
pnpm run format |
Biome format |
ZUI is a CSS-first component + token library. Imported once in src/styles.css:
@import "@mrmartineau/zui/css";Components are plain elements with zui-* classes (zui-button, zui-card, zui-input, etc.) — no JS wrappers, no build step. Design tokens (--space-*, --color-*, --step-*) are exposed as CSS custom properties.
| Env var | Purpose |
|---|---|
DATABASE_URL |
Postgres connection string for drizzle-kit; the Worker's fallback when no Hyperdrive is bound |
CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE |
Connection string the HYPERDRIVE binding uses in local dev |
BETTER_AUTH_SECRET |
32+ char random hex; signs sessions |
BETTER_AUTH_URL |
Public origin (cookies + redirect URLs) |
BETTER_AUTH_TRUSTED_ORIGINS |
Comma-separated. Defaults to BETTER_AUTH_URL |
BETTER_AUTH_DISABLE_SIGNUP |
true to lock out new sign-ups |
MIT