Isomorphic-by-default principle, environment boundary functions (createServerFn, createServerOnlyFn, createClientOnlyFn, createIsomorphicFn), ClientOnly component, useHydrated hook, import protection, dead code elimination, environment variable safety (VITE_ prefix, process.env).
Written by TanStack and published in TanStack/router under the MIT license. Treq shows it unchanged except for heading levels and links to files on GitHub.
Understanding where code runs is fundamental to TanStack Start. This skill covers the isomorphic execution model and how to control environment boundaries.
CRITICAL: ALL code in TanStack Start is isomorphic by default — it runs in BOTH server and client bundles. Route loaders run on BOTH server (during SSR) AND client (during navigation). Server-only operations MUST use
createServerFn. CRITICAL: Module-levelprocess.envaccess is wrong on two axes — security (values leak into the client bundle) AND runtime correctness (on Cloudflare Workers and other edge runtimes, env is injected per-request, so module-level reads evaluate toundefinedeven on the server). Read env inside.handler()or another per-request function, never at module scope. CRITICAL:VITE_prefixed environment variables are exposed to the client bundle. Server secrets must NOT have theVITE_prefix. CRITICAL: Relative URLs belong to browser-only code. An isomorphic loader also runs during SSR, wherefetch('/api/...')may have no base URL. Call a server function from the loader, or keep the fetch inside an explicit environment boundary.
| API | Use Case | Client Behavior | Server Behavior |
|---|---|---|---|
createServerFn() |
RPC calls, data mutations | Network request to server | Direct execution |
createServerOnlyFn(fn) |
Utility functions | Throws error | Direct execution |
createClientOnlyFn(fn) |
Browser utilities | Direct execution | Throws error |
createIsomorphicFn() |
Different impl per env | Uses .client() impl |
Uses .server() impl |
<ClientOnly> |
Browser-only components | Renders children | Renders fallback |
useHydrated() |
Hydration-dependent logic | true after hydration |
false |
import '@tanstack/<fw>-start/server-only' |
Mark whole file server-only | Import denied | Allowed |
import '@tanstack/<fw>-start/client-only' |
Mark whole file client-only | Allowed | Import denied |
The primary way to run server-only code. On the client, calls become fetch requests:
// Use @tanstack/<framework>-start for your framework (react, solid, vue)
import { createServerFn } from '@tanstack/react-start'
const fetchUser = createServerFn().handler(async () => {
const secret = process.env.API_SECRET // safe — server only
return await db.users.find()
})
// Client calls this via network request
const user = await fetchUser()
For utility functions that must never run on client:
// Use @tanstack/<framework>-start for your framework (react, solid, vue)
import { createServerOnlyFn } from '@tanstack/react-start'
const getSecret = createServerOnlyFn(() => process.env.DATABASE_URL)
// Server: returns the value
// Client: THROWS an error
// Use @tanstack/<framework>-start for your framework (react, solid, vue)
import { createClientOnlyFn } from '@tanstack/react-start'
const saveToStorage = createClientOnlyFn((key: string, value: string) => {
localStorage.setItem(key, value)
})
// Use @tanstack/<framework>-router for your framework (react, solid, vue)
import { ClientOnly } from '@tanstack/react-router'
function Analytics() {
return (
<ClientOnly fallback={null}>
<GoogleAnalyticsScript />
</ClientOnly>
)
}
// Use @tanstack/<framework>-router for your framework (react, solid, vue)
import { useHydrated } from '@tanstack/react-router'
function TimeZoneDisplay() {
const hydrated = useHydrated()
const timeZone = hydrated
? Intl.DateTimeFormat().resolvedOptions().timeZone
: 'UTC'
return <div>Your timezone: {timeZone}</div>
}
Behavior: SSR → false, first client render → false, after hydration → true (stays true).
// Use @tanstack/<framework>-start for your framework (react, solid, vue)
import { createIsomorphicFn } from '@tanstack/react-start'
const getDeviceInfo = createIsomorphicFn()
.server(() => ({ type: 'server', platform: process.platform }))
.client(() => ({ type: 'client', userAgent: navigator.userAgent }))
Experimental.
The .server.* and .client.* filename suffixes (e.g. db.server.ts) opt a file into Start's import protection — it can't be imported from the wrong environment. When you can't or don't want to rename the file, add a side-effect import at the top of the file to apply the same protection by marker:
// src/lib/secrets.ts (filename can't be *.server.ts)
import '@tanstack/react-start/server-only'
// (or @tanstack/solid-start/server-only, @tanstack/vue-start/server-only)
export function getApiKey() {
return process.env.API_KEY
}
// src/lib/storage.ts
import '@tanstack/react-start/client-only'
// (or @tanstack/solid-start/client-only, @tanstack/vue-start/client-only)
export function savePreferences(prefs: Record<string, string>) {
localStorage.setItem('prefs', JSON.stringify(prefs))
}
Rules:
error in production builds and mock in dev. The mock returns a recursive Proxy so dev keeps running while you fix the import graph.Pick the right tool:
*.server.ts filename or import '@tanstack/<fw>-start/server-only'.createIsomorphicFn().client(...).server(...).createServerOnlyFn / createClientOnlyFn.<ClientOnly> or useHydrated().Access any variable via process.env:
const connectDb = createServerFn().handler(async () => {
const url = process.env.DATABASE_URL // no prefix needed
return createConnection(url)
})
Only VITE_ prefixed variables are available:
// Framework-specific component type (React.ReactNode, JSX.Element, etc.)
function ApiProvider({ children }: { children: React.ReactNode }) {
const apiUrl = import.meta.env.VITE_API_URL // available
// import.meta.env.DATABASE_URL → undefined (security)
return (
<ApiContext.Provider value={{ apiUrl }}>{children}</ApiContext.Provider>
)
}
If you need server-side variables on the client without VITE_ prefix, pass them through a server function:
const getRuntimeVar = createServerFn({ method: 'GET' }).handler(() => {
return process.env.MY_RUNTIME_VAR
})
export const Route = createFileRoute('/')({
loader: async () => {
const foo = await getRuntimeVar()
return { foo }
},
component: () => {
const { foo } = Route.useLoaderData()
return <div>{foo}</div>
},
})
// src/env.d.ts
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_APP_NAME: string
readonly VITE_API_URL: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
declare global {
namespace NodeJS {
interface ProcessEnv {
readonly DATABASE_URL: string
readonly JWT_SECRET: string
}
}
}
export {}
// WRONG — loader runs on BOTH server and client
export const Route = createFileRoute('/dashboard')({
loader: async () => {
const secret = process.env.API_SECRET // LEAKED to client
return fetch(`https://api.example.com/data`, {
headers: { Authorization: secret },
})
},
})
// CORRECT — use createServerFn
const getData = createServerFn({ method: 'GET' }).handler(async () => {
const secret = process.env.API_SECRET
return fetch(`https://api.example.com/data`, {
headers: { Authorization: secret },
})
})
export const Route = createFileRoute('/dashboard')({
loader: () => getData(),
})
Module-level process.env reads are wrong for two reasons, not one:
undefined even on the server. The bug only surfaces at deploy time.// WRONG — leaks to client AND is undefined on Workers
const apiKey = process.env.SECRET_KEY
export function fetchData() {
/* uses apiKey, which is undefined under Worker SSR */
}
// CORRECT — read per-request, inside the handler
const fetchData = createServerFn({ method: 'GET' }).handler(async () => {
const apiKey = process.env.SECRET_KEY
return fetch(url, { headers: { Authorization: apiKey } })
})
The same rule applies to middleware .server() callbacks, server-route handlers, and any function that runs per request — read env there, not at the top of the file.
# WRONG — exposed to client bundle
VITE_SECRET_API_KEY=sk_live_xxx
# CORRECT — no prefix for server secrets
SECRET_API_KEY=sk_live_xxx
# CORRECT — VITE_ only for public client values
VITE_APP_NAME=My App
// WRONG — different content server vs client
function CurrentTime() {
return <div>{new Date().toLocaleString()}</div>
}
// CORRECT — consistent rendering
function CurrentTime() {
const [time, setTime] = useState<string>()
useEffect(() => {
setTime(new Date().toLocaleString())
}, [])
return <div>{time || 'Loading...'}</div>
}
Server-Only (createServerFn / createServerOnlyFn):
Client-Only (createClientOnlyFn / <ClientOnly>):
Isomorphic (default / createIsomorphicFn):
Claude Code and Codex keep each installed skill's name and description in context. When a request matches the description, the agent loads the full SKILL.md. You can also run it yourself: type /execution-model in Claude Code or $execution-model in Codex.
Copy the execution-model folder into .claude/skills/ in your project. To use it in every project, copy it into ~/.claude/skills/ instead.
git clone --depth 1 https://github.com/TanStack/router.git /tmp/TanStack-router
mkdir -p .claude/skills
cp -r /tmp/TanStack-router/packages/start-client-core/skills/start-core/execution-model .claude/skills/
Codex reads skills from .agents/skills/ in your repository, and from ~/.agents/skills/ for every repository. It detects new skills on its own. Restart Codex if execution-model does not appear.
git clone --depth 1 https://github.com/TanStack/router.git /tmp/TanStack-router
mkdir -p .agents/skills
cp -r /tmp/TanStack-router/packages/start-client-core/skills/start-core/execution-model .agents/skills/
Open Settings and select the Skills tab. The tab appears when Skills installation is on under Settings → Feature Preview. Search for execution-model and choose Install….
Install for repository writes the skill under .treq/skills/ in the current repository. Install for application makes it available to every repository on this machine. Each new workspace gets a copy in .claude/skills/ and .agents/skills/, so Claude Code and Codex both find it. See Installing Skills from the Library.
execution-model ships one file, SKILL.md, shown above.