>-
TanStack Start
Full-stack React framework with SSR, server functions, and Vite bundling.
Project Setup
New project:
pnpm create cloudflare@latest my-app --framework=tanstack-start -y --no-deploy
Existing app: See references/migration.md for converting React/Vite apps.
Critical Configuration
vite.config.ts
import { defineConfig } from 'vite'
import tsConfigPaths from 'vite-tsconfig-paths'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import viteReact from '@vitejs/plugin-react'
export default defineConfig({
plugins: [
tsConfigPaths(),
tanstackStart(),
viteReact(), // MUST come AFTER tanstackStart
],
})
tsconfig.json gotcha
Do NOT enable verbatimModuleSyntax - it leaks server bundles into client bundles.
Server Functions
See references/server-functions.md for complete guide.
⚠️ Critical: Route loaders run on server for initial SSR, but run on CLIENT during navigation. Always wrap server code in
createServerFn()to ensure it runs server-side.
When to use what (Cloudflare Workers):
| Use Case | Solution |
|---|---|
| Server code in route loaders | createServerFn() |
| Server code from client event handlers | API routes (server.handlers) work best |
| Access Cloudflare bindings | import { env } from 'cloudflare:workers' |
createServerFn - for loaders:
import { createServerFn } from '@tanstack/react-start'
export const getData = createServerFn().handler(async () => {
return { data: process.env.SECRET } // Server-only
})
API routes - for client event handlers:
// routes/api/users.ts
export const Route = createFileRoute('/api/users')({
server: {
handlers: {
POST: async ({ request }) => {
const body = await request.json()
return Response.json(await db.users.create(body))
},
},
},
})
// In component: fetch('/api/users', { method: 'POST', body: JSON.stringify(data) })
Key APIs:
createServerFn()- Server-only functions for loadersserver.handlers- API routes for client event handlerscreateMiddleware({ type: 'function' })- Reusable middleware@tanstack/react-start/server:getRequestHeaders(),setResponseHeader(),getCookies()
Routing
See references/routing.md for complete patterns.
File conventions in src/routes/:
| Pattern | Route |
|---|---|
index.tsx |
/ |
posts.$postId.tsx |
/posts/:postId |
_layout.tsx |
Layout (no URL) |
__root.tsx |
Root layout (required) |
import { createFileRoute } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
const getPost = createServerFn()
.handler(async () => await db.post.findFirst())
export const Route = createFileRoute('/posts/$postId')({
loader: ({ params }) => getPost({ data: params.postId }),
component: () => {
const post = Route.useLoaderData()
return <h1>{post.title}</h1>
},
})
Cloudflare Deployment
See references/cloudflare-deployment.md for complete guide.
pnpm add -D @cloudflare/vite-plugin wrangler
vite.config.ts - add cloudflare plugin:
import { cloudflare } from '@cloudflare/vite-plugin'
// Add to plugins: cloudflare({ viteEnvironment: { name: 'ssr' } })
wrangler.jsonc:
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "my-app",
"compatibility_date": "<CURRENT_DATE>", // Use today's YYYY-MM-DD
"compatibility_flags": ["nodejs_compat"],
"main": "@tanstack/react-start/server-entry",
"observability": { "enabled": true }
}
Access Cloudflare bindings in server functions:
import { env } from 'cloudflare:workers'
const value = await env.MY_KV.get('key')
Static Prerendering (v1.138.0+):
tanstackStart({ prerender: { enabled: true } })
TanStack Query Integration
See references/query-integration.md for SSR setup.
pnpm add @tanstack/react-query @tanstack/react-router-ssr-query
// Preload in loaders, consume with useSuspenseQuery
loader: ({ context }) => context.queryClient.ensureQueryData(myQueryOptions)
Better-Auth Integration
See references/better-auth.md for complete guide.
⚠️ Critical: Use
createFileRoutewithserver.handlers, NOT the legacycreateAPIFileRoute.
Mount the auth handler at /src/routes/api/auth/$.ts:
import { auth } from '@/lib/auth'
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/api/auth/$')({
server: {
handlers: {
GET: ({ request }) => auth.handler(request),
POST: ({ request }) => auth.handler(request),
},
},
})
Auth config with tanstackStartCookies plugin:
import { betterAuth } from "better-auth"
import { tanstackStartCookies } from "better-auth/tanstack-start"
export const auth = betterAuth({
// ...your config
plugins: [tanstackStartCookies()] // MUST be last plugin
})
Protect routes with middleware:
import { createMiddleware } from "@tanstack/react-start"
import { getRequestHeaders } from "@tanstack/react-start/server"
import { auth } from "./auth"
export const authMiddleware = createMiddleware().server(
async ({ next }) => {
const session = await auth.api.getSession({ headers: getRequestHeaders() })
if (!session) throw redirect({ to: "/login" })
return next()
}
)
// In route:
export const Route = createFileRoute('/dashboard')({
server: { middleware: [authMiddleware] },
component: Dashboard,
})
GitHub Actions Auto-Deploy
See references/github-actions-deploy.md for CI/CD setup with preview deployments.
You Might Also Like
Related Skills

cache-components
Expert guidance for Next.js Cache Components and Partial Prerendering (PPR). **PROACTIVE ACTIVATION**: Use this skill automatically when working in Next.js projects that have `cacheComponents: true` in their next.config.ts/next.config.js. When this config is detected, proactively apply Cache Components patterns and best practices to all React Server Component implementations. **DETECTION**: At the start of a session in a Next.js project, check for `cacheComponents: true` in next.config. If enabled, this skill's patterns should guide all component authoring, data fetching, and caching decisions. **USE CASES**: Implementing 'use cache' directive, configuring cache lifetimes with cacheLife(), tagging cached data with cacheTag(), invalidating caches with updateTag()/revalidateTag(), optimizing static vs dynamic content boundaries, debugging cache issues, and reviewing Cache Component implementations.
vercel
component-refactoring
Refactor high-complexity React components in Dify frontend. Use when `pnpm analyze-component --json` shows complexity > 50 or lineCount > 300, when the user asks for code splitting, hook extraction, or complexity reduction, or when `pnpm analyze-component` warns to refactor before testing; avoid for simple/well-structured components, third-party wrappers, or when the user explicitly wants testing without refactoring.
langgenius
web-artifacts-builder
Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use for complex artifacts requiring state management, routing, or shadcn/ui components - not for simple single-file HTML/JSX artifacts.
anthropics
frontend-design
Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications (examples include websites, landing pages, dashboards, React components, HTML/CSS layouts, or when styling/beautifying any web UI). Generates creative, polished code and UI design that avoids generic AI aesthetics.
anthropics
react-modernization
Upgrade React applications to latest versions, migrate from class components to hooks, and adopt concurrent features. Use when modernizing React codebases, migrating to React Hooks, or upgrading to latest React versions.
wshobson
tailwind-design-system
Build scalable design systems with Tailwind CSS v4, design tokens, component libraries, and responsive patterns. Use when creating component libraries, implementing design systems, or standardizing UI patterns.
wshobson