Skip to content

Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.

feat: add tanstack-start skill — full-stack SSR dashboard on Cloudflare Workers

Jeremy Dawes0a10f3da76d3
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index db083286..5a17e756 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -9,7 +9,7 @@
"plugins": [
{
"name": "cloudflare",
- "description": "Scaffold Cloudflare Workers, Hono APIs, D1/Drizzle schemas, and full-stack Vite+Workers apps.",
+ "description": "Scaffold Cloudflare Workers, Hono APIs, D1/Drizzle schemas, full-stack Vite+Workers apps, and TanStack Start SSR dashboards.",
"source": "./plugins/cloudflare",
"category": "development"
},
diff --git a/CLAUDE.md b/CLAUDE.md
index cbbb337b..56d7d0bc 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -15,11 +15,12 @@ Production workflow skills for Claude Code CLI. Each skill guides Claude through
```
claude-skills/
-├── plugins/ # 9 installable plugins (31 skills)
-│ ├── cloudflare/ # Cloudflare Workers, Hono, D1/Drizzle, Vite
+├── plugins/ # 9 installable plugins (32 skills)
+│ ├── cloudflare/ # Cloudflare Workers, Hono, D1/Drizzle, Vite, TanStack Start
│ │ └── skills/
│ │ ├── cloudflare-worker-builder/
│ │ ├── vite-flare-starter/
+│ │ ├── tanstack-start/
│ │ ├── hono-api-scaffolder/
│ │ └── d1-drizzle-schema/
│ ├── web-design/ # Web design methodology, patterns, SEO
diff --git a/README.md b/README.md
index cbfce6b4..20a38ede 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@ Workflow skills for [Claude Code](https://claude.com/claude-code) that produce t
| Plugin | Skills | What it produces |
|--------|--------|-----------------|
-| **cloudflare** | cloudflare-worker-builder, vite-flare-starter, hono-api-scaffolder, d1-drizzle-schema | Deployable Cloudflare Workers, full-stack apps, Hono APIs, D1 schemas |
+| **cloudflare** | cloudflare-worker-builder, vite-flare-starter, tanstack-start, hono-api-scaffolder, d1-drizzle-schema | Deployable Cloudflare Workers, full-stack apps, TanStack Start SSR dashboards, Hono APIs, D1 schemas |
| **web-design** | web-design-methodology, web-design-patterns, seo-local-business | Production HTML/CSS, component patterns, local business SEO |
| **frontend** | tailwind-theme-builder, shadcn-ui | Themed Tailwind v4 + shadcn/ui setup with dark mode |
| **design-assets** | color-palette, favicon-gen, icon-set-generator | Colour palettes, favicon packages, custom SVG icon sets |
diff --git a/plugins/cloudflare/.claude-plugin/plugin.json b/plugins/cloudflare/.claude-plugin/plugin.json
index b5a9002a..780774a7 100644
--- a/plugins/cloudflare/.claude-plugin/plugin.json
+++ b/plugins/cloudflare/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "cloudflare",
- "description": "Scaffold Cloudflare Workers, Hono APIs, D1/Drizzle schemas, and full-stack Vite+Workers apps.",
+ "description": "Scaffold Cloudflare Workers, Hono APIs, D1/Drizzle schemas, full-stack Vite+Workers apps, and TanStack Start SSR dashboards.",
"author": {
"name": "Jeremy Dawes / Jezweb",
"email": "[email protected]"
diff --git a/plugins/cloudflare/skills/tanstack-start/SKILL.md b/plugins/cloudflare/skills/tanstack-start/SKILL.md
new file mode 100644
index 00000000..cadc65a9
--- /dev/null
+++ b/plugins/cloudflare/skills/tanstack-start/SKILL.md
@@ -0,0 +1,336 @@
+---
+name: tanstack-start
+description: "Build a full-stack TanStack Start app on Cloudflare Workers from scratch — SSR, file-based routing, server functions, D1+Drizzle, better-auth, Tailwind v4+shadcn/ui. No template repo — Claude generates every file fresh per project."
+compatibility: claude-code-only
+---
+
+# TanStack Start on Cloudflare
+
+Build a complete full-stack app from nothing. Claude generates every file — no template clone, no scaffold command. Each project gets exactly what it needs.
+
+## What You Get
+
+| Layer | Technology |
+|-------|-----------|
+| Framework | TanStack Start v1 (SSR, file-based routing, server functions) |
+| Frontend | React 19, Tailwind v4, shadcn/ui |
+| Backend | Server functions (via Nitro on Cloudflare Workers) |
+| Database | D1 + Drizzle ORM |
+| Auth | better-auth (Google OAuth + email/password) |
+| Deployment | Cloudflare Workers |
+
+## Workflow
+
+### Step 1: Gather Project Info
+
+Ask for:
+
+| Required | Optional |
+|----------|----------|
+| Project name (kebab-case) | Google OAuth credentials |
+| One-line description | Custom domain |
+| Cloudflare account (Jezweb Team or Personal) | R2 storage needed? |
+| Auth method: Google OAuth, email/password, or both | Admin email |
+
+### Step 2: Initialise Project
+
+Create the project directory and all config files from scratch.
+
+**See `references/architecture.md`** for the complete file tree, all dependencies, and config templates.
+
+Create these files first:
+
+1. **`package.json`** — all runtime + dev dependencies with version ranges from architecture.md
+2. **`tsconfig.json`** — strict mode, `@/*` path alias mapped to `src/*`
+3. **`vite.config.ts`** — plugins in correct order: `cloudflare()` → `tailwindcss()` → `tanstackStart()` → `viteReact()`
+4. **`wrangler.jsonc`** — `main: "@tanstack/react-start/server-entry"`, `nodejs_compat` flag, D1 binding placeholder
+5. **`.dev.vars`** — generate `BETTER_AUTH_SECRET` with `openssl rand -hex 32`, set `BETTER_AUTH_URL=http://localhost:3000`, `TRUSTED_ORIGINS=http://localhost:3000`
+6. **`.gitignore`** — node_modules, .wrangler, dist, .output, .dev.vars, .vinxi, .DS_Store
+
+Then:
+
+```bash
+cd PROJECT_NAME
+pnpm install
+```
+
+Create D1 database and update wrangler.jsonc:
+
+```bash
+npx wrangler d1 create PROJECT_NAME-db
+# Copy the database_id into wrangler.jsonc d1_databases binding
+```
+
+### Step 3: Database Schema
+
+Create the Drizzle schema with D1-correct patterns.
+
+**`src/db/schema.ts`** — Define all tables:
+
+- **better-auth tables**: `users`, `sessions`, `accounts`, `verifications` — these are required by better-auth
+- **Application table**: `items` (or whatever the project needs) for CRUD demo
+
+D1-specific rules:
+- Use `integer` for timestamps (Unix epoch), NOT Date objects
+- Use `text` for primary keys (nanoid/cuid2), NOT autoincrement
+- Keep bound parameters under 100 per query (batch large inserts)
+- Foreign keys are always ON in D1
+
+**`src/db/index.ts`** — Drizzle client factory:
+
+```typescript
+import { drizzle } from "drizzle-orm/d1";
+import { env } from "cloudflare:workers";
+import * as schema from "./schema";
+
+export function getDb() {
+ return drizzle(env.DB, { schema });
+}
+```
+
+**CRITICAL**: Use `import { env } from "cloudflare:workers"` — NOT `process.env`. This is a per-request binding, so create the Drizzle client inside each server function, not at module level.
+
+**`drizzle.config.ts`**:
+
+```typescript
+import { defineConfig } from "drizzle-kit";
+
+export default defineConfig({
+ schema: "./src/db/schema.ts",
+ out: "./drizzle",
+ dialect: "sqlite",
+});
+```
+
+Add migration scripts to `package.json`:
+
+```json
+{
+ "db:generate": "drizzle-kit generate",
+ "db:migrate:local": "wrangler d1 migrations apply PROJECT_NAME-db --local",
+ "db:migrate:remote": "wrangler d1 migrations apply PROJECT_NAME-db --remote"
+}
+```
+
+Generate and apply the initial migration:
+
+```bash
+pnpm db:generate
+pnpm db:migrate:local
+```
+
+### Step 4: Configure Auth
+
+**`src/lib/auth.server.ts`** — Server-side better-auth configuration:
+
+```typescript
+import { betterAuth } from "better-auth";
+import { drizzleAdapter } from "better-auth/adapters/drizzle";
+import { drizzle } from "drizzle-orm/d1";
+import { env } from "cloudflare:workers";
+import * as schema from "../db/schema";
+
+export function getAuth() {
+ const db = drizzle(env.DB, { schema });
+ return betterAuth({
+ database: drizzleAdapter(db, { provider: "sqlite" }),
+ secret: env.BETTER_AUTH_SECRET,
+ baseURL: env.BETTER_AUTH_URL,
+ trustedOrigins: env.TRUSTED_ORIGINS?.split(",") ?? [],
+ emailAndPassword: { enabled: true },
+ socialProviders: {
+ // Add Google OAuth if credentials provided
+ },
+ });
+}
+```
+
+**CRITICAL**: `getAuth()` must be called per-request (inside handler/loader), NOT at module level. The `env` import from `cloudflare:workers` is only available during request handling.
+
+**`src/lib/auth.client.ts`** — Client-side auth hooks:
+
+```typescript
+import { createAuthClient } from "better-auth/react";
+
+export const { useSession, signIn, signOut, signUp } = createAuthClient();
+```
+
+**`src/routes/api/auth/$.ts`** — API catch-all route for better-auth:
+
+```typescript
+import { createAPIFileRoute } from "@tanstack/react-start/api";
+import { getAuth } from "../../../lib/auth.server";
+
+export const APIRoute = createAPIFileRoute("/api/auth/$")({
+ GET: ({ request }) => getAuth().handler(request),
+ POST: ({ request }) => getAuth().handler(request),
+});
+```
+
+**CRITICAL**: Auth MUST use an API route (`createAPIFileRoute`), NOT a server function (`createServerFn`). better-auth needs direct request/response access.
+
+### Step 5: App Shell + Theme
+
+**`src/routes/__root.tsx`** — Root layout with HTML document:
+
+- Render full HTML document with `<HeadContent />` and `<Scripts />` from `@tanstack/react-router`
+- Add `suppressHydrationWarning` on `<html>` for SSR + theme toggle compatibility
+- Import the global CSS file
+- Include theme initialisation script inline to prevent flash of wrong theme
+
+**`src/styles/app.css`** — Tailwind v4 + shadcn/ui:
+
+- `@import "tailwindcss"` (v4 syntax)
+- CSS variables for shadcn/ui tokens in `:root` and `.dark`
+- Neutral/monochrome palette (stone, slate, zinc)
+- Use semantic tokens only — never raw Tailwind colours
+
+**`src/router.tsx`** — Router configuration:
+
+```typescript
+import { createRouter as createTanStackRouter } from "@tanstack/react-router";
+import { routeTree } from "./routeTree.gen";
+
+export function createRouter() {
+ return createTanStackRouter({ routeTree });
+}
+
+declare module "@tanstack/react-router" {
+ interface Register {
+ router: ReturnType<typeof createRouter>;
+ }
+}
+```
+
+**`src/client.tsx`** and **`src/ssr.tsx`** — Entry points (standard TanStack Start boilerplate).
+
+Install shadcn/ui components needed for the dashboard:
+
+```bash
+pnpm dlx shadcn@latest init --defaults
+pnpm dlx shadcn@latest add button card input label sidebar table dropdown-menu form separator sheet
+```
+
+**Note**: Configure shadcn to use `src/components` as the components directory.
+
+Theme toggle: three-state (light → dark → system → light). Store preference in localStorage. Apply `.dark` class on `<html>`. Use JS-only system preference detection — NO CSS `@media (prefers-color-scheme)` queries.
+
+### Step 6: Routes + Dashboard
+
+Create the route files:
+
+```
+src/routes/
+├── __root.tsx # Root layout (HTML shell, theme, CSS)
+├── index.tsx # Landing → redirect to /dashboard if authenticated
+├── login.tsx # Login form (email/password + Google OAuth button)
+├── register.tsx # Registration form
+├── _authed.tsx # Auth guard layout (beforeLoad checks session)
+└── _authed/
+ ├── dashboard.tsx # Stat cards overview
+ ├── items.tsx # Items list (table with actions)
+ ├── items.$id.tsx # Edit item form
+ └── items.new.tsx # Create item form
+```
+
+**Auth guard pattern** (`_authed.tsx`):
+
+```typescript
+import { createFileRoute, redirect } from "@tanstack/react-router";
+import { getSessionFn } from "../server/auth";
+
+export const Route = createFileRoute("/_authed")({
+ beforeLoad: async () => {
+ const session = await getSessionFn();
+ if (!session) {
+ throw redirect({ to: "/login" });
+ }
+ return { session };
+ },
+});
+```
+
+**Components** (in `src/components/`):
+
+- `app-sidebar.tsx` — shadcn Sidebar with navigation links (Dashboard, Items)
+- `theme-toggle.tsx` — three-state theme toggle button
+- `user-nav.tsx` — user dropdown menu with sign-out action
+- `stat-card.tsx` — reusable stat card for the dashboard
+
+**See `references/server-functions.md`** for `createServerFn` patterns used in route loaders and mutations.
+
+### Step 7: CRUD Server Functions
+
+Create server functions for the items resource:
+
+| Function | Method | Purpose |
+|----------|--------|---------|
+| `getItems` | GET | List all items for current user |
+| `getItem` | GET | Get single item by ID |
+| `createItem` | POST | Create new item |
+| `updateItem` | POST | Update existing item |
+| `deleteItem` | POST | Delete item by ID |
+
+Each server function:
+1. Gets auth session (redirect if not authenticated)
+2. Creates per-request Drizzle client via `getDb()`
+3. Performs the database operation
+4. Returns typed data
+
+Route loaders call GET server functions. Mutations call POST server functions then `router.invalidate()` to refetch.
+
+### Step 8: Verify Locally
+
+```bash
+pnpm dev
+```
+
+Verification checklist:
+
+- [ ] App loads at http://localhost:3000
+- [ ] Register a new account (email/password)
+- [ ] Login and logout work
+- [ ] Dashboard page loads with stat cards
+- [ ] Create a new item via /items/new
+- [ ] Items list shows the new item
+- [ ] Edit item via /items/:id
+- [ ] Delete item from the list
+- [ ] Theme toggle cycles: light → dark → system
+- [ ] Sidebar collapses on mobile viewports
+- [ ] No console errors
+
+### Step 9: Deploy to Production
+
+```bash
+# Set production secrets
+openssl rand -hex 32 | npx wrangler secret put BETTER_AUTH_SECRET
+echo "https://PROJECT.SUBDOMAIN.workers.dev" | npx wrangler secret put BETTER_AUTH_URL
+echo "http://localhost:3000,https://PROJECT.SUBDOMAIN.workers.dev" | npx wrangler secret put TRUSTED_ORIGINS
+
+# If using Google OAuth
+echo "your-client-id" | npx wrangler secret put GOOGLE_CLIENT_ID
+echo "your-client-secret" | npx wrangler secret put GOOGLE_CLIENT_SECRET
+
+# Migrate remote database
+pnpm db:migrate:remote
+
+# Build and deploy
+pnpm build && npx wrangler deploy
+```
+
+**After first deploy**: Update `BETTER_AUTH_URL` with your actual Worker URL. Add production URL to Google OAuth redirect URIs: `https://your-app.workers.dev/api/auth/callback/google`.
+
+**See `references/deployment.md`** for the full production checklist and common mistakes.
+
+## Common Issues
+
+| Symptom | Fix |
+|---------|-----|
+| `env` is undefined in server function | Use `import { env } from "cloudflare:workers"` — must be inside request handler, not module scope |
+| D1 database not found | Check wrangler.jsonc `d1_databases` binding name matches code |
+| Auth redirect loop | `BETTER_AUTH_URL` must match actual URL exactly (protocol + domain, no trailing slash) |
+| Auth silently fails (redirects to home) | Set `TRUSTED_ORIGINS` secret with all valid URLs (comma-separated) |
+| Styles not loading in dev | Ensure `@tailwindcss/vite` plugin is in vite.config.ts |
+| SSR hydration mismatch | Add `suppressHydrationWarning` to `<html>` element |
+| Build fails on Cloudflare | Check `nodejs_compat` in compatibility_flags, `main` field in wrangler.jsonc |
+| Secrets not taking effect | `wrangler secret put` does NOT redeploy — run `npx wrangler deploy` after |
diff --git a/plugins/cloudflare/skills/tanstack-start/references/architecture.md b/plugins/cloudflare/skills/tanstack-start/references/architecture.md
new file mode 100644
index 00000000..52550dce
--- /dev/null
+++ b/plugins/cloudflare/skills/tanstack-start/references/architecture.md
@@ -0,0 +1,204 @@
+# Architecture Reference
+
+Complete structural blueprint for TanStack Start on Cloudflare Workers. Claude uses this to generate all project files from scratch.
+
+## Project File Tree
+
+```
+PROJECT_NAME/
+├── src/
+│ ├── routes/
+│ │ ├── __root.tsx # Root layout (HTML shell, theme, CSS import)
+│ │ ├── index.tsx # Landing / auth redirect
+│ │ ├── login.tsx # Login page
+│ │ ├── register.tsx # Register page
+│ │ ├── _authed.tsx # Auth guard layout route
+│ │ ├── _authed/
+│ │ │ ├── dashboard.tsx # Dashboard with stat cards
+│ │ │ ├── items.tsx # Items list table
+│ │ │ ├── items.$id.tsx # Edit item
+│ │ │ └── items.new.tsx # Create item
+│ │ └── api/
+│ │ └── auth/
+│ │ └── $.ts # better-auth API catch-all
+│ ├── components/
+│ │ ├── ui/ # shadcn/ui components (auto-installed)
+│ │ ├── app-sidebar.tsx # Navigation sidebar
+│ │ ├── theme-toggle.tsx # Light/dark/system toggle
+│ │ ├── user-nav.tsx # User dropdown menu
+│ │ └── stat-card.tsx # Dashboard stat card
+│ ├── db/
+│ │ ├── schema.ts # Drizzle schema (all tables)
+│ │ └── index.ts # Drizzle client factory
+│ ├── lib/
+│ │ ├── auth.server.ts # better-auth server config
+│ │ ├── auth.client.ts # better-auth React hooks
+│ │ └── utils.ts # cn() helper for shadcn/ui
+│ ├── server/
+│ │ └── functions.ts # Server functions (CRUD, auth checks)
+│ ├── styles/
+│ │ └── app.css # Tailwind v4 + shadcn/ui CSS variables
+│ ├── router.tsx # TanStack Router configuration
+│ ├── client.tsx # Client entry (hydrateRoot)
+│ ├── ssr.tsx # SSR entry
+│ └── routeTree.gen.ts # Auto-generated route tree (do not edit)
+├── drizzle/ # Generated migrations
+├── public/ # Static assets (favicon, etc.)
+├── vite.config.ts # Vite + Cloudflare + TanStack Start config
+├── wrangler.jsonc # Cloudflare Workers config
+├── drizzle.config.ts # Drizzle Kit config
+├── tsconfig.json # TypeScript config
+├── package.json # Dependencies + scripts
+├── .dev.vars # Local env vars (NOT committed)
+└── .gitignore
+```
+
+## Dependencies
+
+### Runtime
+
+```json
+{
+ "react": "^19.0.0",
+ "react-dom": "^19.0.0",
+ "@tanstack/react-router": "^1.120.0",
+ "@tanstack/react-start": "^1.120.0",
+ "drizzle-orm": "^0.38.0",
+ "better-auth": "^1.2.0",
+ "zod": "^3.24.0",
+ "class-variance-authority": "^0.7.0",
+ "clsx": "^2.1.0",
+ "tailwind-merge": "^3.0.0",
+ "lucide-react": "^0.480.0"
+}
+```
+
+### Dev
+
+```json
+{
+ "@cloudflare/vite-plugin": "^1.0.0",
+ "@tailwindcss/vite": "^4.0.0",
+ "@vitejs/plugin-react": "^4.4.0",
+ "tailwindcss": "^4.0.0",
+ "typescript": "^5.7.0",
+ "drizzle-kit": "^0.30.0",
+ "wrangler": "^4.0.0",
+ "tw-animate-css": "^1.2.0"
+}
+```
+
+### package.json scripts
+
+```json
+{
+ "dev": "vite",
+ "build": "vite build",
+ "preview": "vite preview",
+ "deploy": "wrangler deploy",
+ "db:generate": "drizzle-kit generate",
+ "db:migrate:local": "wrangler d1 migrations apply PROJECT_NAME-db --local",
+ "db:migrate:remote": "wrangler d1 migrations apply PROJECT_NAME-db --remote"
+}
+```
+
+## Vite Configuration
+
+Plugin order matters. Cloudflare must be first.
+
+```typescript
+// vite.config.ts
+import { defineConfig } from "vite";
+import { cloudflare } from "@cloudflare/vite-plugin";
+import { tanstackStart } from "@tanstack/react-start/plugin/vite";
+import tailwindcss from "@tailwindcss/vite";
+import viteReact from "@vitejs/plugin-react";
+
+export default defineConfig({
+ plugins: [
+ cloudflare({ viteEnvironment: { name: "ssr" } }),
+ tailwindcss(),
+ tanstackStart(),
+ viteReact(),
+ ],
+});
+```
+
+## Wrangler Configuration
+
+```jsonc
+// wrangler.jsonc
+{
+ "$schema": "node_modules/wrangler/config-schema.json",
+ "name": "PROJECT_NAME",
+ "compatibility_date": "2025-04-01",
+ "compatibility_flags": ["nodejs_compat"],
+ "main": "@tanstack/react-start/server-entry",
+ "account_id": "ACCOUNT_ID",
+ "d1_databases": [
+ {
+ "binding": "DB",
+ "database_name": "PROJECT_NAME-db",
+ "database_id": "DATABASE_ID",
+ "migrations_dir": "drizzle"
+ }
+ ]
+}
+```
+
+Key points:
+- `main` MUST be `"@tanstack/react-start/server-entry"` — this is the Nitro server entry
+- `nodejs_compat` is required (NOT `node_compat`)
+- `migrations_dir` tells wrangler where Drizzle outputs migrations
+- Add `account_id` to avoid interactive prompts during deploy
+
+## TypeScript Configuration
+
+```json
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "jsx": "react-jsx",
+ "strict": true,
+ "skipLibCheck": true,
+ "esModuleInterop": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "noEmit": true,
+ "paths": {
+ "@/*": ["./src/*"]
+ },
+ "types": ["@cloudflare/workers-types/2023-07-01"]
+ },
+ "include": ["src/**/*", "vite.config.ts"]
+}
+```
+
+## Environment Variables
+
+### Auth (required)
+
+| Variable | Purpose | Example |
+|----------|---------|---------|
+| `BETTER_AUTH_SECRET` | Session encryption key | `openssl rand -hex 32` |
+| `BETTER_AUTH_URL` | Auth base URL | `http://localhost:3000` (dev) |
+| `TRUSTED_ORIGINS` | Allowed origins (comma-separated) | `http://localhost:3000,https://app.workers.dev` |
+
+### Google OAuth (optional)
+
+| Variable | Purpose |
+|----------|---------|
+| `GOOGLE_CLIENT_ID` | From Google Cloud Console |
+| `GOOGLE_CLIENT_SECRET` | From Google Cloud Console |
+
+### .dev.vars template
+
+```
+BETTER_AUTH_SECRET=<generated-hex-32>
+BETTER_AUTH_URL=http://localhost:3000
+TRUSTED_ORIGINS=http://localhost:3000
+# GOOGLE_CLIENT_ID=
+# GOOGLE_CLIENT_SECRET=
+```
diff --git a/plugins/cloudflare/skills/tanstack-start/references/deployment.md b/plugins/cloudflare/skills/tanstack-start/references/deployment.md
new file mode 100644
index 00000000..1ddd0e6d
--- /dev/null
+++ b/plugins/cloudflare/skills/tanstack-start/references/deployment.md
@@ -0,0 +1,158 @@
+# Deployment Reference
+
+Production deployment checklist and common mistakes for TanStack Start on Cloudflare Workers.
+
+## Pre-Deploy Checklist
+
+- [ ] `wrangler.jsonc` has correct `account_id`
+- [ ] D1 database created and `database_id` in wrangler.jsonc
+- [ ] `main` field is `"@tanstack/react-start/server-entry"`
+- [ ] `nodejs_compat` in `compatibility_flags`
+- [ ] `.dev.vars` is in `.gitignore`
+- [ ] No hardcoded secrets in source code
+
+## Deploy Sequence
+
+### 1. Set Production Secrets
+
+```bash
+# Generate a DIFFERENT secret than dev
+openssl rand -hex 32 | npx wrangler secret put BETTER_AUTH_SECRET
+
+# Use your actual Worker URL (update after first deploy if needed)
+echo "https://PROJECT_NAME.SUBDOMAIN.workers.dev" | npx wrangler secret put BETTER_AUTH_URL
+
+# Include all valid origins
+echo "http://localhost:3000,https://PROJECT_NAME.SUBDOMAIN.workers.dev" | npx wrangler secret put TRUSTED_ORIGINS
+```
+
+### 2. Google OAuth (if using)
+
+```bash
+echo "your-client-id" | npx wrangler secret put GOOGLE_CLIENT_ID
+echo "your-client-secret" | npx wrangler secret put GOOGLE_CLIENT_SECRET
+```
+
+Add production redirect URI in Google Cloud Console:
+```
+https://PROJECT_NAME.SUBDOMAIN.workers.dev/api/auth/callback/google
+```
+
+### 3. Migrate Remote Database
+
+```bash
+pnpm db:migrate:remote
+```
+
+**Always run migrations on BOTH local AND remote** before testing.
+
+### 4. Build and Deploy
+
+```bash
+pnpm build && npx wrangler deploy
+```
+
+### 5. Post-Deploy Verification
+
+- [ ] App loads at production URL
+- [ ] Auth login/register works
+- [ ] Database operations work (create, read, update, delete)
+- [ ] Theme persists across page loads
+- [ ] No console errors
+
+## Custom Domain (Optional)
+
+After initial deploy:
+
+1. Add custom domain in Cloudflare Dashboard → Workers → your worker → Triggers → Custom Domains
+2. Update secrets:
+ ```bash
+ echo "https://yourdomain.com" | npx wrangler secret put BETTER_AUTH_URL
+ echo "http://localhost:3000,https://yourdomain.com" | npx wrangler secret put TRUSTED_ORIGINS
+ ```
+3. Update Google OAuth redirect URI to use custom domain
+4. Redeploy: `npx wrangler deploy`
+
+## Common Mistakes
+
+### 1. TRUSTED_ORIGINS Not Set
+
+**Symptom**: User signs in but gets silently redirected to homepage. Auth cookie not accepted.
+
+**Fix**: Set the TRUSTED_ORIGINS secret with ALL valid URLs (comma-separated, no spaces):
+```bash
+echo "http://localhost:3000,https://your-app.workers.dev" | npx wrangler secret put TRUSTED_ORIGINS
+```
+
+### 2. BETTER_AUTH_URL Mismatch
+
+**Symptom**: Auth works locally but fails in production. Redirect loops or "invalid callback" errors.
+
+**Fix**: The URL must match the actual production URL exactly — including `https://`, no trailing slash. After first deploy, check the actual Worker URL and update:
+```bash
+echo "https://actual-url.workers.dev" | npx wrangler secret put BETTER_AUTH_URL
+npx wrangler deploy # Must redeploy after setting secret
+```
+
+### 3. Secrets Set But Not Deployed
+
+**Symptom**: Changed a secret but the app still uses the old value.
+
+**Fix**: `wrangler secret put` does NOT automatically redeploy. Always run `npx wrangler deploy` after setting secrets.
+
+### 4. Database Migrations Not Applied to Remote
+
+**Symptom**: API returns 500 errors. "Table not found" or "no such table" in logs.
+
+**Fix**: Run migrations on remote:
+```bash
+pnpm db:migrate:remote
+```
+
+### 5. Google OAuth Redirect URI Missing
+
+**Symptom**: "Error 400: redirect_uri_mismatch" when signing in with Google.
+
+**Fix**: Add your production URL to Google Cloud Console → APIs & Services → Credentials → your OAuth client → Authorised redirect URIs:
+```
+https://your-app.workers.dev/api/auth/callback/google
+```
+
+### 6. Wrong Vite Plugin Order
+
+**Symptom**: Build fails or SSR doesn't work. Cryptic Vite errors about "environment not found".
+
+**Fix**: Plugin order in `vite.config.ts` must be: `cloudflare()` → `tailwindcss()` → `tanstackStart()` → `viteReact()`. Cloudflare MUST be first.
+
+### 7. Module-Level Env Access
+
+**Symptom**: `env` is undefined, or "Cannot access env outside of request context".
+
+**Fix**: Never import and use `env` from `cloudflare:workers` at module level. Always access inside server function handlers, route loaders, or API route handlers.
+
+```typescript
+// ❌ Module level — fails
+import { env } from "cloudflare:workers";
+const db = drizzle(env.DB);
+
+// ✅ Inside handler — works
+export const getItems = createServerFn({ method: "GET" }).handler(async () => {
+ const db = drizzle(env.DB); // env accessed during request
+});
+```
+
+### 8. Auth on Server Function Instead of API Route
+
+**Symptom**: better-auth endpoints return 404 or auth flow doesn't work.
+
+**Fix**: better-auth needs a catch-all API route (`createAPIFileRoute`), not a server function. It handles its own routing internally:
+
+```typescript
+// src/routes/api/auth/$.ts
+import { createAPIFileRoute } from "@tanstack/react-start/api";
+
+export const APIRoute = createAPIFileRoute("/api/auth/$")({
+ GET: ({ request }) => getAuth().handler(request),
+ POST: ({ request }) => getAuth().handler(request),
+});
+```
diff --git a/plugins/cloudflare/skills/tanstack-start/references/server-functions.md b/plugins/cloudflare/skills/tanstack-start/references/server-functions.md
new file mode 100644
index 00000000..13995dbd
--- /dev/null
+++ b/plugins/cloudflare/skills/tanstack-start/references/server-functions.md
@@ -0,0 +1,212 @@
+# Server Functions Reference
+
+Patterns for `createServerFn` on Cloudflare Workers with D1, Drizzle, and better-auth.
+
+## Core Pattern
+
+```typescript
+import { createServerFn } from "@tanstack/react-start";
+import { getDb } from "../db";
+
+export const getItems = createServerFn({ method: "GET" }).handler(async () => {
+ const db = getDb(); // Per-request Drizzle client
+ return db.select().from(items).all();
+});
+```
+
+**CRITICAL**: Create the Drizzle client inside the handler, NOT at module level. The `env` import from `cloudflare:workers` is only available during request handling.
+
+## Env Access on Cloudflare
+
+```typescript
+// ✅ CORRECT — inside handler or called from handler
+import { env } from "cloudflare:workers";
+
+export const getItems = createServerFn({ method: "GET" }).handler(async () => {
+ const db = drizzle(env.DB, { schema }); // env available here
+ return db.select().from(items).all();
+});
+
+// ❌ WRONG — module level
+import { env } from "cloudflare:workers";
+const db = drizzle(env.DB, { schema }); // env is undefined here!
+```
+
+## Input Validation
+
+Use `.inputValidator()` with Zod or inline validator:
+
+```typescript
+import { z } from "zod";
+
+export const createItem = createServerFn({ method: "POST" })
+ .inputValidator(
+ z.object({
+ name: z.string().min(1),
+ description: z.string().optional(),
+ })
+ )
+ .handler(async ({ data }) => {
+ const db = getDb();
+ const id = crypto.randomUUID();
+ await db.insert(items).values({ id, ...data, createdAt: Date.now() });
+ return { id };
+ });
+```
+
+## Protected Server Functions
+
+Check auth session inside the handler. Throw redirect for unauthenticated users:
+
+```typescript
+import { redirect } from "@tanstack/react-router";
+import { getAuth } from "../lib/auth.server";
+
+async function requireSession(request?: Request) {
+ const auth = getAuth();
+ const session = await auth.api.getSession({ headers: request?.headers ?? new Headers() });
+ if (!session) {
+ throw redirect({ to: "/login" });
+ }
+ return session;
+}
+
+// Reusable auth check as a server function
+export const getSessionFn = createServerFn({ method: "GET" }).handler(
+ async ({ request }) => {
+ const auth = getAuth();
+ const session = await auth.api.getSession({
+ headers: request.headers,
+ });
+ return session;
+ }
+);
+
+export const getItems = createServerFn({ method: "GET" }).handler(
+ async ({ request }) => {
+ const session = await requireSession(request);
+ const db = getDb();
+ return db
+ .select()
+ .from(items)
+ .where(eq(items.userId, session.user.id))
+ .all();
+ }
+);
+```
+
+## Route Loader Pattern
+
+Use server functions in route `loader` for data fetching:
+
+```typescript
+import { createFileRoute } from "@tanstack/react-router";
+import { getItems } from "../../server/functions";
+
+export const Route = createFileRoute("/_authed/items")({
+ loader: () => getItems(),
+ component: ItemsPage,
+});
+
+function ItemsPage() {
+ const items = Route.useLoaderData();
+
+ return (
+ <div>
+ {items.map((item) => (
+ <div key={item.id}>{item.name}</div>
+ ))}
+ </div>
+ );
+}
+```
+
+## Route beforeLoad (Auth Guard)
+
+Use `beforeLoad` on layout routes to protect groups of routes:
+
+```typescript
+import { createFileRoute, redirect } from "@tanstack/react-router";
+import { getSessionFn } from "../server/functions";
+
+export const Route = createFileRoute("/_authed")({
+ beforeLoad: async () => {
+ const session = await getSessionFn();
+ if (!session) {
+ throw redirect({ to: "/login" });
+ }
+ return { session };
+ },
+});
+```
+
+Child routes access the session via `useRouteContext()`:
+
+```typescript
+function DashboardPage() {
+ const { session } = Route.useRouteContext();
+ return <h1>Welcome, {session.user.name}!</h1>;
+}
+```
+
+## Mutation + Router Invalidation
+
+After mutations, invalidate the router to refetch loader data:
+
+```typescript
+function CreateItemForm() {
+ const router = useRouter();
+
+ const handleSubmit = async (data: NewItem) => {
+ await createItem({ data });
+ router.invalidate(); // Refetches all active loaders
+ router.navigate({ to: "/items" });
+ };
+
+ return <form onSubmit={...}>...</form>;
+}
+```
+
+## Type Safety
+
+Use Drizzle's type inference for server function input/output:
+
+```typescript
+import { items } from "../db/schema";
+import type { InferSelectModel, InferInsertModel } from "drizzle-orm";
+
+type Item = InferSelectModel<typeof items>;
+type NewItem = InferInsertModel<typeof items>;
+
+export const getItems = createServerFn({ method: "GET" }).handler(
+ async (): Promise<Item[]> => {
+ const db = getDb();
+ return db.select().from(items).all();
+ }
+);
+```
+
+## Error Handling
+
+Server functions can throw errors that propagate to the client:
+
+```typescript
+export const getItem = createServerFn({ method: "GET" })
+ .inputValidator(z.object({ id: z.string() }))
+ .handler(async ({ data }) => {
+ const db = getDb();
+ const item = await db
+ .select()
+ .from(items)
+ .where(eq(items.id, data.id))
+ .get();
+
+ if (!item) {
+ throw new Error("Item not found");
+ }
+
+ return item;
+ });
+```
+
+For auth failures, always use `throw redirect()` — not error responses.