diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000000..8f4e24c72a
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,171 @@
+# AGENTS.md
+
+## Project overview
+
+TanStack Router is a type-safe router with built-in caching and URL state management for React and Solid applications. This monorepo contains two main products:
+
+- **TanStack Router** - Core routing library with type-safe navigation, search params, and path params
+- **TanStack Start** - Full-stack framework built on top of TanStack Router
+
+## Setup commands
+
+- Install deps: `pnpm install`
+- Setup e2e testing: `pnpm exec playwright install`
+- Build packages: `pnpm build` (affected) or `pnpm build:all` (force all)
+- Start dev server: `pnpm dev`
+- Run tests: `pnpm test`
+
+## Code style
+
+- TypeScript strict mode with extensive type safety
+- Framework-agnostic core logic separated from React/Solid bindings
+- Type-safe routing with search params and path params
+- Use workspace protocol for internal dependencies (`workspace:*`)
+
+## Dev environment tips
+
+- This is a pnpm workspace monorepo with packages organized by functionality
+- Nx provides caching, affected testing, targeting, and parallel execution for efficiency
+- Use `npx nx show projects` to list all available packages
+- Target specific packages: `npx nx run @tanstack/react-router:test:unit`
+- Target multiple packages: `npx nx run-many --target=test:eslint --projects=@tanstack/history,@tanstack/router-core`
+- Run affected tests only: `npx nx affected --target=test:unit`
+- Exclude patterns: `npx nx run-many --target=test:unit --exclude="examples/**,e2e/**"`
+- Navigate to examples and run `pnpm dev` to test changes: `cd examples/react/basic && pnpm dev`
+- **Granular Vitest testing within packages:**
+ - Navigate first: `cd packages/react-router`
+ - Specific files: `npx vitest run tests/link.test.tsx tests/Scripts.test.tsx`
+ - Test patterns: `npx vitest run tests/ClientOnly.test.tsx -t "should render fallback"`
+ - Name patterns: `npx vitest run -t "navigation"` (all tests with "navigation" in name)
+ - Exclude patterns: `npx vitest run --exclude="**/*link*" tests/`
+ - List tests: `npx vitest list tests/link.test.tsx` or `npx vitest list` (all)
+ - Through nx: `npx nx run @tanstack/react-router:test:unit -- tests/ClientOnly.test.tsx`
+- **Available test targets per package:** `test:unit`, `test:types`, `test:eslint`, `test:build`, `test:perf`, `build`
+- **Testing strategy:** Package level (nx) → File level (vitest) → Test level (-t flag) → Pattern level (exclude)
+
+## Testing instructions
+
+- **Critical**: Always run unit and type tests during development - do not proceed if they fail
+- **Test types:** `pnpm test:unit`, `pnpm test:types`, `pnpm test:eslint`, `pnpm test:e2e`, `pnpm test:build`
+- **Full CI suite:** `pnpm test:ci`
+- **Fix formatting:** `pnpm prettier:write`
+- **Efficient targeted testing workflow:**
+ 1. **Affected only:** `npx nx affected --target=test:unit` (compares to main branch)
+ 2. **Specific packages:** `npx nx run @tanstack/react-router:test:unit`
+ 3. **Specific files:** `cd packages/react-router && npx vitest run tests/link.test.tsx`
+ 4. **Specific patterns:** `npx vitest run tests/link.test.tsx -t "preloading"`
+- **Pro tips:**
+ - Use `npx vitest list` to explore available tests before running
+ - Use `-t "pattern"` to focus on specific functionality during development
+ - Use `--exclude` patterns to skip unrelated tests
+ - Combine nx package targeting with vitest file targeting for maximum precision
+- **Example workflow:** `npx nx run @tanstack/react-router:test:unit` → `cd packages/react-router && npx vitest run tests/link.test.tsx` → `npx vitest run tests/link.test.tsx -t "preloading"`
+
+## PR instructions
+
+- Always run `pnpm test:eslint`, `pnpm test:types`, and `pnpm test:unit` before committing
+- Test changes in relevant example apps: `cd examples/react/basic && pnpm dev`
+- Update corresponding documentation in `docs/` directory when adding features
+- Add or update tests for any code changes
+- Use internal docs links relative to `docs/` folder (e.g., `./guide/data-loading`)
+
+## Package structure
+
+**Core packages:**
+
+- `packages/router-core/` - Framework-agnostic core router logic
+- `packages/react-router/`, `packages/solid-router/` - React/Solid bindings and components
+- `packages/history/` - Browser history management
+
+**Tooling:**
+
+- `packages/router-cli/` - CLI tools for code generation
+- `packages/router-generator/` - Route generation utilities
+- `packages/router-plugin/` - Universal bundler plugins (Vite, Webpack, ESBuild, Rspack)
+- `packages/virtual-file-routes/` - Virtual file routing system
+
+**Developer experience:**
+
+- `packages/router-devtools/`, `packages/*-router-devtools/` - Development tools
+- `packages/eslint-plugin-router/` - ESLint rules for router
+
+**Validation adapters:**
+
+- `packages/zod-adapter/`, `packages/valibot-adapter/`, `packages/arktype-adapter/`
+
+**Start framework:**
+
+- `packages/*-start/`, `packages/start-*/` - Full-stack framework packages
+
+**Examples & testing:**
+
+- `examples/react/`, `examples/solid/` - Example applications (test changes here)
+- `e2e/` - End-to-end tests (requires Playwright)
+- `docs/router/`, `docs/start/` - Documentation with React/Solid subdirectories
+
+**Dependencies:** Uses workspace protocol (`workspace:*`) - core → framework → start packages
+
+## Common development tasks
+
+**Adding new routes:**
+
+- Use file-based routing in `src/routes/` directories
+- Or use code-based routing with route definitions
+- Run route generation with CLI tools
+
+**Testing changes:**
+
+- Build packages: `pnpm build` or `pnpm dev` (watch mode)
+- Run example apps to test functionality
+- Use devtools for debugging router state
+
+**Documentation updates:**
+
+- Update relevant docs in `docs/` directory
+- Ensure examples reflect documentation changes
+- Test documentation links and references
+- Use relative links to `docs/` folder format
+
+## Framework-specific notes
+
+**React:**
+
+- Uses React Router components and hooks
+- Supports React Server Components (RSC)
+- Examples include React Query integration
+- Package: `@tanstack/react-router`
+
+**Solid:**
+
+- Uses Solid Router components and primitives
+- Supports Solid Start for full-stack applications
+- Examples include Solid Query integration
+- Package: `@tanstack/solid-router`
+
+## Environment requirements
+
+- **Node.js** - Required for development
+- **pnpm** - Package manager (required for workspace features)
+- **Playwright** - Required for e2e tests (`pnpm exec playwright install`)
+
+## Key architecture patterns
+
+- **Type Safety**: Extensive TypeScript for type-safe routing
+- **Framework Agnostic**: Core logic separated from framework bindings
+- **Plugin Architecture**: Universal bundler plugins using unplugin
+- **File-based Routing**: Support for both code-based and file-based routing
+- **Search Params**: First-class support for type-safe search parameters
+
+## Development workflow
+
+1. **Setup**: `pnpm install` and `pnpm exec playwright install`
+2. **Build**: `pnpm build:all` or `pnpm dev` for watch mode
+3. **Test**: Make changes and run relevant tests (use nx for targeted testing)
+4. **Examples**: Navigate to examples and run `pnpm dev` to test changes
+5. **Quality**: Run `pnpm test:eslint`, `pnpm test:types`, `pnpm test:unit` before committing
+
+## References
+
+- **Documentation**: https://tanstack.com/router
+- **GitHub**: https://github.com/TanStack/router
+- **Discord Community**: https://discord.com/invite/WrRKjPJ
diff --git a/AI.md b/AI.md
deleted file mode 100644
index 5860ac0188..0000000000
--- a/AI.md
+++ /dev/null
@@ -1,348 +0,0 @@
-# AI.md
-
-This file provides guidance to AI assistants when working with the TanStack Router codebase.
-
-## Project Overview
-
-TanStack Router is a type-safe router with built-in caching and URL state management for React and Solid applications. This monorepo contains two main products:
-
-- **TanStack Router** - Core routing library with type-safe navigation, search params, and path params
-- **TanStack Start** - Full-stack framework built on top of TanStack Router
-
-## Repository Structure
-
-### Core Packages
-
-**Router Core:**
-
-- `router-core/` - Framework-agnostic core router logic
-- `react-router/` - React bindings and components
-- `solid-router/` - Solid bindings and components
-- `history/` - Browser history management
-
-**Tooling:**
-
-- `router-cli/` - CLI tools for code generation
-- `router-generator/` - Route generation utilities
-- `router-plugin/` - Universal bundler plugins (Vite, Webpack, ESBuild, Rspack)
-- `router-vite-plugin/` - Vite-specific plugin wrapper
-- `virtual-file-routes/` - Virtual file routing system
-
-**Developer Experience:**
-
-- `router-devtools/` - Router development tools
-- `router-devtools-core/` - Core devtools functionality
-- `react-router-devtools/` - React-specific devtools
-- `solid-router-devtools/` - Solid-specific devtools
-- `eslint-plugin-router/` - ESLint rules for router
-
-**Adapters:**
-
-- `zod-adapter/` - Zod validation adapter
-- `valibot-adapter/` - Valibot validation adapter
-- `arktype-adapter/` - ArkType validation adapter
-
-**Start Framework:**
-
-- `start/` - Core start framework
-- `react-start/` - React Start framework
-- `solid-start/` - Solid Start framework
-- `start-*` packages - Various start framework utilities
-
-### Documentation
-
-Documentation is organized in `docs/`:
-
-- `docs/router/` - Router-specific documentation
-- `docs/start/` - Start framework documentation
-- Each has `framework/react/` and `framework/solid/` subdirectories
-
-### Examples
-
-Extensive examples in `examples/`:
-
-- `examples/react/` - React router examples
-- `examples/solid/` - Solid router examples
-- Examples range from basic usage to complex applications
-
-### Testing
-
-- `e2e/` - End-to-end tests organized by framework
-- Individual packages have `tests/` directories
-- Uses Playwright for e2e testing
-
-## Essential Commands
-
-### Development
-
-```bash
-# Install dependencies
-pnpm install
-
-# Build all packages (affected only)
-pnpm build
-
-# Build all packages (force all)
-pnpm build:all
-
-# Development mode with watch
-pnpm dev
-
-# Run all tests
-pnpm test
-
-# Run tests in CI mode
-pnpm test:ci
-```
-
-### Testing
-
-```bash
-# Run unit tests
-pnpm test:unit
-
-# Run e2e tests
-pnpm test:e2e
-
-# Run type checking
-pnpm test:types
-
-# Run linting
-pnpm test:eslint
-
-# Run formatting check
-pnpm test:format
-
-# Fix formatting
-pnpm prettier:write
-```
-
-### Targeted Testing with Nx
-
-```bash
-# Target specific package
-npx nx run @tanstack/react-router:test:unit
-npx nx run @tanstack/router-core:test:types
-npx nx run @tanstack/history:test:eslint
-
-# Target multiple packages
-npx nx run-many --target=test:eslint --projects=@tanstack/history,@tanstack/router-core
-
-# Run affected tests only (compares to main branch)
-npx nx affected --target=test:unit
-
-# Exclude certain patterns
-npx nx run-many --target=test:unit --exclude="examples/**,e2e/**"
-
-# List all available projects
-npx nx show projects
-```
-
-### Granular Vitest Testing
-
-For even more precise test targeting within packages:
-
-```bash
-# Navigate to package directory first
-cd packages/react-router
-
-# Run specific test files
-npx vitest run tests/link.test.tsx
-npx vitest run tests/ClientOnly.test.tsx tests/Scripts.test.tsx
-
-# Run tests by name pattern
-npx vitest run tests/ClientOnly.test.tsx -t "should render fallback"
-npx vitest run -t "navigation" # Run all tests with "navigation" in name
-
-# Exclude test patterns
-npx vitest run --exclude="**/*link*" tests/
-
-# List available tests
-npx vitest list tests/link.test.tsx
-npx vitest list # List all tests in package
-
-# Through nx (passes args to vitest)
-npx nx run @tanstack/react-router:test:unit -- tests/ClientOnly.test.tsx
-npx nx run @tanstack/react-router:test:unit -- tests/link.test.tsx tests/Scripts.test.tsx
-```
-
-### Example Development
-
-```bash
-# Navigate to an example
-cd examples/react/basic
-
-# Run the example
-pnpm dev
-```
-
-## Development Workflow
-
-1. **Setup**: `pnpm install` and `pnpm exec playwright install`
-2. **Build**: `pnpm build:all` or `pnpm dev` for watch mode
-3. **Test**: Make changes and run relevant tests (use nx for targeted testing)
-4. **Examples**: Navigate to examples and run `pnpm dev` to test changes
-
-### Nx-Powered Development
-
-This repository uses Nx for efficient task execution:
-
-- **Caching**: Nx caches task results - repeated commands are faster
-- **Affected**: Only runs tasks for changed code (`nx affected`)
-- **Targeting**: Run tasks for specific packages or combinations
-- **Parallel Execution**: Multiple tasks run in parallel automatically
-- **Dependency Management**: Nx handles build order and dependencies
-
-## Code Organization
-
-### Monorepo Structure
-
-This is a pnpm workspace with packages organized by functionality:
-
-- Core packages provide the fundamental router logic
-- Framework packages provide React/Solid bindings
-- Tool packages provide development utilities
-- Start packages provide full-stack framework capabilities
-
-### Key Patterns
-
-- **Type Safety**: Extensive use of TypeScript for type-safe routing
-- **Framework Agnostic**: Core logic separated from framework bindings
-- **Plugin Architecture**: Universal bundler plugins using unplugin
-- **File-based Routing**: Support for both code-based and file-based routing
-- **Search Params**: First-class support for type-safe search parameters
-
-## Documentation Guidelines
-
-- **Internal Links**: Always write relative to `docs/` folder (e.g., `./guide/data-loading`)
-- **Examples**: Each major feature should have corresponding examples
-- **Type Safety**: Document TypeScript patterns and type inference
-- **Framework Specific**: Separate docs for React and Solid when needed
-
-## Critical Quality Checks
-
-**During prompt-driven development, always run unit and type tests to ensure validity. If either of these fail, do not stop or proceed (unless you have repeatedly failed and need human intervention).**
-
-**You can run these (or the ones you are working on) after each big change:**
-
-```bash
-pnpm test:eslint # Linting
-pnpm test:types # TypeScript compilation
-pnpm test:unit # Unit tests
-pnpm test:build # Build verification
-```
-
-**For comprehensive testing:**
-
-```bash
-pnpm test:ci # Full CI test suite
-pnpm test:e2e # End-to-end tests
-```
-
-**For targeted testing (recommended for efficiency):**
-
-```bash
-# Test only affected packages
-npx nx affected --target=test:unit
-npx nx affected --target=test:types
-npx nx affected --target=test:eslint
-
-# Test specific packages you're working on
-npx nx run @tanstack/react-router:test:unit
-npx nx run @tanstack/router-core:test:types
-
-# Test specific files/functionality you're working on
-cd packages/react-router
-npx vitest run tests/link.test.tsx -t "preloading"
-npx vitest run tests/useNavigate.test.tsx tests/useParams.test.tsx
-```
-
-**Pro Tips:**
-
-- Use `npx vitest list` to explore available tests before running
-- Use `-t "pattern"` to focus on specific functionality during development
-- Use `--exclude` patterns to skip unrelated tests
-- Combine nx package targeting with vitest file targeting for maximum precision
-
-## Package Dependencies
-
-The monorepo uses workspace dependencies extensively:
-
-- Core packages are dependencies of framework packages
-- Framework packages are dependencies of start packages
-- All packages use workspace protocol (`workspace:*`)
-
-## Environment Setup
-
-- **Node.js**: Required for development
-- **pnpm**: Package manager (required for workspace features)
-- **Playwright**: Required for e2e tests (`pnpm exec playwright install`)
-
-## Common Tasks
-
-### Adding New Routes
-
-- Use file-based routing in `src/routes/` directories
-- Or use code-based routing with route definitions
-- Run route generation with CLI tools
-
-### Testing Changes
-
-- Build packages: `pnpm build` or `pnpm dev`
-- Run example apps to test functionality
-- Use devtools for debugging router state
-
-**Available Test Targets per Package:**
-
-- `test:unit` - Unit tests with Vitest
-- `test:types` - TypeScript compilation across multiple TS versions
-- `test:eslint` - Linting with ESLint
-- `test:build` - Build verification (publint + attw)
-- `test:perf` - Performance benchmarks
-- `build` - Package building
-
-**Granular Test Targeting Strategies:**
-
-1. **Package Level**: Use nx to target specific packages
-2. **File Level**: Use vitest directly to target specific test files
-3. **Test Level**: Use vitest `-t` flag to target specific test names
-4. **Pattern Level**: Use vitest exclude patterns to skip certain tests
-
-Example workflow:
-
-```bash
-# 1. Test specific package
-npx nx run @tanstack/react-router:test:unit
-
-# 2. Test specific files within package
-cd packages/react-router && npx vitest run tests/link.test.tsx
-
-# 3. Test specific functionality
-npx vitest run tests/link.test.tsx -t "preloading"
-```
-
-### Documentation Updates
-
-- Update relevant docs in `docs/` directory
-- Ensure examples reflect documentation
-- Test documentation links and references
-
-## Framework-Specific Notes
-
-### React
-
-- Uses React Router components and hooks
-- Supports React Server Components (RSC)
-- Examples include React Query integration
-
-### Solid
-
-- Uses Solid Router components and primitives
-- Supports Solid Start for full-stack applications
-- Examples include Solid Query integration
-
-## References
-
-- Main Documentation: https://tanstack.com/router
-- GitHub Repository: https://github.com/TanStack/router
-- Discord Community: https://discord.com/invite/WrRKjPJ
diff --git a/docs/router/framework/react/guide/navigation.md b/docs/router/framework/react/guide/navigation.md
index 26b8a02ce3..3305a61bf3 100644
--- a/docs/router/framework/react/guide/navigation.md
+++ b/docs/router/framework/react/guide/navigation.md
@@ -28,7 +28,7 @@ type ToOptions<
TTo extends string = '',
> = {
// `from` is an optional route ID or path. If it is not supplied, only absolute paths will be auto-completed and type-safe. It's common to supply the route.fullPath of the origin route you are rendering from for convenience. If you don't know the origin route, leave this empty and work with absolute paths or unsafe relative paths.
- from: string
+ from?: string
// `to` can be an absolute route path or a relative path from the `from` option to a valid route path. ⚠️ Do not interpolate path params, hash or search params into the `to` options. Use the `params`, `search`, and `hash` options instead.
to: string
// `params` is either an object of path params to interpolate into the `to` option or a function that supplies the previous params and allows you to return new ones. This is the only way to interpolate dynamic parameters into the final URL. Depending on the `from` and `to` route, you may need to supply none, some or all of the path params. TypeScript will notify you of the required params if there are any.
@@ -183,7 +183,7 @@ Keep in mind that normally dynamic segment params are `string` values, but they
By default, all links are absolute unless a `from` route path is provided. This means that the above link will always navigate to the `/about` route regardless of what route you are currently on.
-If you want to make a link that is relative to the current route, you can provide a `from` route path:
+Relative links can be combined with a `from` route path. If a from route path isn't provided, relative paths default to the current active location.
```tsx
const postIdRoute = createRoute({
@@ -201,9 +201,9 @@ As seen above, it's common to provide the `route.fullPath` as the `from` route p
### Special relative paths: `"."` and `".."`
-Quite often you might want to reload the current location, for example, to rerun the loaders on the current and/or parent routes, or maybe there was a change in search parameters. This can be achieved by specifying a `to` route path of `"."` which will reload the current location. This is only applicable to the current location, and hence any `from` route path specified is ignored.
+Quite often you might want to reload the current location or another `from` path, for example, to rerun the loaders on the current and/or parent routes, or maybe navigate back to a parent route. This can be achieved by specifying a `to` route path of `"."` which will reload the current location or provided `from` path.
-Another common need is to navigate one route back relative to the current location or some other matched route in the current tree. By specifying a `to` route path of `".."` navigation will be resolved to either the first parent route preceding the current location or, if specified, preceding the `"from"` route path.
+Another common need is to navigate one route back relative to the current location or another path. By specifying a `to` route path of `".."` navigation will be resolved to the first parent route preceding the current location.
```tsx
export const Route = createFileRoute('/posts/$postId')({
@@ -214,7 +214,14 @@ function PostComponent() {
return (
Reload the current route of /posts/$postId
- Navigate to /posts
+ Navigate back to /posts
+ // the below are all equivalent
+ Navigate back to /posts
+
+ Navigate back to /posts
+
+ // the below are all equivalent
+ Navigate to root
Navigate to root
diff --git a/docs/start/config.json b/docs/start/config.json
index 02a44b30ac..b28ad4f7e9 100644
--- a/docs/start/config.json
+++ b/docs/start/config.json
@@ -30,8 +30,20 @@
"to": "framework/react/build-from-scratch"
},
{
- "label": "Learn the Basics",
- "to": "framework/react/learn-the-basics"
+ "label": "Routing",
+ "to": "framework/react/routing"
+ },
+ {
+ "label": "Execution Model",
+ "to": "framework/react/execution-model"
+ },
+ {
+ "label": "Code Execution Patterns",
+ "to": "framework/react/code-execution-patterns"
+ },
+ {
+ "label": "Environment Variables",
+ "to": "framework/react/environment-variables"
},
{
"label": "Server Functions",
@@ -57,10 +69,26 @@
"label": "SPA Mode",
"to": "framework/react/spa-mode"
},
+ {
+ "label": "Static Prerendering",
+ "to": "framework/react/static-prerendering"
+ },
+ {
+ "label": "Server Entry Point",
+ "to": "framework/react/server-entry-point"
+ },
+ {
+ "label": "Client Entry Point",
+ "to": "framework/react/client-entry-point"
+ },
{
"label": "Hosting",
"to": "framework/react/hosting"
},
+ {
+ "label": "Authentication Overview",
+ "to": "framework/react/authentication-overview"
+ },
{
"label": "Authentication",
"to": "framework/react/authentication"
@@ -73,10 +101,6 @@
"label": "Observability",
"to": "framework/react/observability"
},
- {
- "label": "Static Prerendering",
- "to": "framework/react/static-prerendering"
- },
{
"label": "Path Aliases",
"to": "framework/react/path-aliases"
@@ -111,8 +135,20 @@
"to": "framework/solid/build-from-scratch"
},
{
- "label": "Learn the Basics",
- "to": "framework/solid/learn-the-basics"
+ "label": "Routing",
+ "to": "framework/solid/routing"
+ },
+ {
+ "label": "Execution Model",
+ "to": "framework/solid/execution-model"
+ },
+ {
+ "label": "Code Execution Patterns",
+ "to": "framework/solid/code-execution-patterns"
+ },
+ {
+ "label": "Environment Variables",
+ "to": "framework/solid/environment-variables"
},
{
"label": "Server Functions",
@@ -138,10 +174,26 @@
"label": "SPA Mode",
"to": "framework/solid/spa-mode"
},
+ {
+ "label": "Static Prerendering",
+ "to": "framework/solid/static-prerendering"
+ },
+ {
+ "label": "Server Entry Point",
+ "to": "framework/solid/server-entry-point"
+ },
+ {
+ "label": "Client Entry Point",
+ "to": "framework/solid/client-entry-point"
+ },
{
"label": "Hosting",
"to": "framework/solid/hosting"
},
+ {
+ "label": "Authentication Overview",
+ "to": "framework/solid/authentication-overview"
+ },
{
"label": "Authentication",
"to": "framework/solid/authentication"
@@ -155,16 +207,12 @@
"to": "framework/solid/observability"
},
{
- "label": "Static Prerendering",
- "to": "framework/solid/static-prerendering"
+ "label": "Path Aliases",
+ "to": "framework/solid/path-aliases"
},
{
"label": "Tailwind CSS Integration",
"to": "framework/solid/tailwind-integration"
- },
- {
- "label": "Path Aliases",
- "to": "framework/solid/path-aliases"
}
]
}
@@ -242,6 +290,15 @@
"to": "framework/react/reading-writing-file"
}
]
+ },
+ {
+ "label": "solid",
+ "children": [
+ {
+ "label": "Reading and Writing a File",
+ "to": "framework/solid/reading-writing-file"
+ }
+ ]
}
]
}
diff --git a/docs/start/framework/react/authentication-overview.md b/docs/start/framework/react/authentication-overview.md
new file mode 100644
index 0000000000..466f85a9a6
--- /dev/null
+++ b/docs/start/framework/react/authentication-overview.md
@@ -0,0 +1,239 @@
+---
+id: authentication-overview
+title: Authentication
+---
+
+## Authentication vs Authorization
+
+- **Authentication**: Who is this user? (Login/logout, identity verification)
+- **Authorization**: What can this user do? (Permissions, roles, access control)
+
+## Architecture Overview
+
+### Full-Stack Authentication Model
+
+**Server-Side (Secure)**
+
+- Session storage and validation
+- User credential verification
+- Database operations
+- Token generation/verification
+- Protected API endpoints
+
+**Client-Side (Public)**
+
+- Authentication state management
+- Route protection logic
+- Login/logout user interface
+- Redirect handling
+
+**Isomorphic (Both)**
+
+- Route loaders checking auth state
+- Shared validation logic
+- User profile data access
+
+### Session Management Patterns
+
+**HTTP-Only Cookies (Recommended)**
+
+- Most secure approach - not accessible via JavaScript
+- Automatic browser handling
+- Built-in CSRF protection with `sameSite`
+- Best for traditional web applications
+
+**JWT Tokens**
+
+- Stateless authentication
+- Good for API-first applications
+- Requires careful handling to avoid XSS vulnerabilities
+- Consider refresh token rotation
+
+**Server-Side Sessions**
+
+- Centralized session control
+- Easy to revoke sessions
+- Requires session storage (database, Redis)
+- Good for applications requiring immediate session control
+
+### Route Protection Architecture
+
+**Layout Route Pattern (Recommended)**
+
+- Protect entire route subtrees with parent layout routes
+- Centralized authentication logic
+- Automatic protection for all child routes
+- Clean separation of authenticated vs public routes
+
+**Component-Level Protection**
+
+- Conditional rendering within components
+- More granular control over UI states
+- Good for mixed public/private content on same route
+- Requires careful handling to prevent layout shifts
+
+**Server Function Guards**
+
+- Server-side validation before executing sensitive operations
+- Works alongside route-level protection
+- Essential for API security regardless of client-side protection
+
+### State Management Patterns
+
+**Server-Driven State (Recommended)**
+
+- Authentication state sourced from server on each request
+- Always up-to-date with server state
+- Works seamlessly with SSR
+- Best security - server is source of truth
+
+**Context-Based State**
+
+- Client-side authentication state management
+- Good for third-party auth providers (Auth0, Firebase)
+- Requires careful synchronization with server state
+- Consider for highly interactive client-first applications
+
+**Hybrid Approach**
+
+- Initial state from server, client-side updates
+- Balance between security and UX
+- Periodic server-side validation
+
+## Authentication Options
+
+### 🏢 Partner Solutions
+
+- **[WorkOS](https://workos.com)**
+- **[Clerk](https://clerk.dev)**
+
+### 🛠️ DIY Authentication
+
+Build your own authentication system using TanStack Start's server functions and session management:
+
+- **Full Control**: Complete customization over authentication flow
+- **Server Functions**: Secure authentication logic on the server
+- **Session Management**: Built-in session handling with HTTP-only cookies
+- **Type Safety**: End-to-end type safety for authentication state
+
+### 🌐 Other Excellent Options
+
+**Open Source & Community Solutions:**
+
+- **[Better Auth](https://www.better-auth.com/)** - Modern, TypeScript-first authentication library
+- **[Auth.js](https://authjs.dev/)** (formerly NextAuth.js) - Popular authentication library for React
+
+**Hosted Services:**
+
+- **[Supabase Auth](https://supabase.com/auth)** - Open source Firebase alternative with built-in auth
+- **[Auth0](https://auth0.com/)** - Established authentication platform with extensive features
+- **[Firebase Auth](https://firebase.google.com/docs/auth)** - Google's authentication service
+
+## Partner Solutions
+
+### WorkOS - Enterprise Authentication
+
+
+
+
+
+
+
+
+
+- **Single Sign-On (SSO)** - SAML, OIDC, and OAuth integrations
+- **Directory Sync** - SCIM provisioning with Active Directory and Google Workspace
+- **Multi-factor Authentication** - Enterprise-grade security options
+- **Compliance Ready** - SOC 2, GDPR, and CCPA compliant
+
+[Visit WorkOS →](https://workos.com/) | [View example →](https://github.com/TanStack/router/tree/main/examples/react/start-workos)
+
+### Clerk - Complete Authentication Platform
+
+
+
+
+
+
+
+
+
+- **Ready-to-use UI Components** - Sign-in, sign-up, user profile, and organization management
+- **Social Logins** - Google, GitHub, Discord, and 20+ providers
+- **Multi-factor Authentication** - SMS, TOTP, and backup codes
+- **Organizations & Teams** - Built-in support for team-based applications
+
+[Visit Clerk →](https://go.clerk.com/wOwHtuJ) | [Sign up free →](https://go.clerk.com/PrSDXti) | [View example →](https://github.com/TanStack/router/tree/main/examples/react/start-clerk-basic)
+
+## Examples
+
+**Partner Solutions:**
+
+- [Clerk Integration](https://github.com/TanStack/router/tree/main/examples/react/start-clerk-basic)
+- [WorkOS Integration](https://github.com/TanStack/router/tree/main/examples/react/start-workos)
+
+**DIY Implementations:**
+
+- [Basic Auth with Prisma](https://github.com/TanStack/router/tree/main/examples/react/start-basic-auth)
+- [Supabase Auth](https://github.com/TanStack/router/tree/main/examples/react/start-supabase-basic)
+
+**Client-Side Examples:**
+
+- [Basic Authentication](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes)
+- [Firebase Auth](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes-firebase)
+
+## Architecture Decision Guide
+
+### Choosing an Authentication Approach
+
+**Partner Solutions:**
+
+- Focus on your core business logic
+- Enterprise features (SSO, compliance)
+- Managed security and updates
+- Pre-built UI components
+
+**OSS Solutions:**
+
+- Community-driven development
+- Specific customizations
+- Self-hosted solutions
+- Avoid vendor lock-in
+
+**DIY Implementation:**
+
+- Complete control over the auth flow
+- Custom security requirements
+- Specific business logic needs
+- Full ownership of authentication data
+
+### Security Considerations
+
+- Use HTTPS in production
+- Use HTTP-only cookies when possible
+- Validate all inputs on the server
+- Keep secrets in server-only functions
+- Implement rate limiting for auth endpoints
+- Use CSRF protection for form submissions
+
+## Next Steps
+
+- **Partner solutions** → [Clerk](https://go.clerk.com/wOwHtuJ) or [WorkOS](https://workos.com/)
+- **DIY implementation** → [Authentication Guide](./authentication.md)
+- **Examples** → [Working implementations](https://github.com/TanStack/router/tree/main/examples/react)
+
+## Resources
+
+**Implementation Guides:**
+
+- [Authentication Patterns](./authentication.md)
+- [Router Authentication Guide](../../router/framework/react/guide/authenticated-routes.md)
+
+**Foundation Concepts:**
+
+- [Execution Model](./execution-model.md)
+- [Server Functions](./server-functions.md)
+
+**Step-by-Step Tutorials:**
+
+- [Router How-to Guides](../../router/framework/react/how-to/README.md#authentication)
diff --git a/docs/start/framework/react/authentication.md b/docs/start/framework/react/authentication.md
index 5846ef5b72..a49ae409ba 100644
--- a/docs/start/framework/react/authentication.md
+++ b/docs/start/framework/react/authentication.md
@@ -3,32 +3,605 @@ id: authentication
title: Authentication
---
-
+This guide covers authentication patterns and shows how to implement your own authentication system with TanStack Start.
-Authentication is the process of verifying the identity of a user. This is a critical part of any application that requires users to log in or access protected resources. TanStack Start provides the necessary full-stack APIs to implement authentication in your application.
+> **📋 Before You Start:** Check our [Authentication Overview](./authentication-overview.md) for all available options including partner solutions and hosted services.
-## What should I use?
+## Authentication Approaches
-TanStack Start is **designed to work with any authentication provider**, so if you already have an authentication provider or strategy in mind, you can use either find an existing example or implement your own authentication logic using the full-stack APIs provided by TanStack Start.
+You have several options for authentication in your TanStack Start application:
-That said, authentication is not something to be taken lightly. After much vetting, usage and reviewing on our end, we highly recommend using [Clerk](https://clerk.dev) for the best possible authentication experience. Clerk provides a full suite of authentication APIs and UI components that make it easy to implement authentication in your application and provide a seamless user experience.
+**Hosted Solutions:**
-## What is Clerk?
+1. **[Clerk](https://clerk.dev)** - Complete authentication platform with UI components
+2. **[WorkOS](https://workos.com)** - Enterprise-focused with SSO and compliance features
+3. **[Better Auth](https://www.better-auth.com/)** - Open-source TypeScript library
-
-
-
-
-
-
-
+**DIY Implementation Benefits:**
-Clerk is a modern authentication platform that provides a full suite of authentication APIs and UI components to help you implement authentication in your application. Clerk is designed to be easy to use and provides a seamless user experience. With Clerk, you can implement authentication in your application in minutes and provide your users with a secure and reliable authentication experience.
+- **Full Control**: Complete customization over authentication flow
+- **No Vendor Lock-in**: Own your authentication logic and user data
+- **Custom Requirements**: Implement specific business logic or compliance needs
+- **Cost Control**: No per-user pricing or usage limits
-- To learn more about Clerk, visit the [Clerk website](https://go.clerk.com/wOwHtuJ)
-- To sign up, visit the [Clerk dashboard](https://go.clerk.com/PrSDXti)
-- To get started with Clerk, check out our [official Start + Clerk examples!](https://github.com/TanStack/router/tree/main/examples/react/start-clerk-basic)
+Authentication involves many considerations including password security, session management, rate limiting, CSRF protection, and various attack vectors.
-## Documentation & APIs
+## Core Concepts
-Documentation for implementing your own authentication logic with TanStack Start is coming soon! In the meantime, you can check out any of the `-auth` prefixed [examples](https://github.com/TanStack/router/tree/main/examples/react) for a starting point.
+### Authentication vs Authorization
+
+- **Authentication**: Who is this user? (Login/logout)
+- **Authorization**: What can this user do? (Permissions/roles)
+
+TanStack Start provides the tools for both through server functions, sessions, and route protection.
+
+## Essential Building Blocks
+
+### 1. Server Functions for Authentication
+
+Server functions handle sensitive authentication logic securely on the server:
+
+```tsx
+import { createServerFn } from '@tanstack/react-start'
+import { redirect } from '@tanstack/react-router'
+
+// Login server function
+export const loginFn = createServerFn({ method: 'POST' })
+ .validator((data: { email: string; password: string }) => data)
+ .handler(async ({ data }) => {
+ // Verify credentials (replace with your auth logic)
+ const user = await authenticateUser(data.email, data.password)
+
+ if (!user) {
+ return { error: 'Invalid credentials' }
+ }
+
+ // Create session
+ const session = await useAppSession()
+ await session.update({
+ userId: user.id,
+ email: user.email,
+ })
+
+ // Redirect to protected area
+ throw redirect({ to: '/dashboard' })
+ })
+
+// Logout server function
+export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => {
+ const session = await useAppSession()
+ await session.clear()
+ throw redirect({ to: '/' })
+})
+
+// Get current user
+export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler(
+ async () => {
+ const session = await useAppSession()
+ const userId = session.get('userId')
+
+ if (!userId) {
+ return null
+ }
+
+ return await getUserById(userId)
+ },
+)
+```
+
+### 2. Session Management
+
+TanStack Start provides secure HTTP-only cookie sessions:
+
+```tsx
+// utils/session.ts
+import { useSession } from '@tanstack/react-start'
+
+type SessionData = {
+ userId?: string
+ email?: string
+ role?: string
+}
+
+export function useAppSession() {
+ return useSession({
+ // Session configuration
+ name: 'app-session',
+ password: process.env.SESSION_SECRET!, // At least 32 characters
+ // Optional: customize cookie settings
+ cookie: {
+ secure: process.env.NODE_ENV === 'production',
+ sameSite: 'lax',
+ httpOnly: true,
+ },
+ })
+}
+```
+
+### 3. Authentication Context
+
+Share authentication state across your application:
+
+```tsx
+// contexts/auth.tsx
+import { createContext, useContext, ReactNode } from 'react'
+import { useServerFn } from '@tanstack/react-start'
+import { getCurrentUserFn } from '../server/auth'
+
+type User = {
+ id: string
+ email: string
+ role: string
+}
+
+type AuthContextType = {
+ user: User | null
+ isLoading: boolean
+ refetch: () => void
+}
+
+const AuthContext = createContext(undefined)
+
+export function AuthProvider({ children }: { children: ReactNode }) {
+ const { data: user, isLoading, refetch } = useServerFn(getCurrentUserFn)
+
+ return (
+
+ {children}
+
+ )
+}
+
+export function useAuth() {
+ const context = useContext(AuthContext)
+ if (!context) {
+ throw new Error('useAuth must be used within AuthProvider')
+ }
+ return context
+}
+```
+
+### 4. Route Protection
+
+Protect routes using `beforeLoad`:
+
+```tsx
+// routes/_authed.tsx - Layout route for protected pages
+import { createFileRoute, redirect } from '@tanstack/react-router'
+import { getCurrentUserFn } from '../server/auth'
+
+export const Route = createFileRoute('/_authed')({
+ beforeLoad: async ({ location }) => {
+ const user = await getCurrentUserFn()
+
+ if (!user) {
+ throw redirect({
+ to: '/login',
+ search: { redirect: location.href },
+ })
+ }
+
+ // Pass user to child routes
+ return { user }
+ },
+})
+```
+
+```tsx
+// routes/_authed/dashboard.tsx - Protected route
+import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/_authed/dashboard')({
+ component: DashboardComponent,
+})
+
+function DashboardComponent() {
+ const { user } = Route.useRouteContext()
+
+ return (
+
+
Welcome, {user.email}!
+ {/* Dashboard content */}
+
+ )
+}
+```
+
+## Implementation Patterns
+
+### Basic Email/Password Authentication
+
+```tsx
+// server/auth.ts
+import bcrypt from 'bcryptjs'
+import { createServerFn } from '@tanstack/react-start'
+
+// User registration
+export const registerFn = createServerFn({ method: 'POST' })
+ .validator((data: { email: string; password: string; name: string }) => data)
+ .handler(async ({ data }) => {
+ // Check if user exists
+ const existingUser = await getUserByEmail(data.email)
+ if (existingUser) {
+ return { error: 'User already exists' }
+ }
+
+ // Hash password
+ const hashedPassword = await bcrypt.hash(data.password, 12)
+
+ // Create user
+ const user = await createUser({
+ email: data.email,
+ password: hashedPassword,
+ name: data.name,
+ })
+
+ // Create session
+ const session = await useAppSession()
+ await session.update({ userId: user.id })
+
+ return { success: true, user: { id: user.id, email: user.email } }
+ })
+
+async function authenticateUser(email: string, password: string) {
+ const user = await getUserByEmail(email)
+ if (!user) return null
+
+ const isValid = await bcrypt.compare(password, user.password)
+ return isValid ? user : null
+}
+```
+
+### Role-Based Access Control (RBAC)
+
+```tsx
+// utils/auth.ts
+export const roles = {
+ USER: 'user',
+ ADMIN: 'admin',
+ MODERATOR: 'moderator',
+} as const
+
+type Role = (typeof roles)[keyof typeof roles]
+
+export function hasPermission(userRole: Role, requiredRole: Role): boolean {
+ const hierarchy = {
+ [roles.USER]: 0,
+ [roles.MODERATOR]: 1,
+ [roles.ADMIN]: 2,
+ }
+
+ return hierarchy[userRole] >= hierarchy[requiredRole]
+}
+
+// Protected route with role check
+export const Route = createFileRoute('/_authed/admin/')({
+ beforeLoad: async ({ context }) => {
+ if (!hasPermission(context.user.role, roles.ADMIN)) {
+ throw redirect({ to: '/unauthorized' })
+ }
+ },
+})
+```
+
+### Social Authentication Integration
+
+```tsx
+// Example with OAuth providers
+export const authProviders = {
+ google: {
+ clientId: process.env.GOOGLE_CLIENT_ID!,
+ redirectUri: `${process.env.APP_URL}/auth/google/callback`,
+ },
+ github: {
+ clientId: process.env.GITHUB_CLIENT_ID!,
+ redirectUri: `${process.env.APP_URL}/auth/github/callback`,
+ },
+}
+
+export const initiateOAuthFn = createServerFn({ method: 'POST' })
+ .validator((data: { provider: 'google' | 'github' }) => data)
+ .handler(async ({ data }) => {
+ const provider = authProviders[data.provider]
+ const state = generateRandomState()
+
+ // Store state in session for CSRF protection
+ const session = await useAppSession()
+ await session.update({ oauthState: state })
+
+ // Generate OAuth URL
+ const authUrl = generateOAuthUrl(provider, state)
+
+ throw redirect({ href: authUrl })
+ })
+```
+
+### Password Reset Flow
+
+```tsx
+// Password reset request
+export const requestPasswordResetFn = createServerFn({ method: 'POST' })
+ .validator((data: { email: string }) => data)
+ .handler(async ({ data }) => {
+ const user = await getUserByEmail(data.email)
+ if (!user) {
+ // Don't reveal if email exists
+ return { success: true }
+ }
+
+ const token = generateSecureToken()
+ const expires = new Date(Date.now() + 60 * 60 * 1000) // 1 hour
+
+ await savePasswordResetToken(user.id, token, expires)
+ await sendPasswordResetEmail(user.email, token)
+
+ return { success: true }
+ })
+
+// Password reset confirmation
+export const resetPasswordFn = createServerFn({ method: 'POST' })
+ .validator((data: { token: string; newPassword: string }) => data)
+ .handler(async ({ data }) => {
+ const resetToken = await getPasswordResetToken(data.token)
+
+ if (!resetToken || resetToken.expires < new Date()) {
+ return { error: 'Invalid or expired token' }
+ }
+
+ const hashedPassword = await bcrypt.hash(data.newPassword, 12)
+ await updateUserPassword(resetToken.userId, hashedPassword)
+ await deletePasswordResetToken(data.token)
+
+ return { success: true }
+ })
+```
+
+## Security Best Practices
+
+### 1. Password Security
+
+```tsx
+// Use strong hashing (bcrypt, scrypt, or argon2)
+import bcrypt from 'bcryptjs'
+
+const saltRounds = 12 // Adjust based on your security needs
+const hashedPassword = await bcrypt.hash(password, saltRounds)
+```
+
+### 2. Session Security
+
+```tsx
+// Use secure session configuration
+export function useAppSession() {
+ return useSession({
+ name: 'app-session',
+ password: process.env.SESSION_SECRET!, // 32+ characters
+ cookie: {
+ secure: process.env.NODE_ENV === 'production', // HTTPS only in production
+ sameSite: 'lax', // CSRF protection
+ httpOnly: true, // XSS protection
+ maxAge: 7 * 24 * 60 * 60, // 7 days
+ },
+ })
+}
+```
+
+### 3. Rate Limiting
+
+```tsx
+// Simple in-memory rate limiting (use Redis in production)
+const loginAttempts = new Map()
+
+export const rateLimitLogin = (ip: string): boolean => {
+ const now = Date.now()
+ const attempts = loginAttempts.get(ip)
+
+ if (!attempts || now > attempts.resetTime) {
+ loginAttempts.set(ip, { count: 1, resetTime: now + 15 * 60 * 1000 }) // 15 min
+ return true
+ }
+
+ if (attempts.count >= 5) {
+ return false // Too many attempts
+ }
+
+ attempts.count++
+ return true
+}
+```
+
+### 4. Input Validation
+
+```tsx
+import { z } from 'zod'
+
+const loginSchema = z.object({
+ email: z.string().email().max(255),
+ password: z.string().min(8).max(100),
+})
+
+export const loginFn = createServerFn({ method: 'POST' })
+ .validator((data) => loginSchema.parse(data))
+ .handler(async ({ data }) => {
+ // data is now validated
+ })
+```
+
+## Testing Authentication
+
+### Unit Testing Server Functions
+
+```tsx
+// __tests__/auth.test.ts
+import { describe, it, expect, beforeEach } from 'vitest'
+import { loginFn } from '../server/auth'
+
+describe('Authentication', () => {
+ beforeEach(async () => {
+ await setupTestDatabase()
+ })
+
+ it('should login with valid credentials', async () => {
+ const result = await loginFn({
+ data: { email: 'test@example.com', password: 'password123' },
+ })
+
+ expect(result.error).toBeUndefined()
+ expect(result.user).toBeDefined()
+ })
+
+ it('should reject invalid credentials', async () => {
+ const result = await loginFn({
+ data: { email: 'test@example.com', password: 'wrongpassword' },
+ })
+
+ expect(result.error).toBe('Invalid credentials')
+ })
+})
+```
+
+### Integration Testing
+
+```tsx
+// __tests__/auth-flow.test.tsx
+import { render, screen, fireEvent, waitFor } from '@testing-library/react'
+import { RouterProvider, createMemoryHistory } from '@tanstack/react-router'
+import { router } from '../router'
+
+describe('Authentication Flow', () => {
+ it('should redirect to login when accessing protected route', async () => {
+ const history = createMemoryHistory()
+ history.push('/dashboard') // Protected route
+
+ render()
+
+ await waitFor(() => {
+ expect(screen.getByText('Login')).toBeInTheDocument()
+ })
+ })
+})
+```
+
+## Common Patterns
+
+### Loading States
+
+```tsx
+function LoginForm() {
+ const [isLoading, setIsLoading] = useState(false)
+ const loginMutation = useServerFn(loginFn)
+
+ const handleSubmit = async (data: LoginData) => {
+ setIsLoading(true)
+ try {
+ await loginMutation.mutate(data)
+ } catch (error) {
+ // Handle error
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ return (
+
+ )
+}
+```
+
+### Remember Me Functionality
+
+```tsx
+export const loginFn = createServerFn({ method: 'POST' })
+ .validator(
+ (data: { email: string; password: string; rememberMe?: boolean }) => data,
+ )
+ .handler(async ({ data }) => {
+ const user = await authenticateUser(data.email, data.password)
+ if (!user) return { error: 'Invalid credentials' }
+
+ const session = await useAppSession()
+ await session.update(
+ { userId: user.id },
+ {
+ // Extend session if remember me is checked
+ maxAge: data.rememberMe ? 30 * 24 * 60 * 60 : undefined, // 30 days vs session
+ },
+ )
+
+ return { success: true }
+ })
+```
+
+## Working Examples
+
+Study these implementations to understand different authentication patterns:
+
+- **[Basic Auth with Prisma](https://github.com/TanStack/router/tree/main/examples/react/start-basic-auth)** - Complete DIY implementation with database and sessions
+- **[Supabase Integration](https://github.com/TanStack/router/tree/main/examples/react/start-supabase-basic)** - Third-party service integration example
+- **[Client-side Context Auth](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes)** - Client-only authentication patterns
+
+## Migration from Other Solutions
+
+### From Client-Side Auth
+
+If you're migrating from client-side authentication (localStorage, context only):
+
+1. Move authentication logic to server functions
+2. Replace localStorage with server sessions
+3. Update route protection to use `beforeLoad`
+4. Add proper security headers and CSRF protection
+
+### From Other Frameworks
+
+- **Next.js**: Replace API routes with server functions, migrate NextAuth sessions
+- **Remix**: Convert loaders/actions to server functions, adapt session patterns
+- **SvelteKit**: Move form actions to server functions, update route protection
+
+## Production Considerations
+
+When choosing your authentication approach, consider these factors:
+
+### Hosted vs DIY Comparison
+
+**Hosted Solutions (Clerk, WorkOS, Better Auth):**
+
+- Pre-built security measures and regular updates
+- UI components and user management features
+- Compliance certifications and audit trails
+- Support and documentation
+- Per-user or subscription pricing
+
+**DIY Implementation:**
+
+- Complete control over implementation and data
+- No ongoing subscription costs
+- Custom business logic and workflows
+- Responsibility for security updates and monitoring
+- Need to handle edge cases and attack vectors
+
+### Security Considerations
+
+Authentication systems need to handle various security aspects:
+
+- Password hashing and timing attack prevention
+- Session management and fixation protection
+- CSRF and XSS protection
+- Rate limiting and brute force prevention
+- OAuth flow security
+- Compliance requirements (GDPR, CCPA, etc.)
+
+## Next Steps
+
+When implementing authentication, consider:
+
+- **Security Review**: Review your implementation for security best practices
+- **Performance**: Add caching for user lookups and session validation
+- **Monitoring**: Add logging and monitoring for authentication events
+- **Compliance**: Ensure compliance with relevant regulations if storing personal data
+
+For other authentication approaches, check the [Authentication Overview](./authentication-overview.md). For specific integration help, see the [How-to Guides](../../router/framework/react/how-to/README.md#authentication) or explore our [working examples](https://github.com/TanStack/router/tree/main/examples/react).
diff --git a/docs/start/framework/react/build-from-scratch.md b/docs/start/framework/react/build-from-scratch.md
index 74989fb9ea..04452e9af0 100644
--- a/docs/start/framework/react/build-from-scratch.md
+++ b/docs/start/framework/react/build-from-scratch.md
@@ -4,15 +4,15 @@ title: Build a Project from Scratch
---
> [!NOTE]
-> If you chose to quick start with an example or cloned project, you can skip this guide and move on to the [Learn the Basics](../learn-the-basics.md) guide.
+> If you chose to quick start with an example or cloned project, you can skip this guide and move on to the [Routing](../routing) guide.
_So you want to build a TanStack Start project from scratch?_
This guide will help you build a **very** basic TanStack Start web application. Together, we will use TanStack Start to:
-- Serve an index page...
-- Which displays a counter...
-- With a button to increment the counter persistently.
+- Serve an index page
+- Display a counter
+- Increment the counter on the server and client
[Here is what that will look like](https://stackblitz.com/github/tanstack/router/tree/main/examples/react/start-counter)
@@ -58,13 +58,15 @@ npm i @tanstack/react-start @tanstack/react-router vite
You'll also need React:
```shell
-npm i react react-dom
+npm i react react-dom @vitejs/plugin-react
```
+Alternatively, you can also use `@vitejs/plugin-react-oxc` or `@vitejs/plugin-react-swc`.
+
and some TypeScript:
```shell
-npm i -D typescript @types/react @types/react-dom vite-tsconfig-paths @vitejs/plugin-react
+npm i -D typescript @types/react @types/react-dom vite-tsconfig-paths
```
## Update Configuration Files
@@ -84,9 +86,6 @@ We'll then update our `package.json` to use Vite's CLI and set `"type": "module"
Then configure TanStack Start's Vite plugin in `vite.config.ts`:
-> [!NOTE]
-> TanStack Start will stop auto-configuring React/Solid Vite plugins. You’ll get full control - choose `@vitejs/plugin-react`, `@vitejs/plugin-react-oxc`, etc. Set `customViteReactPlugin: true` to opt in to this feature right now!
-
```ts
// vite.config.ts
import { defineConfig } from 'vite'
@@ -100,7 +99,8 @@ export default defineConfig({
},
plugins: [
tsConfigPaths(),
- tanstackStart({ customViteReactPlugin: true }),
+ tanstackStart(),
+ // react's vite plugin must come after start's vite plugin
viteReact(),
],
})
diff --git a/docs/start/framework/react/client-entry-point.md b/docs/start/framework/react/client-entry-point.md
new file mode 100644
index 0000000000..134eeb63bd
--- /dev/null
+++ b/docs/start/framework/react/client-entry-point.md
@@ -0,0 +1,107 @@
+---
+id: client-entry-point
+title: Client Entry Point
+---
+
+# Client Entry Point
+
+> [!NOTE]
+> The client entry point is **optional** out of the box. If not provided, TanStack Start will automatically handle the client entry point for you using the below as a default.
+
+Getting our html to the client is only half the battle. Once there, we need to hydrate our client-side JavaScript once the route resolves to the client. We do this by hydrating the root of our application with the `StartClient` component:
+
+```tsx
+// src/client.tsx
+import { StartClient } from '@tanstack/react-start'
+import { StrictMode } from 'react'
+import { hydrateRoot } from 'react-dom/client'
+import { createRouter } from './router'
+
+const router = createRouter()
+
+hydrateRoot(
+ document,
+
+
+ ,
+)
+```
+
+This enables us to kick off client-side routing once the user's initial server request has fulfilled.
+
+## Custom Client Configuration
+
+You can customize the client entry point to add global providers, error boundaries, or other client-specific setup:
+
+```tsx
+// src/client.tsx
+import { StartClient } from '@tanstack/react-start'
+import { StrictMode } from 'react'
+import { hydrateRoot } from 'react-dom/client'
+import { createRouter } from './router'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+
+const router = createRouter()
+const queryClient = new QueryClient()
+
+hydrateRoot(
+ document,
+
+
+
+
+ ,
+)
+```
+
+## Error Handling
+
+You can wrap your client entry point with error boundaries to handle client-side errors gracefully:
+
+```tsx
+// src/client.tsx
+import { StartClient } from '@tanstack/react-start'
+import { StrictMode } from 'react'
+import { hydrateRoot } from 'react-dom/client'
+import { createRouter } from './router'
+import { ErrorBoundary } from './components/ErrorBoundary'
+
+const router = createRouter()
+
+hydrateRoot(
+ document,
+
+
+
+
+ ,
+)
+```
+
+## Development vs Production
+
+You may want different behavior in development vs production:
+
+```tsx
+// src/client.tsx
+import { StartClient } from '@tanstack/react-start'
+import { StrictMode } from 'react'
+import { hydrateRoot } from 'react-dom/client'
+import { createRouter } from './router'
+
+const router = createRouter()
+
+const App = (
+ <>
+ {import.meta.env.DEV &&
Development Mode
}
+
+ >
+)
+
+hydrateRoot(
+ document,
+ import.meta.env.DEV ? {App} : App,
+)
+```
+
+The client entry point gives you full control over how your application initializes on the client side while working seamlessly with TanStack Start's server-side rendering.
diff --git a/docs/start/framework/react/code-execution-patterns.md b/docs/start/framework/react/code-execution-patterns.md
new file mode 100644
index 0000000000..c1afda4f41
--- /dev/null
+++ b/docs/start/framework/react/code-execution-patterns.md
@@ -0,0 +1,146 @@
+---
+id: code-execution-patterns
+title: Code Execution Patterns
+---
+
+This guide covers patterns for controlling where code runs in your TanStack Start application - server-only, client-only, or isomorphic (both environments). For foundational concepts, see the [Execution Model](./execution-model.md) guide.
+
+## Quick Start
+
+Set up execution boundaries in your TanStack Start application:
+
+```tsx
+import {
+ createServerFn,
+ createServerOnlyFn,
+ createClientOnlyFn,
+ createIsomorphicFn,
+} from '@tanstack/react-start'
+
+// Server function (RPC call)
+const getUsers = createServerFn().handler(async () => {
+ return await db.users.findMany()
+})
+
+// Server-only utility (crashes on client)
+const getSecret = createServerOnlyFn(() => process.env.API_SECRET)
+
+// Client-only utility (crashes on server)
+const saveToStorage = createClientOnlyFn((data: any) => {
+ localStorage.setItem('data', JSON.stringify(data))
+})
+
+// Different implementations per environment
+const logger = createIsomorphicFn()
+ .server((msg) => console.log(`[SERVER]: ${msg}`))
+ .client((msg) => console.log(`[CLIENT]: ${msg}`))
+```
+
+## Implementation Patterns
+
+### Progressive Enhancement
+
+```tsx
+// Component works without JS, enhanced with JS
+function SearchForm() {
+ const [query, setQuery] = useState('')
+
+ return (
+
+ )
+}
+```
+
+### Environment-Aware Storage
+
+```tsx
+const storage = createIsomorphicFn()
+ .server((key: string) => {
+ // Server: File-based cache
+ const fs = require('node:fs')
+ return JSON.parse(fs.readFileSync('.cache', 'utf-8'))[key]
+ })
+ .client((key: string) => {
+ // Client: localStorage
+ return JSON.parse(localStorage.getItem(key) || 'null')
+ })
+```
+
+## Common Problems
+
+### Environment Variable Exposure
+
+```tsx
+// ❌ Exposes to client bundle
+const apiKey = process.env.SECRET_KEY
+
+// ✅ Server-only access
+const apiKey = createServerOnlyFn(() => process.env.SECRET_KEY)
+```
+
+### Incorrect Loader Assumptions
+
+```tsx
+// ❌ Assuming loader is server-only
+export const Route = createFileRoute('/users')({
+ loader: () => {
+ // This runs on BOTH server and client!
+ const secret = process.env.SECRET // Exposed to client
+ return fetch(`/api/users?key=${secret}`)
+ },
+})
+
+// ✅ Use server function for server-only operations
+const getUsersSecurely = createServerFn().handler(() => {
+ const secret = process.env.SECRET // Server-only
+ return fetch(`/api/users?key=${secret}`)
+})
+
+export const Route = createFileRoute('/users')({
+ loader: () => getUsersSecurely(), // Isomorphic call to server function
+})
+```
+
+### Hydration Mismatches
+
+```tsx
+// ❌ Different content server vs client
+function CurrentTime() {
+ return
+}
+```
+
+## Production Checklist
+
+- [ ] **Bundle Analysis**: Verify server-only code isn't in client bundle
+- [ ] **Environment Variables**: Ensure secrets use `createServerOnlyFn()` or `createServerFn()`
+- [ ] **Loader Logic**: Remember loaders are isomorphic, not server-only
+- [ ] **ClientOnly Fallbacks**: Provide appropriate fallbacks to prevent layout shift
+- [ ] **Error Boundaries**: Handle server/client execution errors gracefully
+
+## Related Resources
+
+- [Execution Model](./execution-model.md) - Core concepts and architectural patterns
+- [Server Functions](./server-functions.md) - Deep dive into server function patterns
+- [Environment Variables](./environment-variables.md) - Secure environment variable handling
+- [Middleware](./middleware.md) - Server function middleware patterns
diff --git a/docs/start/framework/react/how-to/use-environment-variables.md b/docs/start/framework/react/environment-variables.md
similarity index 88%
rename from docs/start/framework/react/how-to/use-environment-variables.md
rename to docs/start/framework/react/environment-variables.md
index ee185fbb56..f56114da76 100644
--- a/docs/start/framework/react/how-to/use-environment-variables.md
+++ b/docs/start/framework/react/environment-variables.md
@@ -1,5 +1,6 @@
---
-title: How to Use Environment Variables
+id: environment-variables
+title: Environment Variables
---
Learn how to securely configure and use environment variables in your TanStack Start application across different contexts (server functions, client code, and build processes).
@@ -375,21 +376,9 @@ for (const key of requiredClientEnv) {
**Solutions**:
1. **Add correct prefix**: Use `VITE_` prefix (e.g. `VITE_MY_VARIABLE`)
- Vite's default prefix may be changed in the config:
- ```ts
- // vite.config.ts
- export const config = {
- // ...rest of your config
- envPrefix: 'MYPREFIX_', // this means `MYPREFIX_MY_VARIABLE` is the new correct way
- }
- ```
2. **Restart development server** after adding new variables
3. **Check file location**: `.env` file must be in project root
4. **Verify bundler configuration**: Ensure variables are properly injected
-5. **Verify variable**:
-
-- **In dev**: is in correct `.env` file or environment
-- **For prod**: is in correct `.env` file or current environment **_at bundle time_**. That's right, `VITE_`-prefixed variables are replaced in a macro-like fashion at bundle time, and will _never_ be read at runtime on your server. This is a common mistake, so make sure this is not your case.
**Example**:
@@ -407,21 +396,14 @@ npm run build
VITE_API_KEY=abc123 npm run build
```
-### Runtime Client Environment Variables at Runtime in Production
+### Runtime Client Environment Variables in Production
-**Problem**: If `VITE_` variables are replaced at bundle time only, how to make runtime variables available on the client ?
+**Problem**: If `VITE_` variables are replaced at bundle time only, how to make runtime variables available on the client?
**Solutions**:
Pass variables from the server down to the client:
-1. Add your variable to the correct `env.` file
-2. Create an endpoint on your server to read the value from the client
-
-**Example**:
-
-Using Tanstack Start server functions:
-
```tsx
const getRuntimeVar = createServerFn({ method: 'GET' }).handler(() => {
return process.env.MY_RUNTIME_VAR // notice `process.env` on the server, and no `VITE_` prefix
@@ -483,14 +465,9 @@ interface ImportMetaEnv {
2. Validate required variables at build time
3. Use deployment-specific `.env` files
-## Common Next Steps
-
-
-
-
-
## Related Resources
-- [TanStack Start Server Functions](../server-functions.md) - Learn more about server-side code
-- [TanStack Start Hosting](../hosting.md) - Platform-specific environment variable configuration
+- [Code Execution Patterns](./code-execution-patterns.md) - Learn about server vs client code execution
+- [Server Functions](./server-functions.md) - Learn more about server-side code
+- [Hosting](./hosting.md) - Platform-specific environment variable configuration
- [Vite Environment Variables](https://vitejs.dev/guide/env-and-mode.html) - Official Vite documentation
diff --git a/docs/start/framework/react/how-to/write-isomorphic-client-server-code.md b/docs/start/framework/react/execution-model.md
similarity index 51%
rename from docs/start/framework/react/how-to/write-isomorphic-client-server-code.md
rename to docs/start/framework/react/execution-model.md
index 9835639c34..babecc1061 100644
--- a/docs/start/framework/react/how-to/write-isomorphic-client-server-code.md
+++ b/docs/start/framework/react/execution-model.md
@@ -1,8 +1,9 @@
---
-title: How to Write Isomorphic, Client-Only, and Server-Only Code
+id: execution-model
+title: Execution Model
---
-This guide covers TanStack Start's execution model and APIs for controlling where code runs.
+Understanding where code runs is fundamental to building TanStack Start applications. This guide explains TanStack Start's execution model and how to control where your code executes.
## Core Principle: Isomorphic by Default
@@ -27,21 +28,37 @@ export const Route = createFileRoute('/products')({
})
```
-**Important**: Route `loader`s are isomorphic - they run on both server and client.
+> **Critical Understanding**: Route `loader`s are isomorphic - they run on both server and client, not just the server.
----
+## The Execution Boundary
-## When You Need Execution Constraints
+TanStack Start applications run in two environments:
-### Server-Only APIs
+### Server Environment
-| API | Use Case | Client Behavior |
-| ------------------ | ------------------------- | ------------------------- |
-| `createServerFn()` | RPC calls, data mutations | Network request to server |
-| `serverOnly(fn)` | Utility functions | Throws error |
+- **Node.js runtime** with access to file system, databases, environment variables
+- **During SSR** - Initial page renders on server
+- **API requests** - Server functions execute server-side
+- **Build time** - Static generation and pre-rendering
+
+### Client Environment
+
+- **Browser runtime** with access to DOM, localStorage, user interactions
+- **After hydration** - Client takes over after initial server render
+- **Navigation** - Route loaders run client-side during navigation
+- **User interactions** - Event handlers, form submissions, etc.
+
+## Execution Control APIs
+
+### Server-Only Execution
+
+| API | Use Case | Client Behavior |
+| ------------------------ | ------------------------- | ------------------------- |
+| `createServerFn()` | RPC calls, data mutations | Network request to server |
+| `createServerOnlyFn(fn)` | Utility functions | Throws error |
```tsx
-import { createServerFn, serverOnly } from '@tanstack/react-start'
+import { createServerFn, createServerOnlyFn } from '@tanstack/react-start'
// RPC: Server execution, callable from client
const updateUser = createServerFn({ method: 'POST' })
@@ -52,22 +69,22 @@ const updateUser = createServerFn({ method: 'POST' })
})
// Utility: Server-only, client crashes if called
-const getEnvVar = serverOnly(() => process.env.DATABASE_URL)
+const getEnvVar = createServerOnlyFn(() => process.env.DATABASE_URL)
```
-### Client-Only APIs
+### Client-Only Execution
-| API | Use Case | Server Behavior |
-| ---------------- | ------------------------------- | ---------------- |
-| `clientOnly(fn)` | Browser utilities | Throws error |
-| `` | Components needing browser APIs | Renders fallback |
+| API | Use Case | Server Behavior |
+| ------------------------ | ------------------------------- | ---------------- |
+| `createClientOnlyFn(fn)` | Browser utilities | Throws error |
+| `` | Components needing browser APIs | Renders fallback |
```tsx
-import { clientOnly } from '@tanstack/react-start'
+import { createClientOnlyFn } from '@tanstack/react-start'
import { ClientOnly } from '@tanstack/react-router'
// Utility: Client-only, server crashes if called
-const saveToStorage = clientOnly((key: string, value: any) => {
+const saveToStorage = createClientOnlyFn((key: string, value: any) => {
localStorage.setItem(key, JSON.stringify(value))
})
@@ -92,52 +109,13 @@ const getDeviceInfo = createIsomorphicFn()
.client(() => ({ type: 'client', userAgent: navigator.userAgent }))
```
----
-
-## Key Distinctions
-
-### `createServerFn()` vs `serverOnly()`
-
-```tsx
-// createServerFn: RPC pattern - server execution, client callable
-const fetchUser = createServerFn().handler(async () => await db.users.find())
-
-// Usage from client component:
-const user = await fetchUser() // ✅ Network request
-
-// serverOnly: Crashes if called from client
-const getSecret = serverOnly(() => process.env.SECRET)
-
-// Usage from client:
-const secret = getSecret() // ❌ Throws error
-```
-
-### Manual Environment Detection vs APIs
-
-```tsx
-// Manual: You handle the logic
-function logMessage(msg: string) {
- if (typeof window === 'undefined') {
- console.log(`[SERVER]: ${msg}`)
- } else {
- console.log(`[CLIENT]: ${msg}`)
- }
-}
-
-// API: Framework handles it
-const logMessage = createIsomorphicFn()
- .server((msg) => console.log(`[SERVER]: ${msg}`))
- .client((msg) => console.log(`[CLIENT]: ${msg}`))
-```
-
----
-
-## Common Patterns
+## Architectural Patterns
### Progressive Enhancement
+Build components that work without JavaScript and enhance with client-side functionality:
+
```tsx
-// Component works without JS, enhanced with JS
function SearchForm() {
const [query, setQuery] = useState('')
@@ -171,9 +149,25 @@ const storage = createIsomorphicFn()
})
```
----
+### RPC vs Direct Function Calls
-## Common Problems
+Understanding when to use server functions vs server-only functions:
+
+```tsx
+// createServerFn: RPC pattern - server execution, client callable
+const fetchUser = createServerFn().handler(async () => await db.users.find())
+
+// Usage from client component:
+const user = await fetchUser() // ✅ Network request
+
+// createServerOnlyFn: Crashes if called from client
+const getSecret = createServerOnlyFn(() => process.env.SECRET)
+
+// Usage from client:
+const secret = getSecret() // ❌ Throws error
+```
+
+## Common Anti-Patterns
### Environment Variable Exposure
@@ -182,7 +176,7 @@ const storage = createIsomorphicFn()
const apiKey = process.env.SECRET_KEY
// ✅ Server-only access
-const apiKey = serverOnly(() => process.env.SECRET_KEY)
+const apiKey = createServerOnlyFn(() => process.env.SECRET_KEY)
```
### Incorrect Loader Assumptions
@@ -228,26 +222,86 @@ function CurrentTime() {
}
```
----
+## Manual vs API-Driven Environment Detection
-## Production Checklist
+```tsx
+// Manual: You handle the logic
+function logMessage(msg: string) {
+ if (typeof window === 'undefined') {
+ console.log(`[SERVER]: ${msg}`)
+ } else {
+ console.log(`[CLIENT]: ${msg}`)
+ }
+}
-- [ ] **Bundle Analysis**: Verify server-only code isn't in client bundle
-- [ ] **Environment Variables**: Ensure secrets use `serverOnly()` or `createServerFn()`
-- [ ] **Loader Logic**: Remember loaders are isomorphic, not server-only
-- [ ] **ClientOnly Fallbacks**: Provide appropriate fallbacks to prevent layout shift
-- [ ] **Error Boundaries**: Handle server/client execution errors gracefully
+// API: Framework handles it
+const logMessage = createIsomorphicFn()
+ .server((msg) => console.log(`[SERVER]: ${msg}`))
+ .client((msg) => console.log(`[CLIENT]: ${msg}`))
+```
----
+## Architecture Decision Framework
-## Related Resources
+**Choose Server-Only when:**
-- [TanStack Start Server Functions Guide](../server-functions.md)
-- [TanStack Start Middleware Guide](../middleware.md)
-- [TanStack Router SSR Guide](../../../router/framework/react/how-to/setup-ssr.md)
+- Accessing sensitive data (environment variables, secrets)
+- File system operations
+- Database connections
+- External API keys
-
+**Choose Client-Only when:**
+
+- DOM manipulation
+- Browser APIs (localStorage, geolocation)
+- User interaction handling
+- Analytics/tracking
+
+**Choose Isomorphic when:**
+
+- Data formatting/transformation
+- Business logic
+- Shared utilities
+- Route loaders (they're isomorphic by nature)
+
+## Security Considerations
+
+### Bundle Analysis
+
+Always verify server-only code isn't included in client bundles:
+
+```bash
+# Analyze client bundle
+npm run build
+# Check dist/client for any server-only imports
+```
+
+### Environment Variable Strategy
+
+- **Client-exposed**: Use `VITE_` prefix for client-accessible variables
+- **Server-only**: Access via `createServerOnlyFn()` or `createServerFn()`
+- **Never expose**: Database URLs, API keys, secrets
+
+### Error Boundaries
+
+Handle server/client execution errors gracefully:
+
+```tsx
+function ErrorBoundary({ children }: { children: React.ReactNode }) {
+ return (
+ Something went wrong
}
+ onError={(error) => {
+ if (typeof window === 'undefined') {
+ console.error('[SERVER ERROR]:', error)
+ } else {
+ console.error('[CLIENT ERROR]:', error)
+ }
+ }}
+ >
+ {children}
+
+ )
+}
+```
+
+Understanding TanStack Start's execution model is crucial for building secure, performant, and maintainable applications. The isomorphic-by-default approach provides flexibility while the execution control APIs give you precise control when needed.
diff --git a/docs/start/framework/react/getting-started.md b/docs/start/framework/react/getting-started.md
index 85cf844637..e2d45a100d 100644
--- a/docs/start/framework/react/getting-started.md
+++ b/docs/start/framework/react/getting-started.md
@@ -3,8 +3,23 @@ id: getting-started
title: Getting Started
---
-To set up a TanStack Start project, you can:
+## Migrate an existing project from another framework
-- Use the [TanStack Start CLI](https://github.com/TanStack/create-tsrouter-app/blob/main/cli/create-start-app/README.md) via `npx create-start-app@latest`
-- Use the [Quick Start Examples](../quick-start) to rapidly learn as you go
-- [Build a project from scratch](../build-from-scratch) to learn how TanStack Start works from the ground up
+- [Start a new project from scratch](#start-a-new-project-from-scratch) to quickly learn how Start works (see below)
+- Refer to a migration guide for your specific framework:
+ - [Next.js](../migrate-from-next-js)
+ - [React Router](../migrate-from-react-router) (Including React Router 7 "Data Mode")
+ - Remix 2 / React Router 7 "Framework Mode" (coming soon!)
+
+## Start a new project from scratch
+
+Choose one of the following options to start building a _new_ TanStack Start project:
+
+- [TanStack Builder](#) (coming soon!) - A visual interface to configure new TanStack projects with a few clicks
+- [TanStack Start CLI](https://github.com/TanStack/create-tsrouter-app/blob/main/cli/create-start-app/README.md) via `npx create-start-app@latest` - Local, fast, and optionally customizable
+- [Quick Start Examples](../quick-start) Download or clone one of our official examples
+- [Build a project from scratch](../build-from-scratch) - A guide to building a TanStack Start project line-by-line, file-by-file.
+
+## Next Steps
+
+Unless you chose to build a project from scratch, you can now move on to the [Routing](../routing) guide to learn how to use TanStack Start!
diff --git a/docs/start/framework/react/hosting.md b/docs/start/framework/react/hosting.md
index aff63011e7..b4be04b6e4 100644
--- a/docs/start/framework/react/hosting.md
+++ b/docs/start/framework/react/hosting.md
@@ -9,22 +9,7 @@ Hosting is the process of deploying your application to the internet so that use
TanStack Start is **designed to work with any hosting provider**, so if you already have a hosting provider in mind, you can deploy your application there using the full-stack APIs provided by TanStack Start.
-However, since hosting is one of the most crucial aspects of your application's performance, reliability, and scalability, we highly recommend using our Official Hosting Partner [Netlify](https://www.netlify.com?utm_source=tanstack).
-
-## What is Netlify?
-
-
-
-
-
-
-
-
-
-Netlify is a leading hosting platform that provides a fast, secure, and reliable environment for deploying your web applications. With Netlify, you can deploy your TanStack Start application in just a few clicks and benefit from features like a global edge network, automatic scaling, and seamless integrations with GitHub and GitLab. Netlify is designed to make your development process as smooth as possible, from local development to production deployment.
-
-- To learn more about Netlify, visit the [Netlify website](https://www.netlify.com?utm_source=tanstack)
-- To sign up, visit the [Netlify dashboard](https://www.netlify.com/signup?utm_source=tanstack)
+However, since hosting is one of the most crucial aspects of your application's performance, reliability, and scalability, we recommend using one of our **Official Hosting Partners**: [Cloudflare](https://www.cloudflare.com?utm_source=tanstack) or [Netlify](https://www.netlify.com?utm_source=tanstack).
## Deployment
@@ -33,48 +18,24 @@ Netlify is a leading hosting platform that provides a fast, secure, and reliable
When a TanStack Start application is being deployed, the `target` value in the TanStack Start Vite plugin in the`vite.config.ts` file determines the deployment target. The deployment target can be set to one of the following values:
+- [`cloudflare-pages`](#cloudflare-pages): Deploy to Cloudflare Pages
- [`netlify`](#netlify): Deploy to Netlify
- [`vercel`](#vercel): Deploy to Vercel
-- [`cloudflare-pages`](#cloudflare-pages): Deploy to Cloudflare Pages
- [`node-server`](#nodejs): Deploy to a Node.js server
- [`bun`](#bun): Deploy to a Bun server
- ... and more to come!
Once you've chosen a deployment target, you can follow the deployment guidelines below to deploy your TanStack Start application to the hosting provider of your choice.
-### Netlify
+### Cloudflare Workers ⭐ _Official Partner_
-Set the `target` value to `'netlify'` in the TanStack Start Vite plugin in `vite.config.ts` file.
-
-```ts
-// vite.config.ts
-import { tanstackStart } from '@tanstack/react-start/plugin/vite'
-import { defineConfig } from 'vite'
-
-export default defineConfig({
- plugins: [tanstackStart({ target: 'netlify' })],
-})
-```
-
-Deploy your application to Netlify using their one-click deployment process, and you're ready to go!
-
-### Vercel
-
-Set the `target` value to `'vercel'` in the TanStack Start Vite plugin in `vite.config.ts` file.
-
-```ts
-// vite.config.ts
-import { tanstackStart } from '@tanstack/react-start/plugin/vite'
-import { defineConfig } from 'vite'
-
-export default defineConfig({
- plugins: [tanstackStart({ target: 'vercel' })],
-})
-```
-
-Deploy your application to Vercel using their one-click deployment process, and you're ready to go!
-
-### Cloudflare Workers
+
+
+
+
+
+
+
When deploying to Cloudflare Workers, you'll need to complete a few extra steps before your users can start using your app.
@@ -84,11 +45,12 @@ Set the `target` value to `cloudflare-module` in your `vite.config.ts` file.
```ts
// vite.config.ts
-import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import { defineConfig } from 'vite'
+import { tanstackStart } from '@tanstack/react-start/plugin/vite'
+import viteReact from '@vitejs/plugin-react'
export default defineConfig({
- plugins: [tanstackStart({ target: 'cloudflare-module' })],
+ plugins: [tanstackStart({ target: 'cloudflare-module' }), viteReact()],
})
```
@@ -108,17 +70,60 @@ directory = "./.output/public"
Deploy your application to Cloudflare Workers using their one-click deployment process, and you're ready to go!
+### Netlify ⭐ _Official Partner_
+
+
+
+
+
+
+
+
+
+Set the `target` value to `'netlify'` in the TanStack Start Vite plugin in `vite.config.ts` file.
+
+```ts
+// vite.config.ts
+import { defineConfig } from 'vite'
+import { tanstackStart } from '@tanstack/react-start/plugin/vite'
+import viteReact from '@vitejs/plugin-react'
+
+export default defineConfig({
+ plugins: [tanstackStart({ target: 'netlify' }), viteReact()],
+})
+```
+
+Deploy your application to Netlify using their one-click deployment process, and you're ready to go!
+
+### Vercel
+
+Set the `target` value to `'vercel'` in the TanStack Start Vite plugin in `vite.config.ts` file.
+
+```ts
+// vite.config.ts
+import { defineConfig } from 'vite'
+import { tanstackStart } from '@tanstack/react-start/plugin/vite'
+import viteReact from '@vitejs/plugin-react'
+
+export default defineConfig({
+ plugins: [tanstackStart({ target: 'vercel' }), viteReact()],
+})
+```
+
+Deploy your application to Vercel using their one-click deployment process, and you're ready to go!
+
### Node.js
Set the `target` value to `node-server` in your `vite.config.ts` file.
```ts
// vite.config.ts
-import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import { defineConfig } from 'vite'
+import { tanstackStart } from '@tanstack/react-start/plugin/vite'
+import viteReact from '@vitejs/plugin-react'
export default defineConfig({
- plugins: [tanstackStart({ target: 'node-server' })],
+ plugins: [tanstackStart({ target: 'node-server' }), viteReact()],
})
```
@@ -149,11 +154,12 @@ Set the `target` value to `bun` in your `vite.config.ts` file.
```ts
// vite.config.ts
-import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import { defineConfig } from 'vite'
+import { tanstackStart } from '@tanstack/react-start/plugin/vite'
+import viteReact from '@vitejs/plugin-react'
export default defineConfig({
- plugins: [tanstackStart({ target: 'bun' })],
+ plugins: [tanstackStart({ target: 'bun' }), viteReact()],
})
```
diff --git a/docs/start/framework/react/how-to/README.md b/docs/start/framework/react/how-to/README.md
deleted file mode 100644
index ad2b1a069e..0000000000
--- a/docs/start/framework/react/how-to/README.md
+++ /dev/null
@@ -1,497 +0,0 @@
-# How-To Guides for TanStack Start
-
-This directory contains focused, step-by-step instructions for common TanStack Start tasks. Each guide is designed to be:
-
-- **Task-focused**: Covers one specific goal from start to finish
-- **Self-contained**: All necessary steps included, no prerequisites assumed
-- **Copy-paste ready**: Working code examples you can use immediately
-- **Problem-solving oriented**: Addresses real-world scenarios and common issues
-
-## **Implementation Plan - Sorted by First-Principles & Dependencies**
-
-_Based on GitHub issues analysis and actual user pain points from the TanStack/router repository_
-
----
-
-### **Foundation Layer (Prerequisites for everything else)**
-
-### **1. How to Write Isomorphic, Client-Only, and Server-Only Code**
-
-**Priority: Foundation** | **Dependencies: None** | **Status: ✅ Completed**
-
-Core concept that affects every subsequent pattern in TanStack Start.
-
-**Should Cover:**
-
-- Understanding the execution boundary (server vs client)
-- Code organization strategies for different execution contexts
-- Common pitfalls and how to avoid them
-- When to use each pattern
-
-### **2. How to Create Basic Server Functions**
-
-**Priority: Foundation** | **Dependencies: #1** | **Status: 📝 Needed**
-
-**GitHub Issues:** [#4533](https://github.com/TanStack/router/issues/4533) (TypeScript issues)
-
-Core server function concepts before advanced patterns.
-
-**Should Cover:**
-
-- `createServerFn()` basic setup and usage
-- Input validation with validators (Zod, Valibot)
-- Return types and serialization
-- Error handling patterns
-- Basic HTTP methods (GET, POST)
-- Calling server functions from client components
-
-### **3. How to Write Type-Safe Server Functions**
-
-**Priority: Critical** | **Dependencies: #2** | **Status: 🔥 Urgent**
-
-**GitHub Issues:** [#4533](https://github.com/TanStack/router/issues/4533) (5 👍)
-
-**Should Cover:**
-
-- Designing server functions with proper TypeScript patterns
-- Avoiding "Type instantiation is excessively deep" errors
-- Structuring types to prevent recursive type issues
-- Input/output type validation patterns
-- Performance-optimized TypeScript configurations
-- Testing type safety in server functions
-
----
-
-### **Server Function Advanced Patterns**
-
-### **4. How to Use Server Function Middleware**
-
-**Priority: Foundation** | **Dependencies: #2** | **Status: 📝 Needed**
-
-**GitHub Issues:** [#4737](https://github.com/TanStack/router/issues/4737), [#4738](https://github.com/TanStack/router/issues/4738), [#4460](https://github.com/TanStack/router/issues/4460)
-
-**Should Cover:**
-
-- `createMiddleware()` setup and patterns
-- Proper `next()` calling patterns (avoid multiple calls)
-- Composing multiple middleware functions
-- Authentication middleware patterns
-- Logging and observability middleware
-- Error handling middleware
-- Conditional middleware application
-
-### **5. How to Handle Redirects in Server Functions**
-
-**Priority: High** | **Dependencies: #4** | **Status: 🔥 Urgent**
-
-**GitHub Issues:** [#4460](https://github.com/TanStack/router/issues/4460) (5 👍)
-
-**Should Cover:**
-
-- Redirect patterns with and without middleware
-- Why redirects fail with middleware
-- Proper response handling
-- Authentication redirect patterns
-- Common redirect failures and solutions
-
-### **6. How to Manage Server Function Context**
-
-**Priority: Core** | **Dependencies: #4** | **Status: 📝 Needed**
-
-**Should Cover:**
-
-- Context creation and typing
-- Passing context between middleware layers
-- Request context (headers, cookies, user info)
-- Database connections in context
-- Context inheritance patterns
-- Performance considerations
-
-### **7. How to Use sendContext for Server-Client Communication**
-
-**Priority: Core** | **Dependencies: #6** | **Status: 📝 Needed**
-
-**Should Cover:**
-
-- `sendContext` API usage and patterns
-- Serialization considerations
-- Client-side context consumption
-- Type safety with context transfer
-- Performance optimization
-- Use cases and best practices
-
----
-
-### **Deployment & Hosting Layer (Major User Pain Points)**
-
-### **8. How to Deploy to Cloudflare Pages/Workers (Comprehensive)**
-
-**Priority: Critical** | **Dependencies: #2** | **Status: 🔥 Urgent**
-
-**GitHub Issues:** [#4473](https://github.com/TanStack/router/issues/4473) (13 👍), [#4400](https://github.com/TanStack/router/issues/4400)
-
-**Should Cover:**
-
-- Cloudflare Pages deployment setup
-- Cloudflare Workers configuration
-- `@cloudflare/vite-plugin` integration
-- Wrangler.toml configuration (best practices)
-- Post-vinxi→vite migration fixes
-- Virtual imports (`cloudflare:workflows`, `cloudflare:workers`)
-- Environment variable management
-- Custom Nitro configuration for Cloudflare
-- **Note:** Some plugin configuration issues (#4779) are upstream dependencies
-
-### **9. How to Deploy to Netlify**
-
-**Priority: High** | **Dependencies: #2** | **Status: 📝 Needed**
-
-**Partnership Focus:** Netlify (official hosting partner)
-
-**Should Cover:**
-
-- Netlify-specific configuration
-- Edge functions integration
-- Environment variables
-- Build optimization
-- Server function deployment on Netlify
-
-### **10. How to Deploy to Netlify with Clerk Integration**
-
-**Priority: High** | **Dependencies: #9** | **Status: 📝 Needed**
-
-**GitHub Issues:** [#4762](https://github.com/TanStack/router/issues/4762)
-
-**Should Cover:**
-
-- Netlify + Clerk webhook setup
-- Authentication flow on Netlify
-- Environment variable management
-- Edge function auth patterns
-- Troubleshooting common issues
-
-### **11. How to Deploy to Vercel**
-
-**Priority: Medium-High** | **Dependencies: #2** | **Status: 📝 Needed**
-
-**Should Cover:**
-
-- Vercel Edge Functions
-- Serverless function optimization
-- Build configuration
-- Performance monitoring
-
----
-
-### **Advanced Configuration & Troubleshooting**
-
-### **12. How to Configure Custom Nitro Settings**
-
-**Priority: Medium-High** | **Dependencies: #8** | **Status: 📝 Needed**
-
-**GitHub Issues:** [#4404](https://github.com/TanStack/router/issues/4404) (3 👍)
-
-**Should Cover:**
-
-- Post-vinxi→vite migration Nitro configuration
-- Custom deployment target settings
-- Advanced Nitro options for different platforms
-- Migration troubleshooting from old configs
-- `tanstackStart({ nitro: { ... } })` patterns
-
-### **13. How to Handle Deferred Data and Streaming**
-
-**Priority: High** | **Dependencies: #2** | **Status: 📝 Needed**
-
-**GitHub Issues:** [#4802](https://github.com/TanStack/router/issues/4802)
-
-**Should Cover:**
-
-- Deferred data patterns in Start
-- Server vs client promise resolution
-- Page refresh behavior with deferred data
-- Streaming best practices
-- `useSuspenseQuery` with server functions
-- Dynamic streaming without configuration
-
-### **14. How to Handle URL Parameters and Encoding**
-
-**Priority: Medium-High** | **Dependencies: #1** | **Status: 📝 Needed**
-
-**GitHub Issues:** [#4514](https://github.com/TanStack/router/issues/4514)
-
-**Should Cover:**
-
-- Encoded URL parameter handling
-- Preventing redirect loops on page refresh
-- Complex parameter validation
-- URL encoding best practices
-- Client vs server parameter handling
-
-### **15. How to Configure Project Structure and srcDirectory**
-
-**Priority: Medium** | **Dependencies: #1** | **Status: 📝 Needed**
-
-**GitHub Issues:** [#4432](https://github.com/TanStack/router/issues/4432)
-
-**Should Cover:**
-
-- srcDirectory configuration options
-- Root directory setup patterns
-- Avoiding "Invalid lazy handler" errors
-- Project structure best practices
-- File organization strategies
-
----
-
-### **Server Infrastructure Layer**
-
-### **16. How to Create and Configure Server Routes**
-
-**Priority: Core** | **Dependencies: #2** | **Status: 📝 Needed**
-
-**Should Cover:**
-
-- Server route file conventions
-- HTTP method handling with server functions
-- Route parameters and server function integration
-- Middleware integration with server routes
-- Error handling patterns
-
-### **17. How to Implement Single Flight Mutations with TanStack Query**
-
-**Priority: Medium-High** | **Dependencies: #2, #7** | **Status: 📝 Needed**
-
-**Advanced Pattern:** Server function + TanStack Query optimization
-
-**Should Cover:**
-
-- Single flight mutation patterns
-- Server function integration with TanStack Query
-- Optimistic updates with server functions
-- Error handling and rollback strategies
-- Performance optimization techniques
-- Cache invalidation patterns
-
----
-
-### **Database & Partnership Integrations**
-
-### **18. How to Set Up TanStack DB with Start**
-
-**Priority: High** | **Dependencies: #6, #7** | **Status: 📝 Needed**
-
-**TanStack Ecosystem Integration**
-
-**Should Cover:**
-
-- TanStack DB setup and configuration
-- Database context in server functions
-- Type-safe database operations
-- Migration patterns with Start
-- Real-time features integration
-- Performance optimization patterns
-
-### **19. How to Set Up Neon Database Integration**
-
-**Priority: High** | **Dependencies: #6** | **Status: 📝 Needed**
-
-**Partnership Focus:** Neon (sponsor)
-
-**Should Cover:**
-
-- Neon setup with server function context
-- Connection pooling in middleware
-- Serverless-optimized patterns
-- Environment management
-- Migration workflows
-
-### **20. How to Integrate with Convex**
-
-**Priority: High** | **Dependencies: #6, #13** | **Status: 📝 Needed**
-
-**Partnership Focus:** Convex (sponsor) + Real-time
-
-**Should Cover:**
-
-- Convex integration with server functions
-- Real-time data with sendContext
-- Authentication integration patterns
-- Convex mutations vs server functions
-- Performance optimization
-
----
-
-### **Server Framework Integrations**
-
-### **21. How to Integrate tRPC with TanStack Start**
-
-**Priority: High** | **Dependencies: #16** | **Status: 📝 Needed**
-
-**Should Cover:**
-
-- tRPC router setup in server routes
-- tRPC vs server functions comparison
-- Hybrid patterns (when to use each)
-- Authentication middleware with tRPC
-- Type-safe client integration
-
-### **22. How to Use Hono with TanStack Start**
-
-**Priority: Medium-High** | **Dependencies: #16** | **Status: 📝 Needed**
-
-**Should Cover:**
-
-- Hono app integration in server routes
-- Hono middleware vs Start middleware
-- Performance optimizations
-- Edge runtime compatibility
-
----
-
-### **Authentication & Authorization**
-
-### **23. How to Implement Full-Stack Authentication (Comprehensive)**
-
-**Priority: Core** | **Dependencies: #4, #6** | **Status: 📝 Needed**
-
-**Should Cover:**
-
-- **HTTP-Only Cookie Sessions** with server function middleware
-- **JWT Patterns** using context management
-- **Session Management APIs** with TanStack Start
-- **Route Protection** using middleware patterns
-- **Auth Context** management across server functions
-- **Login/Logout flows** with server function patterns
-
-### **24. How to Integrate with Clerk Authentication**
-
-**Priority: Core** | **Dependencies: #23** | **Status: 📝 Needed**
-
-**Partnership Focus:** Clerk integration
-
-**Should Cover:**
-
-- Clerk middleware for server functions
-- Authentication context with Clerk
-- Protected server function patterns
-- User management through server functions
-
-### **25. How to Integrate with Better Auth**
-
-**Priority: Medium** | **Dependencies: #23** | **Status: 📝 Needed**
-
-**Emerging Auth Solution**
-
-**Should Cover:**
-
-- Better Auth setup and configuration
-- Integration with Start's server functions
-- Session management patterns
-- Social login integration
-
----
-
-## **Implementation Priority & Timeline**
-
-### **Phase 1: Critical Foundation (Immediate - 4 weeks)**
-
-1. **#1** - Isomorphic/Client/Server Code Boundaries ✅
-2. **#2** - Basic Server Functions
-3. **#3** - Write Type-Safe Server Functions 🔥
-4. **#4** - Server Function Middleware
-5. **#5** - Handle Redirects in Server Functions 🔥
-
-### **Phase 2: Deployment Blockers (6 weeks)**
-
-6. **#8** - Cloudflare Deployment (Comprehensive) 🔥
-7. **#9** - Netlify Deployment
-8. **#10** - Netlify + Clerk Integration
-9. **#12** - Custom Nitro Configuration
-
-### **Phase 3: Advanced Server Patterns (8 weeks)**
-
-10. **#6** - Server Function Context Management
-11. **#7** - sendContext Usage
-12. **#13** - Deferred Data and Streaming
-13. **#16** - Server Routes Configuration
-14. **#17** - Single Flight Mutations
-
-### **Phase 4: Database & Partnerships (10 weeks)**
-
-15. **#18** - TanStack DB Integration
-16. **#19** - Neon Database Integration
-17. **#20** - Convex Integration
-18. **#21** - tRPC Integration
-
-### **Phase 5: Authentication & Advanced (12 weeks)**
-
-19. **#23** - Full-Stack Authentication
-20. **#24** - Clerk Integration
-21. **#11** - Vercel Deployment
-22. **#22** - Hono Integration
-
----
-
-## **Success Metrics**
-
-### **Each Guide Must Include:**
-
-1. **Completeness**: Setup to production deployment
-2. **Working Examples**: Copy-paste ready code
-3. **Troubleshooting**: Address common pitfalls and errors
-4. **GitHub Issue Resolution**: Link to and solve specific reported issues
-5. **Next Steps**: Related guides and advanced topics
-
-### **Format Consistency:**
-
-- **Quick Start** section with minimal working example
-- **Step-by-step implementation** with code samples
-- **Common Problems** section addressing GitHub issues
-- **Production Checklist** for deployment readiness
-- **Related Resources** linking to other guides
-
----
-
-## **Available Guides**
-
-- ✅ [Write Isomorphic, Client-Only, and Server-Only Code](./write-isomorphic-client-server-code.md) - Understand execution boundaries and control where code runs in TanStack Start applications
-- ✅ [Use Environment Variables](./use-environment-variables.md) - Set up and use environment variables securely in TanStack Start applications
-
----
-
-## **GitHub Issues Tracking**
-
-**High Priority Issues to Address:**
-
-- [#4533](https://github.com/TanStack/router/issues/4533) - Server Function TypeScript Issues (5 👍)
-- [#4473](https://github.com/TanStack/router/issues/4473) - Cloudflare Vite Plugin Support (13 👍)
-- [#4460](https://github.com/TanStack/router/issues/4460) - Redirects in Server Functions (5 👍)
-- [#4779](https://github.com/TanStack/router/issues/4779) - Cloudflare Hosting Docs
-- [#4762](https://github.com/TanStack/router/issues/4762) - Netlify + Clerk Integration
-- [#4802](https://github.com/TanStack/router/issues/4802) - Deferred Data Behavior
-- [#4737](https://github.com/TanStack/router/issues/4737) - Server Function Middleware Patterns
-- [#4514](https://github.com/TanStack/router/issues/4514) - URL Parameter Encoding
-- [#4432](https://github.com/TanStack/router/issues/4432) - Project Structure Configuration
-- [#4404](https://github.com/TanStack/router/issues/4404) - Custom Nitro Configuration
-
----
-
-## **Contributing**
-
-When adding new how-to guides:
-
-1. **Focus on a single, well-defined task**
-2. **Address specific GitHub issues when possible**
-3. **Use clear headings and numbered steps**
-4. **Include complete, working code examples**
-5. **Address the most frequent problems at the end**
-6. **Follow the dependency order outlined above**
-7. **Link to related guides and GitHub issues**
-
-**Priority should be given to guides that:**
-
-- Solve actual user problems (GitHub issues)
-- Enable TanStack Start's unique features (server functions)
-- Support partnership integrations (Neon, Convex, Clerk, Netlify)
-- Unblock deployment and production usage
diff --git a/docs/start/framework/react/learn-the-basics.md b/docs/start/framework/react/learn-the-basics.md
deleted file mode 100644
index d9f9939be6..0000000000
--- a/docs/start/framework/react/learn-the-basics.md
+++ /dev/null
@@ -1,347 +0,0 @@
----
-id: learn-the-basics
-title: Learn the Basics
----
-
-This guide will help you learn the basics behind how TanStack Start works, regardless of how you set up your project.
-
-## Dependencies
-
-TanStack Start is powered by [Vite](https://vite.dev/) and [TanStack Router](https://tanstack.com/router).
-
-- **TanStack Router**: A router for building web applications.
-- **Vite**: A build tool for bundling your application.
-
-## It all "Starts" with the Router
-
-This is the file that will dictate the behavior of TanStack Router used within Start. Here, you can configure everything
-from the default [preloading functionality](/router/latest/docs/framework/react/guide/preloading) to [caching staleness](/router/latest/docs/framework/react/guide/data-loading).
-
-```tsx
-// src/router.tsx
-import { createRouter as createTanStackRouter } from '@tanstack/react-router'
-import { routeTree } from './routeTree.gen'
-
-export function createRouter() {
- const router = createTanStackRouter({
- routeTree,
- scrollRestoration: true,
- })
-
- return router
-}
-
-declare module '@tanstack/react-router' {
- interface Register {
- router: ReturnType
- }
-}
-```
-
-- Notice the `scrollRestoration` property. This is used to restore the scroll position of the page when navigating between routes.
-
-## Route Generation
-
-The `routeTree.gen.ts` file is generated when you run TanStack Start (via `npm run dev` or `npm run start`) for the first time. This file contains the generated route tree and a handful of TS utilities that make TanStack Start fully type-safe.
-
-## The Server Entry Point (Optional)
-
-> [!NOTE]
-> The server entry point is **optional** out of the box. If not provided, TanStack Start will automatically handle the server entry point for you using the below as a default.
-
-This is done via the `src/server.ts` file:
-
-```tsx
-// src/server.ts
-import {
- createStartHandler,
- defaultStreamHandler,
-} from '@tanstack/react-start/server'
-import { createRouter } from './router'
-
-export default createStartHandler({
- createRouter,
-})(defaultStreamHandler)
-```
-
-Whether we are statically generating our app or serving it dynamically, the `server.ts` file is the entry point for doing all SSR-related work.
-
-- It's important that a new router is created for each request. This ensures that any data handled by the router is unique to the request.
-- The `defaultStreamHandler` function is used to render our application to a stream, allowing us to take advantage of streaming HTML to the client. (This is the default handler, but you can also use other handlers like `defaultRenderHandler`, or even build your own)
-
-## The Client Entry Point (Optional)
-
-> [!NOTE]
-> The client entry point is **optional** out of the box. If not provided, TanStack Start will automatically handle the client entry point for you using the below as a default.
-
-Getting our html to the client is only half the battle. Once there, we need to hydrate our client-side JavaScript once the route resolves to the client. We do this by hydrating the root of our application with the `StartClient` component:
-
-```tsx
-// src/client.tsx
-import { StartClient } from '@tanstack/react-start'
-import { StrictMode } from 'react'
-import { hydrateRoot } from 'react-dom/client'
-import { createRouter } from './router'
-
-const router = createRouter()
-
-hydrateRoot(
- document,
-
-
- ,
-)
-```
-
-This enables us to kick off client-side routing once the user's initial server request has fulfilled.
-
-## The Root of Your Application
-
-Other than the client entry point (which is optional by default), the `__root` route of your application is the entry point for your application. The code in this file will wrap all other routes in the app, including your home page. It behaves like a pathless layout route for your whole application.
-
-Because it is **always rendered**, it is the perfect place to construct your application shell and take care of any global logic.
-
-```tsx
-// src/routes/__root.tsx
-import {
- Outlet,
- createRootRoute,
- HeadContent,
- Scripts,
-} 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: 'TanStack Start Starter',
- },
- ],
- }),
- component: RootComponent,
-})
-
-function RootComponent() {
- return (
-
-
-
- )
-}
-
-function RootDocument({ children }: Readonly<{ children: ReactNode }>) {
- return (
-
-
-
-
-
- {children}
-
-
-
- )
-}
-```
-
-- This layout may change in the future as we roll out SPA mode, which allows the root route to render the SPA shell without any page-specific content.
-- Notice the `Scripts` component. This is used to load all of the client-side JavaScript for the application.
-
-## Routes
-
-Routes are an extensive feature of TanStack Router, and are covered thoroughly in the [Routing Guide](/router/latest/docs/framework/react/routing/file-based-routing). As a summary:
-
-- Routes are defined using the `createFileRoute` function.
-- Routes are automatically code-split and lazy-loaded.
-- Critical data fetching is coordinated from a Route's loader
-- Much more!
-
-```tsx
-// src/routes/index.tsx
-import * as fs from 'node:fs'
-import { createFileRoute, useRouter } from '@tanstack/react-router'
-import { createServerFn } from '@tanstack/react-start'
-
-const filePath = 'count.txt'
-
-async function readCount() {
- return parseInt(
- await fs.promises.readFile(filePath, 'utf-8').catch(() => '0'),
- )
-}
-
-const getCount = createServerFn({
- method: 'GET',
-}).handler(() => {
- return readCount()
-})
-
-const updateCount = createServerFn({ method: 'POST' })
- .validator((d: number) => d)
- .handler(async ({ data }) => {
- const count = await readCount()
- await fs.promises.writeFile(filePath, `${count + data}`)
- })
-
-export const Route = createFileRoute('/')({
- component: Home,
- loader: async () => await getCount(),
-})
-
-function Home() {
- const router = useRouter()
- const state = Route.useLoaderData()
-
- return (
-
- )
-}
-```
-
-## Navigation
-
-TanStack Start builds 100% on top of TanStack Router, so all of the navigation features of TanStack Router are available to you. In summary:
-
-- Use the `Link` component to navigate to a new route.
-- Use the `useNavigate` hook to navigate imperatively.
-- Use the `useRouter` hook anywhere in your application to access the router instance and perform invalidations.
-- Every router hook that returns state is reactive, meaning it will automatically re-run when the appropriate state changes.
-
-Here's a quick example of how you can use the `Link` component to navigate to a new route:
-
-```tsx
-import { Link } from '@tanstack/react-router'
-
-function Home() {
- return About
-}
-```
-
-For more in-depth information on navigation, check out the [navigation guide](/router/latest/docs/framework/react/guide/navigation).
-
-## Server Functions (RPCs)
-
-You may have noticed the **server function** we created above using `createServerFn`. This is one of TanStack's most powerful features, allowing you to create server-side functions that can be called from both the server during SSR and the client!
-
-Here's a quick overview of how server functions work:
-
-- Server functions are created using the `createServerFn` function.
-- They can be called from both the server during SSR and the client.
-- They can be used to fetch data from the server, or to perform other server-side actions.
-
-Here's a quick example of how you can use server functions to fetch and return data from the server:
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-import * as fs from 'node:fs'
-import { z } from 'zod'
-
-const getUserById = createServerFn({ method: 'GET' })
- // Always validate data sent to the function, here we use Zod
- .validator(z.string())
- // The handler function is where you perform the server-side logic
- .handler(async ({ data }) => {
- return db.query.users.findFirst({ where: eq(users.id, data) })
- })
-
-// Somewhere else in your application
-const user = await getUserById({ data: '1' })
-```
-
-To learn more about server functions, check out the [server functions guide](../server-functions).
-
-### Mutations
-
-Server Functions can also be used to perform mutations on the server. This is also done using the same `createServerFn` function, but with the additional requirement that you invalidate any data on the client that was affected by the mutation.
-
-- If you're using TanStack Router only, you can use the `router.invalidate()` method to invalidate all router data and re-fetch it.
-- If you're using TanStack Query, you can use the `queryClient.invalidateQueries()` method to invalidate data, among other more specific methods to target specific queries.
-
-Here's a quick example of how you can use server functions to perform a mutation on the server and invalidate the data on the client:
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-import { z } from 'zod'
-import { dbUpdateUser } from '...'
-
-const UserSchema = z.object({
- id: z.string(),
- name: z.string(),
-})
-export type User = z.infer
-
-export const updateUser = createServerFn({ method: 'POST' })
- .validator(UserSchema)
- .handler(({ data }) => dbUpdateUser(data))
-
-// Somewhere else in your application
-import { useQueryClient } from '@tanstack/react-query'
-import { useRouter } from '@tanstack/react-router'
-import { useServerFn } from '@tanstack/react-start'
-import { updateUser, type User } from '...'
-
-export function useUpdateUser() {
- const router = useRouter()
- const queryClient = useQueryClient()
- const _updateUser = useServerFn(updateUser)
-
- return useCallback(
- async (user: User) => {
- const result = await _updateUser({ data: user })
-
- router.invalidate()
- queryClient.invalidateQueries({
- queryKey: ['users', 'updateUser', user.id],
- })
-
- return result
- },
- [router, queryClient, _updateUser],
- )
-}
-
-// Somewhere else in your application
-import { useUpdateUser } from '...'
-
-function MyComponent() {
- const updateUser = useUpdateUser()
- const onClick = useCallback(async () => {
- await updateUser({ id: '1', name: 'John' })
- console.log('Updated user')
- }, [updateUser])
-
- return
-}
-```
-
-To learn more about mutations, check out the [mutations guide](/router/latest/docs/framework/react/guide/data-mutations).
-
-## Data Loading
-
-Another powerful feature of TanStack Router is data loading. This allows you to fetch data for SSR and preload route data before it is rendered. This is done using the `loader` function of a route.
-
-Here's a quick overview of how data loading works:
-
-- Data loading is done using the `loader` function of a route.
-- Data loaders are **isomorphic**, meaning they are executed on both the server and the client.
-- For performing server-only logic, call a server function from within the loader.
-- Similar to TanStack Query, data loaders are cached on the client and are re-used and even re-fetched in the background when the data is stale.
-
-To learn more about data loading, check out the [data loading guide](/router/latest/docs/framework/react/guide/data-loading).
diff --git a/docs/start/framework/react/middleware.md b/docs/start/framework/react/middleware.md
index ecae7a9a87..9f56b7d441 100644
--- a/docs/start/framework/react/middleware.md
+++ b/docs/start/framework/react/middleware.md
@@ -3,289 +3,153 @@ id: middleware
title: Middleware
---
-## What is Server Function Middleware?
+Middleware customizes server function behavior with shared logic like authentication, validation, and logging. It executes before and after your server functions in a composable chain.
-Middleware allows you to customize the behavior of server functions created with `createServerFn` with things like shared validation, context, and much more. Middleware can even depend on other middleware to create a chain of operations that are executed hierarchically and in order.
+## Middleware Types
-## What kinds of things can I do with Middleware in my Server Functions?
+There are two types of middleware:
-- **Authentication**: Verify a user's identity before executing a server function.
-- **Authorization**: Check if a user has the necessary permissions to execute a server function.
-- **Logging**: Log requests, responses, and errors.
-- **Observability**: Collect metrics, traces, and logs.
-- **Provide Context**: Attach data to the request object for use in other middleware or server functions.
-- **Error Handling**: Handle errors in a consistent way.
-- And many more! The possibilities are up to you!
-
-## Defining Middleware for Server Functions
-
-Middleware is defined using the `createMiddleware` function. This function returns a `Middleware` object that can be used to continue customizing the middleware with methods like `middleware`, `validator`, `server`, and `client`.
+**Server Middleware** (default) - Works everywhere middleware can be used, including server routes:
```tsx
-import { createMiddleware } from '@tanstack/react-start'
-
-const loggingMiddleware = createMiddleware({ type: 'function' }).server(
- async ({ next, data }) => {
- console.log('Request received:', data)
- const result = await next()
- console.log('Response processed:', result)
- return result
- },
-)
+const loggingMiddleware = createMiddleware().server(({ next }) => {
+ console.log('Request received')
+ const result = await next()
+ console.log('Response processed')
+ return result
+})
```
-## Using Middleware in Your Server Functions
-
-Once you've defined your middleware, you can use it in combination with the `createServerFn` function to customize the behavior of your server functions.
+**Function Middleware** - Adds input validation and client-side lifecycle for server functions:
```tsx
-import { createServerFn } from '@tanstack/react-start'
-import { loggingMiddleware } from './middleware'
-
-const fn = createServerFn()
- .middleware([loggingMiddleware])
- .handler(async () => {
- // ...
+const validatingMiddleware = createMiddleware({ type: 'function' })
+ .validator(zodValidator(schema))
+ .client(({ next }) => {
+ console.log('Client: sending request')
+ return next()
+ })
+ .server(({ next, data }) => {
+ console.log('Server: validated data:', data) // Type-safe!
+ return next()
})
```
-## Middleware Methods
+### When to Use Each Type
-Several methods are available to customize the middleware. If you are (hopefully) using TypeScript, the order of these methods is enforced by the type system to ensure maximum inference and type safety.
+- **Server Middleware** (default): Use for authentication, logging, context sharing, and any server-only logic. Works with both server functions and server routes.
+- **Function Middleware**: Use when you need input validation or client-side request/response handling for server functions.
-- `middleware`: Add a middleware to the chain.
-- `validator`: Modify the data object before it is passed to this middleware and any nested middleware.
-- `server`: Define server-side logic that the middleware will execute before any nested middleware and ultimately a server function, and also provide the result to the next middleware.
-- `client`: Define client-side logic that the middleware will execute before any nested middleware and ultimately the client-side RPC function (or the server-side function), and also provide the result to the next middleware.
+### Method Order
-## The `middleware` method
+When using TypeScript, the order of middleware methods is enforced by the type system for maximum inference and type safety. The recommended order is: `middleware` → `validator` → `server` → `client`.
-The `middleware` method is used to dependency middleware to the chain that will executed **before** the current middleware. Just call the `middleware` method with an array of middleware objects.
+## Common Use Cases
+
+- **Authentication**: Verify user identity
+- **Authorization**: Check permissions
+- **Logging**: Track requests and responses
+- **Validation**: Validate input data
+- **Context**: Share data between middleware
+- **Error Handling**: Handle errors consistently
+
+## Server Method
+
+The `server` method defines logic that runs on the server before and after nested middleware. It receives `next`, `data`, and `context`:
```tsx
-import { createMiddleware } from '@tanstack/react-start'
+const authMiddleware = createMiddleware().server(async ({ next, context }) => {
+ // Check authentication
+ if (!context.user) {
+ throw new Error('Unauthorized')
+ }
-const loggingMiddleware = createMiddleware({ type: 'function' }).middleware([
- authMiddleware,
- loggingMiddleware,
-])
+ // Continue to next middleware/handler
+ const result = await next()
+ return result
+})
```
-Type-safe context and payload validation are also inherited from parent middlewares!
+**Always call `next()` and return its result** to continue the middleware chain.
-## The `validator` method
+### Modifying Server Response
-The `validator` method is used to modify the data object before it is passed to this middleware, nested middleware, and ultimately the server function. This method should receive a function that takes the data object and returns a validated (and optionally modified) data object. It's common to use a validation library like `zod` to do this. Here is an example:
+Server middleware can modify the response using the same [Server Function Context Utilities](../server-functions.md#server-function-context) to read and modify request headers, status codes, etc:
+
+```tsx
+import { setHeader } from '@tanstack/react-start/server'
+
+const headerMiddleware = createMiddleware().server(({ next }) => {
+ // Modify response headers
+ setHeader('X-Custom-Header', 'value')
+ return next()
+})
+```
+
+## Adding Validation
+
+**Function middleware** can validate input data using the `validator` method:
```tsx
import { createMiddleware } from '@tanstack/react-start'
import { zodValidator } from '@tanstack/zod-adapter'
import { z } from 'zod'
-const mySchema = z.object({
- workspaceId: z.string(),
+const schema = z.object({
+ userId: z.string(),
})
-const workspaceMiddleware = createMiddleware({ type: 'function' })
- .validator(zodValidator(mySchema))
+const validateUserMiddleware = createMiddleware({ type: 'function' })
+ .validator(zodValidator(schema))
.server(({ next, data }) => {
- console.log('Workspace ID:', data.workspaceId)
+ console.log('Valid user ID:', data.userId) // Type-safe!
return next()
})
```
-## The `server` method
+> **Note**: Only function middleware supports validation. Server middleware cannot use the `validator` method.
-The `server` method is used to define **server-side** logic that the middleware will execute both before and after any nested middleware and ultimately a server function. This method receives an object with the following properties:
+## Passing Context
-- `next`: A function that, when called, will execute the next middleware in the chain.
-- `data`: The data object that was passed to the server function.
-- `context`: An object that stores data from parent middleware. It can be extended with additional data that will be passed to child middleware.
-
-## Returning the required result from `next`
-
-The `next` function is used to execute the next middleware in the chain. **You must await and return (or return directly) the result of the `next` function provided to you** for the chain to continue executing.
+Middleware can share data through context. Pass context to the next middleware using the `context` property:
```tsx
-import { createMiddleware } from '@tanstack/react-start'
+const userMiddleware = createMiddleware().server(({ next }) => {
+ return next({
+ context: {
+ user: { id: '123', name: 'John' },
+ },
+ })
+})
-const loggingMiddleware = createMiddleware({ type: 'function' }).server(
- async ({ next }) => {
- console.log('Request received')
- const result = await next()
- console.log('Response processed')
- return result
- },
-)
-```
-
-## Providing context to the next middleware via `next`
-
-The `next` function can be optionally called with an object that has a `context` property with an object value. Whatever properties you pass to this `context` value will be merged into the parent `context` and provided to the next middleware.
-
-```tsx
-import { createMiddleware } from '@tanstack/react-start'
-
-const awesomeMiddleware = createMiddleware({ type: 'function' }).server(
- ({ next }) => {
- return next({
- context: {
- isAwesome: Math.random() > 0.5,
- },
- })
- },
-)
-
-const loggingMiddleware = createMiddleware({ type: 'function' })
- .middleware([awesomeMiddleware])
+const logUserMiddleware = createMiddleware()
+ .middleware([userMiddleware])
.server(async ({ next, context }) => {
- console.log('Is awesome?', context.isAwesome)
+ console.log('User:', context.user.name) // Type-safe access
return next()
})
```
## Client-Side Logic
-Despite server functions being mostly server-side bound operations, there is still plenty of client-side logic surrounding the outgoing RPC request from the client. This means that we can also define client-side logic in middleware that will execute on the client side around any nested middleware and ultimately the RPC function and its response to the client.
-
-## Client-side Payload Validation
-
-By default, middleware validation is only performed on the server to keep the client bundle size small. However, you may also choose to validate data on the client side by passing the `validateClient: true` option to the `createMiddleware` function. This will cause the data to be validated on the client side before being sent to the server, potentially saving a round trip.
-
-> Why can't I pass a different validation schema for the client?
->
-> The client-side validation schema is derived from the server-side schema. This is because the client-side validation schema is used to validate the data before it is sent to the server. If the client-side schema were different from the server-side schema, the server would receive data that it did not expect, which could lead to unexpected behavior.
+**Function middleware** can run on the client side to handle outgoing requests and responses:
```tsx
-import { createMiddleware } from '@tanstack/react-start'
-import { zodValidator } from '@tanstack/zod-adapter'
-import { z } from 'zod'
-
-const workspaceMiddleware = createMiddleware({ validateClient: true })
- .validator(zodValidator(mySchema))
- .server(({ next, data }) => {
- console.log('Workspace ID:', data.workspaceId)
- return next()
- })
-```
-
-## The `client` method
-
-Client middleware logic is defined using the `client` method on a `Middleware` object. This method is used to define client-side logic that the middleware will execute both before and after any nested middleware and ultimately the client-side RPC function (or the server-side function if you're doing SSR or calling this function from another server function).
-
-**Client-side middleware logic shares much of the same API as logic created with the `server` method, but it is executed on the client side.** This includes:
-
-- Requiring the `next` function to be called to continue the chain.
-- The ability to provide context to the next client middleware via the `next` function.
-- The ability to modify the data object before it is passed to the next client middleware.
-
-Similar to the `server` function, it also receives an object with the following properties:
-
-- `next`: A function that, when called, will execute the next client middleware in the chain.
-- `data`: The data object that was passed to the client function.
-- `context`: An object that stores data from parent middleware. It can be extended with additional data that will be passed to child middleware.
-
-```tsx
-const loggingMiddleware = createMiddleware({ type: 'function' }).client(
+const clientLoggingMiddleware = createMiddleware({ type: 'function' }).client(
async ({ next }) => {
- console.log('Request sent')
+ console.log('Sending request...')
const result = await next()
- console.log('Response received')
+ console.log('Received response:', result)
return result
},
)
```
-## Sending client context to the server
+### Adding Request Headers
-**Client context is NOT sent to the server by default since this could end up unintentionally sending large payloads to the server.** If you need to send client context to the server, you must call the `next` function with a `sendContext` property and object to transmit any data to the server. Any properties passed to `sendContext` will be merged, serialized and sent to the server along with the data and will be available on the normal context object of any nested server middleware.
+Add headers to outgoing requests using the `headers` property:
```tsx
-const requestLogger = createMiddleware({ type: 'function' })
- .client(async ({ next, context }) => {
- return next({
- sendContext: {
- // Send the workspace ID to the server
- workspaceId: context.workspaceId,
- },
- })
- })
- .server(async ({ next, data, context }) => {
- // Woah! We have the workspace ID from the client!
- console.log('Workspace ID:', context.workspaceId)
- return next()
- })
-```
-
-## Client-Sent Context Security
-
-You may have noticed that in the example above that while client-sent context is type-safe, it is is not required to be validated at runtime. If you pass dynamic user-generated data via context, that could pose a security concern, so **if you are sending dynamic data from the client to the server via context, you should validate it in the server-side middleware before using it.** Here's an example:
-
-```tsx
-import { zodValidator } from '@tanstack/zod-adapter'
-import { z } from 'zod'
-
-const requestLogger = createMiddleware({ type: 'function' })
- .client(async ({ next, context }) => {
- return next({
- sendContext: {
- workspaceId: context.workspaceId,
- },
- })
- })
- .server(async ({ next, data, context }) => {
- // Validate the workspace ID before using it
- const workspaceId = zodValidator(z.number()).parse(context.workspaceId)
- console.log('Workspace ID:', workspaceId)
- return next()
- })
-```
-
-## Sending server context to the client
-
-Similar to sending client context to the server, you can also send server context to the client by calling the `next` function with a `sendContext` property and object to transmit any data to the client. Any properties passed to `sendContext` will be merged, serialized and sent to the client along with the response and will be available on the normal context object of any nested client middleware. The returned object of calling `next` in `client` contains the context sent from server to the client and is type-safe. Middleware is able to infer the context sent from the server to the client from previous middleware chained from the `middleware` function.
-
-> [!WARNING]
-> The return type of `next` in `client` can only be inferred from middleware known in the current middleware chain. Therefore the most accurate return type of `next` is in middleware at the end of the middleware chain
-
-```tsx
-const serverTimer = createMiddleware({ type: 'function' }).server(
- async ({ next }) => {
- return next({
- sendContext: {
- // Send the current time to the client
- timeFromServer: new Date(),
- },
- })
- },
-)
-
-const requestLogger = createMiddleware({ type: 'function' })
- .middleware([serverTimer])
- .client(async ({ next }) => {
- const result = await next()
- // Woah! We have the time from the server!
- console.log('Time from the server:', result.context.timeFromServer)
-
- return result
- })
-```
-
-## Reading/Modifying the Server Response
-
-Middleware that uses the `server` method executes in the same context as server functions, so you can follow the exact same [Server Function Context Utilities](../server-functions.md#server-function-context) to read and modify anything about the request headers, status codes, etc.
-
-## Modifying the Client Request
-
-Middleware that uses the `client` method executes in a **completely different client-side context** than server functions, so you can't use the same utilities to read and modify the request. However, you can still modify the request returning additional properties when calling the `next` function. Currently supported properties are:
-
-- `headers`: An object containing headers to be added to the request.
-
-Here's an example of adding an `Authorization` header any request using this middleware:
-
-```tsx
-import { getToken } from 'my-auth-library'
-
const authMiddleware = createMiddleware({ type: 'function' }).client(
async ({ next }) => {
return next({
@@ -297,132 +161,166 @@ const authMiddleware = createMiddleware({ type: 'function' }).client(
)
```
-## Using Middleware
+> **Note**: Only function middleware supports client-side logic. Server middleware cannot use the `client` method.
-Middleware can be used in two different ways:
+### Client-Server Context
-- **Global Middleware**: Middleware that should be executed for every request.
-- **Server Function Middleware**: Middleware that should be executed for a specific server function.
+**Function middleware** can send data between client and server using `sendContext`. Client context is not sent by default:
+
+```tsx
+const contextMiddleware = createMiddleware({ type: 'function' })
+ .client(({ next }) => {
+ return next({
+ sendContext: { userId: '123' },
+ })
+ })
+ .server(({ next, context }) => {
+ console.log('User ID from client:', context.userId)
+ return next({
+ sendContext: { timestamp: Date.now() },
+ })
+ })
+```
+
+**Security note**: Always validate client-sent context on the server before use.
+
+```tsx
+import { zodValidator } from '@tanstack/zod-adapter'
+import { z } from 'zod'
+
+// Validate client-sent context for security
+const secureMiddleware = createMiddleware({ type: 'function' })
+ .client(({ next }) => {
+ return next({
+ sendContext: { workspaceId: getUserWorkspace() },
+ })
+ })
+ .server(({ next, context }) => {
+ // Validate before using
+ const workspaceId = zodValidator(z.string()).parse(context.workspaceId)
+ return next({ context: { validatedWorkspaceId: workspaceId } })
+ })
+```
+
+### Server-to-Client Context
+
+Server middleware can also send context back to the client:
+
+```tsx
+const serverTimerMiddleware = createMiddleware({ type: 'function' })
+ .server(({ next }) => {
+ return next({
+ sendContext: { serverTime: new Date().toISOString() },
+ })
+ })
+ .client(async ({ next }) => {
+ const result = await next()
+ console.log('Server time:', result.context.serverTime)
+ return result
+ })
+```
+
+> **Warning**: The return type of `next` in client middleware can only be inferred from middleware known in the current middleware chain. For the most accurate return types, place middleware with server-to-client context at the end of the chain.
## Global Middleware
-Global middleware runs automatically for every server function in your application. This is useful for functionality like authentication, logging, and monitoring that should apply to all requests.
-
-To use global middleware, create a `global-middleware.ts` file in your project (typically at `app/global-middleware.ts`). This file runs in both client and server environments and is where you register global middleware.
-
-Here's how to register global middleware:
+Apply middleware to all server functions by registering it globally. Both server and function middleware can be used globally:
```tsx
// app/global-middleware.ts
import { registerGlobalMiddleware } from '@tanstack/react-start'
-import { authMiddleware } from './middleware'
+
+const globalAuthMiddleware = createMiddleware().server(({ next, context }) => {
+ // Authentication logic
+ return next({ context: { user: getCurrentUser() } })
+})
registerGlobalMiddleware({
- middleware: [authMiddleware],
+ middleware: [globalAuthMiddleware],
})
```
-### Global Middleware Type Safety
-
-Global middleware types are inherently **detached** from server functions themselves. This means that if a global middleware supplies additional context to server functions or other server function specific middleware, the types will not be automatically passed through to the server function or other server function specific middleware.
+For type safety with global middleware, include it in your server function's middleware array:
```tsx
-// app/global-middleware.ts
-registerGlobalMiddleware({
- middleware: [authMiddleware],
-})
-```
-
-```tsx
-// authMiddleware.ts
-const authMiddleware = createMiddleware({ type: 'function' }).server(
- ({ next, context }) => {
- console.log(context.user) // <-- This will not be typed!
- // ...
- },
-)
-```
-
-To solve this, add the global middleware you are trying to reference to the server function's middleware array. **The global middleware will be deduped to a single entry (the global instance), and your server function will receive the correct types.**
-
-Here's an example of how this works:
-
-```tsx
-import { authMiddleware } from './authMiddleware'
-
const fn = createServerFn()
- .middleware([authMiddleware])
+ .middleware([globalAuthMiddleware]) // Types will be inferred
.handler(async ({ context }) => {
- console.log(context.user)
- // ...
+ console.log(context.user) // Type-safe!
})
```
-## Middleware Execution Order
+## Chaining Middleware
-Middleware is executed dependency-first, starting with global middleware, followed by server function middleware. The following example will log the following in this order:
-
-- `globalMiddleware1`
-- `globalMiddleware2`
-- `a`
-- `b`
-- `c`
-- `d`
+Chain multiple middleware together using the `middleware` method. Type-safe context and validation are inherited from parent middleware:
```tsx
-const globalMiddleware1 = createMiddleware({ type: 'function' }).server(
- async ({ next }) => {
- console.log('globalMiddleware1')
- return next()
- },
-)
-
-const globalMiddleware2 = createMiddleware({ type: 'function' }).server(
- async ({ next }) => {
- console.log('globalMiddleware2')
- return next()
- },
-)
-
-registerGlobalMiddleware({
- middleware: [globalMiddleware1, globalMiddleware2],
+const authMiddleware = createMiddleware().server(({ next }) => {
+ // Authentication logic
+ return next({ context: { user: getCurrentUser() } })
})
-const a = createMiddleware({ type: 'function' }).server(async ({ next }) => {
- console.log('a')
- return next()
-})
-
-const b = createMiddleware({ type: 'function' })
- .middleware([a])
- .server(async ({ next }) => {
- console.log('b')
+const loggingMiddleware = createMiddleware()
+ .middleware([authMiddleware])
+ .server(({ next, context }) => {
+ console.log('User:', context.user) // Type-safe access to inherited context
return next()
})
-
-const c = createMiddleware({ type: 'function' })
- .middleware()
- .server(async ({ next }) => {
- console.log('c')
- return next()
- })
-
-const d = createMiddleware({ type: 'function' })
- .middleware([b, c])
- .server(async () => {
- console.log('d')
- })
-
-const fn = createServerFn()
- .middleware([d])
- .server(async () => {
- console.log('fn')
- })
```
-## Environment Tree Shaking
+## Execution Order
-Middleware functionality is tree-shaken based on the environment for each bundle produced.
+Middleware executes in a nested, wrapping pattern. Each middleware wraps around the next, creating an "onion" structure where execution flows down the chain, then back up in reverse order:
-- On the server, nothing is tree-shaken, so all code used in middleware will be included in the server bundle.
-- On the client, all server-specific code is removed from the client bundle. This means any code used in the `server` method is always removed from the client bundle. If `validateClient` is set to `true`, the client-side validation code will be included in the client bundle, otherwise `data` validation code will also be removed.
+```tsx
+const authMiddleware = createMiddleware().server(async ({ next }) => {
+ console.log('🔐 Auth: Before')
+ const result = await next()
+ console.log('🔐 Auth: After')
+ return result
+})
+
+const loggingMiddleware = createMiddleware().server(async ({ next }) => {
+ console.log('📝 Log: Before')
+ const result = await next()
+ console.log('📝 Log: After')
+ return result
+})
+
+const myServerFn = createServerFn()
+ .middleware([authMiddleware, loggingMiddleware])
+ .handler(async () => {
+ console.log('⚡ Handler: Executing')
+ return { message: 'Success!' }
+ })
+
+// When called, prints:
+// 🔐 Auth: Before
+// 📝 Log: Before
+// ⚡ Handler: Executing
+// 📝 Log: After
+// 🔐 Auth: After
+```
+
+### Dependency Order
+
+Middleware executes in dependency order: global middleware first, then local middleware dependencies:
+
+```tsx
+// 1. Global middleware (always first)
+registerGlobalMiddleware({ middleware: [globalAuth] })
+
+// 2. Then local middleware dependencies in order
+const combined = createMiddleware()
+ .middleware([authMiddleware, loggingMiddleware])
+ .server(({ next }) => next())
+
+// Full execution: globalAuth → authMiddleware → loggingMiddleware → combined → handler
+```
+
+## Tree Shaking
+
+Code is automatically optimized for each environment:
+
+- **Server**: All middleware code is included
+- **Client**: Server-only code (like `server` method logic) is removed from the client bundle
diff --git a/docs/start/framework/react/migrate-from-next-js.md b/docs/start/framework/react/migrate-from-next-js.md
index ea080417f7..95a83e93d4 100644
--- a/docs/start/framework/react/migrate-from-next-js.md
+++ b/docs/start/framework/react/migrate-from-next-js.md
@@ -85,10 +85,11 @@ Now that you've installed the necessary dependencies, update your project config
```ts
// vite.config.ts
-import tailwindcss from '@tailwindcss/vite'
-import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import { defineConfig } from 'vite'
+import { tanstackStart } from '@tanstack/react-start/plugin/vite'
+import viteReact from '@vitejs/plugin-react'
import tsconfigPaths from 'vite-tsconfig-paths'
+import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
server: {
@@ -99,11 +100,12 @@ export default defineConfig({
// Enables Vite to resolve imports using path aliases.
tsconfigPaths(),
tanstackStart({
- tsr: {
+ router: {
// Specifies the directory TanStack Router uses for your routes.
routesDirectory: 'src/app', // Defaults to "src/routes"
},
}),
+ viteReact(),
],
})
```
diff --git a/docs/start/framework/react/observability.md b/docs/start/framework/react/observability.md
index 78e6a2dff3..abab73ba21 100644
--- a/docs/start/framework/react/observability.md
+++ b/docs/start/framework/react/observability.md
@@ -3,31 +3,659 @@ id: observability
title: Observability
---
-Observability is a critical aspect of modern web development, enabling you to monitor, trace, and debug your application’s performance and errors. TanStack Start integrates seamlessly with observability tools to provide comprehensive insights into how your application behaves in production, helping you ensure that everything runs smoothly.
+Observability is a critical aspect of modern web development, enabling you to monitor, trace, and debug your application's performance and errors. TanStack Start provides built-in patterns for observability and integrates seamlessly with external tools to give you comprehensive insights into your application.
-## What should I use?
-
-TanStack Start is **designed to work with any observability tool**, so you can integrate your preferred solution using the full-stack APIs provided by TanStack Start. Whether you need logging, tracing, or error monitoring, TanStack Start is flexible enough to meet your observability needs.
-
-However, for the best observability experience, we highly recommend using [Sentry](https://sentry.io?utm_source=tanstack). Sentry is a powerful, full-featured observability platform that provides real-time insights into your application's performance and error tracking.
-
-## What is Sentry?
+## Partner Solution: Sentry
-
+
-Sentry is a leading observability platform that helps developers monitor and fix crashes in real-time. With Sentry, you can track errors, performance issues, and trends across your entire stack, from the frontend to the backend. Sentry integrates seamlessly with TanStack Start, enabling you to identify and resolve issues faster, maintain a high level of performance, and deliver a better experience to your users.
+For comprehensive observability, we recommend [Sentry](https://sentry.io?utm_source=tanstack) - our trusted partner for error tracking and performance monitoring. Sentry provides:
-Sentry’s comprehensive dashboards, alerting capabilities, and in-depth error analysis tools make it an invaluable resource for any development team looking to maintain control over their application’s health in production.
+- **Real-time Error Tracking** - Catch and debug errors across your entire stack
+- **Performance Monitoring** - Track slow transactions and optimize bottlenecks
+- **Release Health** - Monitor deployments and track error rates over time
+- **User Impact Analysis** - Understand how errors affect your users
+- **TanStack Start Integration** - Works seamlessly with server functions and client code
-- To learn more about Sentry, visit the [Sentry website](https://sentry.io?utm_source=tanstack)
-- To sign up, visit the [Sentry dashboard](https://sentry.io/signup?utm_source=tanstack)
+**Quick Setup:**
-## Documentation & APIs
+```tsx
+// Client-side (app.tsx)
+import * as Sentry from '@sentry/react'
-Documentation for integrating different observability tools with TanStack Start is coming soon! Stay tuned for more examples and guides on how to use Sentry effectively with your TanStack Start projects.
+Sentry.init({
+ dsn: import.meta.env.VITE_SENTRY_DSN,
+ environment: import.meta.env.NODE_ENV,
+})
+
+// Server functions
+import * as Sentry from '@sentry/node'
+
+const serverFn = createServerFn().handler(async () => {
+ try {
+ return await riskyOperation()
+ } catch (error) {
+ Sentry.captureException(error)
+ throw error
+ }
+})
+```
+
+[Get started with Sentry →](https://sentry.io/signup?utm_source=tanstack) | [View integration example →](https://github.com/TanStack/router/tree/main/e2e/react-router/sentry-integration)
+
+## Built-in Observability Patterns
+
+TanStack Start's architecture provides several opportunities for built-in observability without external dependencies:
+
+### Server Function Logging
+
+Add logging to your server functions to track execution, performance, and errors:
+
+```tsx
+import { createServerFn } from '@tanstack/react-start'
+
+const getUser = createServerFn({ method: 'GET' })
+ .validator((id: string) => id)
+ .handler(async ({ data: id }) => {
+ const startTime = Date.now()
+
+ try {
+ console.log(`[SERVER] Fetching user ${id}`)
+
+ const user = await db.users.findUnique({ where: { id } })
+
+ if (!user) {
+ console.log(`[SERVER] User ${id} not found`)
+ throw new Error('User not found')
+ }
+
+ const duration = Date.now() - startTime
+ console.log(`[SERVER] User ${id} fetched in ${duration}ms`)
+
+ return user
+ } catch (error) {
+ const duration = Date.now() - startTime
+ console.error(
+ `[SERVER] Error fetching user ${id} after ${duration}ms:`,
+ error,
+ )
+ throw error
+ }
+ })
+```
+
+### Request/Response Middleware
+
+Create middleware to log all requests and responses:
+
+```tsx
+import { createMiddleware } from '@tanstack/react-start'
+
+const requestLogger = createMiddleware().handler(async ({ next }) => {
+ const startTime = Date.now()
+ const timestamp = new Date().toISOString()
+
+ console.log(`[${timestamp}] ${request.method} ${request.url} - Starting`)
+
+ try {
+ const response = await next()
+ const duration = Date.now() - startTime
+
+ console.log(
+ `[${timestamp}] ${request.method} ${request.url} - ${response.status} (${duration}ms)`,
+ )
+
+ return response
+ } catch (error) {
+ const duration = Date.now() - startTime
+ console.error(
+ `[${timestamp}] ${request.method} ${request.url} - Error (${duration}ms):`,
+ error,
+ )
+ throw error
+ }
+})
+
+// Apply to all server routes
+export const Route = createFileRoute('/api/users')({
+ server: {
+ middleware: [requestLogger],
+ handlers: {
+ GET: async () => {
+ return json({ users: await getUsers() })
+ },
+ },
+ },
+})
+```
+
+### Route Performance Monitoring
+
+Track route loading performance on both client and server:
+
+```tsx
+import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/dashboard')({
+ loader: async ({ context }) => {
+ const startTime = Date.now()
+
+ try {
+ const data = await loadDashboardData()
+ const duration = Date.now() - startTime
+
+ // Log server-side performance
+ if (typeof window === 'undefined') {
+ console.log(`[SSR] Dashboard loaded in ${duration}ms`)
+ }
+
+ return data
+ } catch (error) {
+ const duration = Date.now() - startTime
+ console.error(`[LOADER] Dashboard error after ${duration}ms:`, error)
+ throw error
+ }
+ },
+ component: Dashboard,
+})
+
+function Dashboard() {
+ const data = Route.useLoaderData()
+
+ // Track client-side render time
+ React.useEffect(() => {
+ const renderTime = performance.now()
+ console.log(`[CLIENT] Dashboard rendered in ${renderTime}ms`)
+ }, [])
+
+ return
+ )
+}
+
+export function App() {
+ return (
+
+
+
+ )
+}
+
+// Server function error handling
+const riskyOperation = createServerFn().handler(async () => {
+ try {
+ return await performOperation()
+ } catch (error) {
+ // Log server errors with context
+ console.error('[SERVER ERROR]:', {
+ error: error.message,
+ stack: error.stack,
+ timestamp: new Date().toISOString(),
+ // Add request context if available
+ })
+
+ // Return user-friendly error
+ throw new Error('Operation failed. Please try again.')
+ }
+})
+```
+
+### Performance Metrics Collection
+
+Collect and expose basic performance metrics:
+
+```tsx
+// utils/metrics.ts
+class MetricsCollector {
+ private metrics = new Map()
+
+ recordTiming(name: string, duration: number) {
+ if (!this.metrics.has(name)) {
+ this.metrics.set(name, [])
+ }
+ this.metrics.get(name)!.push(duration)
+ }
+
+ getStats(name: string) {
+ const timings = this.metrics.get(name) || []
+ if (timings.length === 0) return null
+
+ const sorted = timings.sort((a, b) => a - b)
+ return {
+ count: timings.length,
+ avg: timings.reduce((a, b) => a + b, 0) / timings.length,
+ p50: sorted[Math.floor(sorted.length * 0.5)],
+ p95: sorted[Math.floor(sorted.length * 0.95)],
+ min: sorted[0],
+ max: sorted[sorted.length - 1],
+ }
+ }
+
+ getAllStats() {
+ const stats: Record = {}
+ for (const [name] of this.metrics) {
+ stats[name] = this.getStats(name)
+ }
+ return stats
+ }
+}
+
+export const metrics = new MetricsCollector()
+
+// Metrics endpoint
+// routes/metrics.ts
+export const Route = createFileRoute('/metrics')({
+ server: {
+ handlers: {
+ GET: async () => {
+ return json({
+ system: {
+ uptime: process.uptime(),
+ memory: process.memoryUsage(),
+ timestamp: new Date().toISOString(),
+ },
+ application: metrics.getAllStats(),
+ })
+ },
+ },
+ },
+})
+```
+
+### Debug Headers for Development
+
+Add helpful debug information to responses:
+
+```tsx
+import { createMiddleware } from '@tanstack/react-start'
+
+const debugMiddleware = createMiddleware().handler(async ({ next }) => {
+ const response = await next()
+
+ if (process.env.NODE_ENV === 'development') {
+ response.headers.set('X-Debug-Timestamp', new Date().toISOString())
+ response.headers.set('X-Debug-Node-Version', process.version)
+ response.headers.set('X-Debug-Uptime', process.uptime().toString())
+ }
+
+ return response
+})
+```
+
+### Environment-Specific Logging
+
+Configure different logging strategies for development vs production:
+
+```tsx
+// utils/logger.ts
+import { createIsomorphicFn } from '@tanstack/react-start'
+
+type LogLevel = 'debug' | 'info' | 'warn' | 'error'
+
+const logger = createIsomorphicFn()
+ .server((level: LogLevel, message: string, data?: any) => {
+ const timestamp = new Date().toISOString()
+
+ if (process.env.NODE_ENV === 'development') {
+ // Development: Detailed console logging
+ console[level](`[${timestamp}] [${level.toUpperCase()}]`, message, data)
+ } else {
+ // Production: Structured JSON logging
+ console.log(
+ JSON.stringify({
+ timestamp,
+ level,
+ message,
+ data,
+ service: 'tanstack-start',
+ environment: process.env.NODE_ENV,
+ }),
+ )
+ }
+ })
+ .client((level: LogLevel, message: string, data?: any) => {
+ if (process.env.NODE_ENV === 'development') {
+ console[level](`[CLIENT] [${level.toUpperCase()}]`, message, data)
+ } else {
+ // Production: Send to analytics service
+ // analytics.track('client_log', { level, message, data })
+ }
+ })
+
+// Usage anywhere in your app
+export { logger }
+
+// Example usage
+const fetchUserData = createServerFn().handler(async ({ data: userId }) => {
+ logger('info', 'Fetching user data', { userId })
+
+ try {
+ const user = await db.users.findUnique({ where: { id: userId } })
+ logger('info', 'User data fetched successfully', { userId })
+ return user
+ } catch (error) {
+ logger('error', 'Failed to fetch user data', {
+ userId,
+ error: error.message,
+ })
+ throw error
+ }
+})
+```
+
+### Simple Error Reporting
+
+Basic error reporting without external dependencies:
+
+```tsx
+// utils/error-reporter.ts
+const errorStore = new Map<
+ string,
+ { count: number; lastSeen: Date; error: any }
+>()
+
+export function reportError(error: Error, context?: any) {
+ const key = `${error.name}:${error.message}`
+ const existing = errorStore.get(key)
+
+ if (existing) {
+ existing.count++
+ existing.lastSeen = new Date()
+ } else {
+ errorStore.set(key, {
+ count: 1,
+ lastSeen: new Date(),
+ error: {
+ name: error.name,
+ message: error.message,
+ stack: error.stack,
+ context,
+ },
+ })
+ }
+
+ // Log immediately
+ console.error('[ERROR REPORTED]:', {
+ error: error.message,
+ count: existing ? existing.count : 1,
+ context,
+ })
+}
+
+// Error reporting endpoint
+// routes/errors.ts
+export const Route = createFileRoute('/admin/errors')({
+ server: {
+ handlers: {
+ GET: async () => {
+ const errors = Array.from(errorStore.entries()).map(([key, data]) => ({
+ id: key,
+ ...data,
+ }))
+
+ return json({ errors })
+ },
+ },
+ },
+})
+```
+
+## External Observability Tools
+
+While TanStack Start provides built-in observability patterns, external tools offer more comprehensive monitoring:
+
+### Other Popular Tools
+
+**Application Performance Monitoring:**
+
+- **[DataDog](https://www.datadoghq.com/)** - Full-stack monitoring with APM
+- **[New Relic](https://newrelic.com/)** - Performance monitoring and alerting
+- **[Honeycomb](https://honeycomb.io/)** - Observability for complex systems
+
+**Error Tracking:**
+
+- **[Bugsnag](https://bugsnag.com/)** - Error monitoring with deployment tracking
+- **[Rollbar](https://rollbar.com/)** - Real-time error alerting
+
+**Analytics & User Behavior:**
+
+- **[PostHog](https://posthog.com/)** - Product analytics with error tracking
+- **[Mixpanel](https://mixpanel.com/)** - Event tracking and user analytics
+
+### OpenTelemetry Integration (Experimental)
+
+[OpenTelemetry](https://opentelemetry.io/) is the industry standard for observability. Here's an experimental approach to integrate it with TanStack Start:
+
+```tsx
+// instrumentation.ts - Initialize before your app
+import { NodeSDK } from '@opentelemetry/sdk-node'
+import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'
+import { Resource } from '@opentelemetry/resources'
+import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
+
+const sdk = new NodeSDK({
+ resource: new Resource({
+ [SemanticResourceAttributes.SERVICE_NAME]: 'tanstack-start-app',
+ [SemanticResourceAttributes.SERVICE_VERSION]: '1.0.0',
+ }),
+ instrumentations: [getNodeAutoInstrumentations()],
+})
+
+// Initialize BEFORE importing your app
+sdk.start()
+```
+
+```tsx
+// Server function tracing
+import { trace, SpanStatusCode } from '@opentelemetry/api'
+
+const tracer = trace.getTracer('tanstack-start')
+
+const getUserWithTracing = createServerFn({ method: 'GET' })
+ .validator((id: string) => id)
+ .handler(async ({ data: id }) => {
+ return tracer.startActiveSpan('get-user', async (span) => {
+ span.setAttributes({
+ 'user.id': id,
+ operation: 'database.query',
+ })
+
+ try {
+ const user = await db.users.findUnique({ where: { id } })
+ span.setStatus({ code: SpanStatusCode.OK })
+ return user
+ } catch (error) {
+ span.recordException(error)
+ span.setStatus({
+ code: SpanStatusCode.ERROR,
+ message: error.message,
+ })
+ throw error
+ } finally {
+ span.end()
+ }
+ })
+ })
+```
+
+```tsx
+// Middleware for automatic tracing
+import { createMiddleware } from '@tanstack/react-start'
+import { trace, SpanStatusCode } from '@opentelemetry/api'
+
+const tracer = trace.getTracer('tanstack-start')
+
+const tracingMiddleware = createMiddleware().handler(
+ async ({ next, request }) => {
+ const url = new URL(request.url)
+
+ return tracer.startActiveSpan(
+ `${request.method} ${url.pathname}`,
+ async (span) => {
+ span.setAttributes({
+ 'http.method': request.method,
+ 'http.url': request.url,
+ 'http.route': url.pathname,
+ })
+
+ try {
+ const response = await next()
+ span.setAttribute('http.status_code', response.status)
+ span.setStatus({ code: SpanStatusCode.OK })
+ return response
+ } catch (error) {
+ span.recordException(error)
+ span.setStatus({
+ code: SpanStatusCode.ERROR,
+ message: error.message,
+ })
+ throw error
+ } finally {
+ span.end()
+ }
+ },
+ )
+ },
+)
+```
+
+> **Note**: The above OpenTelemetry integration is experimental and requires manual setup. We're exploring first-class OpenTelemetry support that would provide automatic instrumentation for server functions, middleware, and route loaders.
+
+### Quick Integration Pattern
+
+Most observability tools follow a similar integration pattern with TanStack Start:
+
+```tsx
+// Initialize in app entry point
+import { initObservabilityTool } from 'your-tool'
+
+initObservabilityTool({
+ dsn: import.meta.env.VITE_TOOL_DSN,
+ environment: import.meta.env.NODE_ENV,
+})
+
+// Server function middleware
+const observabilityMiddleware = createMiddleware().handler(async ({ next }) => {
+ return yourTool.withTracing('server-function', async () => {
+ try {
+ return await next()
+ } catch (error) {
+ yourTool.captureException(error)
+ throw error
+ }
+ })
+})
+```
+
+## Best Practices
+
+### Development vs Production
+
+```tsx
+// Different strategies per environment
+const observabilityConfig = {
+ development: {
+ logLevel: 'debug',
+ enableTracing: true,
+ enableMetrics: false, // Too noisy in dev
+ },
+ production: {
+ logLevel: 'warn',
+ enableTracing: true,
+ enableMetrics: true,
+ enableAlerting: true,
+ },
+}
+```
+
+### Performance Monitoring Checklist
+
+- [ ] **Server Function Performance**: Track execution times
+- [ ] **Route Loading Times**: Monitor loader performance
+- [ ] **Database Query Performance**: Log slow queries
+- [ ] **External API Latency**: Monitor third-party service calls
+- [ ] **Memory Usage**: Track memory consumption patterns
+- [ ] **Error Rates**: Monitor error frequency and types
+
+### Security Considerations
+
+- Never log sensitive data (passwords, tokens, PII)
+- Use structured logging for better parsing
+- Implement log rotation in production
+- Consider compliance requirements (GDPR, CCPA)
+
+## Future OpenTelemetry Support
+
+Direct OpenTelemetry support is coming to TanStack Start, which will provide automatic instrumentation for server functions, middleware, and route loaders without the manual setup shown above.
+
+## Resources
+
+- **[Sentry Documentation](https://docs.sentry.io/)**
+- **[OpenTelemetry Documentation](https://opentelemetry.io/docs/)** - Industry standard observability
+- **[Working Example](https://github.com/TanStack/router/tree/main/examples/react/start-basic)** - See observability patterns in action
diff --git a/docs/start/framework/react/overview.md b/docs/start/framework/react/overview.md
index 73331b0bd5..df85a36fd8 100644
--- a/docs/start/framework/react/overview.md
+++ b/docs/start/framework/react/overview.md
@@ -5,114 +5,38 @@ title: TanStack Start Overview
TanStack Start is a full-stack React framework powered by TanStack Router. It provides a full-document SSR, streaming, server functions, bundling, and more. Thanks to [Vite](https://vite.dev/), it's ready to develop and deploy to any hosting provider or runtime you want!
-## Router or Start?
+## Dependencies
-TanStack Router is a powerful, type-safe, and full-featured routing system for React applications. It is designed to handle the beefiest of full-stack routing requirements with ease. TanStack Start builds on top of Router's type system to provide type-safe full-stack APIs that keep you in the fast lane.
+TanStack Start is built on two key technologies:
-What you get with TanStack Router:
+- **[TanStack Router](https://tanstack.com/router)**: A type-safe router for building web applications with advanced features like nested routing, search params, and data loading
+- **[Vite](https://vite.dev/)**: A modern build tool that provides fast development with hot module replacement and optimized production builds
-- 100% inferred TypeScript support
-- Typesafe navigation
-- Nested Routing and pathless layout routes
-- Built-in Route Loaders w/ SWR Caching
-- Designed for client-side data caches (TanStack Query, SWR, etc.)
-- Automatic route prefetching
-- Asynchronous route elements and error boundaries
-- File-based Route Generation
-- Typesafe JSON-first Search Params state management APIs
-- Path and Search Parameter Schema Validation
-- Search Param Navigation APIs
-- Custom Search Param parser/serializer support
-- Search param middleware
-- Route matching/loading middleware
+## Should I use TanStack Start or just TanStack Router?
-What you get with TanStack Start:
+90% of any framework usually comes down to the router, and TanStack Start is no different. **TanStack Start relies 100% on TanStack Router for its routing system.** In addition to TanStack Router's amazing features, Start enables even more powerful features:
-- Full-document SSR
-- Streaming
-- Server Functions / RPCs
-- Bundling
-- Deployment
-- Full-Stack Type Safety
+- **Full-document SSR** - Server-side rendering for better performance and SEO
+- **Streaming** - Progressive page loading for improved user experience
+- **Server Routes & API Routes** - Build backend endpoints alongside your frontend
+- **Server Functions** - Type-safe RPCs between client and server
+- **Middleware & Context** - Powerful request/response handling and data injection
+- **Full-Stack Bundling** - Optimized builds for both client and server code
+- **Universal Deployment** - Deploy to any Vite-compatible hosting provider
+- **End-to-End Type Safety** - Full TypeScript support across the entire stack
-**In summary, use TanStack Router for client-side routing and TanStack Start for full-stack routing.**
+That said, if you **know with certainty** that you will not need any of the above features, then you may want to consider using TanStack Router alone, which is still a powerful and type-safe SPA routing upgrade over other routers and frameworks.
-## How does it work?
+## Are there limitations?
-TanStack Start uses [Vite](https://vitejs.dev/) to bundle and deploy your application and empowers amazing features like:
+The only relevant limitation is that TanStack Start does not currently support React Server Components, **but we are actively working on integration and expect to support them in the near future.**
-- Provide a unified API for SSR, streaming, and hydration
-- Extract server-only code from your client-side code (e.g. server functions)
-- Bundle your application for deployment to any hosting provider
-
-## When should I use it?
-
-TanStack Start is perfect for you if you want to build a full-stack React application with the following requirements:
-
-- Full-document SSR & Hydration
-- Streaming
-- Server Functions / RPCs
-- Full-Stack Type Safety
-- Robust Routing
-- Rich Client-Side Interactivity
-
-## When might I not want to use it?
-
-TanStack Start is not for you if:
-
-- Your goal is a server-rendered site with zero JS or minimal client-side interactivity
-- You're looking for a React-Server-Component-first framework. (We'll support RSCs soon in our own awesome flavor!)
+Otherwise, TanStack Start provides the same capability as other full-stack frameworks like Next.js, Remix, etc, with even more features and a more powerful developer experience.
## How is TanStack Start funded?
-TanStack works closely with our partners to provide the best possible developer experience while also providing solutions that work anywhere and are vetted by industry experts. Each of our partners plays a unique role in the TanStack ecosystem:
-
-- **Clerk**
-
-
-
-
-
-
-
- The best possible authentication experience for modern web applications, including TanStack Start applications. Clerk provides TanStack Start users with first-class integrations and solutions to auth and collaborates closely with the TanStack team to ensure that TanStack Start provides APIs that are up to date with the latest in auth best practices.
-- **Netlify**
-
-
-
-
-
-
-
- The leading hosting platform for web applications that provides a fast, secure, and reliable environment for deploying your web applications. We work closely with Netlify to ensure that TanStack Start applications not only deploy seamlessly to their platform, but also implement best practices for performance, security, and reliability regardless of where you end up deploying.
-- **Neon**
-
-
-
-
-
-
-
- A serverless, autoscaling Postgres solution purpose-built for modern full-stack apps. Neon offers rich integration opportunities with TanStack Start, including server functions and database-backed routing. Together, we’re simplifying the database experience for developers using TanStack.
-- **Convex**
-
-
-
-
-
-
-
- A serverless database platform that integrates seamlessly with TanStack Start. Convex is designed to simplify the process of managing your application's data and provides a real-time, scalable, and transactional data backend that works well with TanStack Start applications. Convex also collaborates closely with the TanStack team to ensure that TanStack Start provides APIs that are up to date with the latest in database best practices.
-- **Sentry**
-
-
-
-
-
-
-
- A powerful, full-featured observability platform that integrates seamlessly with TanStack Start. Sentry helps developers monitor and fix crashes in real-time and provides insights into your application's performance and error tracking. Sentry collaborates closely with the TanStack team to ensure that TanStack Start provides APIs that are up to date with the latest in observability best practices.
+TanStack is 100% open source, free to use, and always will be. It is built and maintained by an extremely talented and dedicated community of developers and software engineers. TanStack.com (also open source) is owned by TanStack LLC, a privately held company, 100% bootstrapped and self-funded. We are not venture-backed and have never sought investors. To support the development of TanStack Start and other TanStack libraries, TanStack.com partners with [these amazing companies](https://tanstack.com/partners?status=active&libraries=%5B%22start%22%5D) who offer both financial support and resources to help us continue to build the best possible developer experience for the web community.
## Ready to get started?
-Proceed to the next page to learn how to install TanStack Start and create your first app!
+Go to the next page to learn how to install TanStack Start and create your first app!
diff --git a/docs/start/framework/react/quick-start.md b/docs/start/framework/react/quick-start.md
index 75913e24e2..59f20023e7 100644
--- a/docs/start/framework/react/quick-start.md
+++ b/docs/start/framework/react/quick-start.md
@@ -16,7 +16,7 @@ npm run dev
If you'd like to use a different example, you can replace `start-basic` above with the slug of the example you'd like to use from the list below.
-Once you've cloned the example you want, head back to the [Learn the Basics](../learn-the-basics) guide to learn how to use TanStack Start!
+Once you've cloned the example you want, head back to the [Routing](../routing) guide to learn how to use TanStack Start!
## Examples
@@ -52,7 +52,7 @@ npm install
npm run dev
```
-Once you've clone or deployed an example, head back to the [Learn the Basics](../learn-the-basics) guide to learn how to use TanStack Start!
+Once you've clone or deployed an example, head back to the [Routing](../routing) guide to learn how to use TanStack Start!
## Other Router Examples
diff --git a/docs/start/framework/react/routing.md b/docs/start/framework/react/routing.md
new file mode 100644
index 0000000000..21a0b5fce1
--- /dev/null
+++ b/docs/start/framework/react/routing.md
@@ -0,0 +1,242 @@
+---
+id: routing
+title: Routing
+---
+
+TanStack Start is built on top of TanStack Router, so all of the features of TanStack Router are available to you.
+
+> [!NOTE]
+> We highly recommend reading the [TanStack Router documentation](/router/latest/docs/framework/react/overview) to learn more about the features and capabilities of TanStack Router. What you learn here is more of a high-level overview of TanStack Router and how it works in Start.
+
+## The Router
+
+The `router.tsx` file is the file that will dictate the behavior of TanStack Router used within Start. It's located in the `src` directory of your project.
+
+```
+src/
+├── router.tsx
+```
+
+Here, you can configure everything from the default [preloading functionality](/router/latest/docs/framework/react/guide/preloading) to [caching staleness](/router/latest/docs/framework/react/guide/data-loading).
+
+```tsx
+// src/router.tsx
+import { createRouter as createTanStackRouter } from '@tanstack/react-router'
+import { routeTree } from './routeTree.gen'
+
+// You must export a createRouter function that
+// returns a new router instance each time
+export function createRouter() {
+ const router = createTanStackRouter({
+ routeTree,
+ scrollRestoration: true,
+ })
+
+ return router
+}
+
+// You must register your router instance with TanStack Router's type system
+declare module '@tanstack/react-router' {
+ interface Register {
+ router: ReturnType
+ }
+}
+```
+
+## File-Based Routing
+
+Start uses TanStack Router's file-based routing approach to ensure proper code-splitting and advanced type-safety.
+
+You can find your routes in the `src/routes` directory.
+
+```
+src/
+├── routes <-- This is where you put your routes
+│ ├── __root.tsx
+│ ├── index.tsx
+│ ├── about.tsx
+│ ├── posts.tsx
+│ ├── posts/$postId.tsx
+```
+
+## The Root Route
+
+The root route is the top-most route in the entire tree and encapsulates all other routes as children. It's found in the `src/routes/__root.tsx` file and must be named `__root.tsx`.
+
+```
+src/
+├── routes
+│ ├── __root.tsx <-- The root route
+```
+
+- It has no path and is **always** matched
+- Its `component` is **always** rendered
+- This is where you render your document shell, e.g. ``, ``, etc.
+- Because it is **always rendered**, it is the perfect place to construct your application shell and take care of any global logic
+
+```tsx
+// src/routes/__root.tsx
+import {
+ Outlet,
+ createRootRoute,
+ HeadContent,
+ Scripts,
+} 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: 'TanStack Start Starter',
+ },
+ ],
+ }),
+ component: RootComponent,
+})
+
+function RootComponent() {
+ return (
+
+
+
+ )
+}
+
+function RootDocument({ children }: Readonly<{ children: ReactNode }>) {
+ return (
+
+
+
+
+
+ {children}
+
+
+
+ )
+}
+```
+
+Notice the `Scripts` component at the bottom of the `` tag. This is used to load all of the client-side JavaScript for the application and should always be included for proper functionality.
+
+## The HeadContent Component
+
+The `HeadContent` component is used to render the head, title, meta, link, and head-related script tags of the document.
+
+It should be **rendered in the `` tag of your root route's layout.**
+
+## The Outlet Component
+
+The `Outlet` component is used to render the next potentially matching child route. `` doesn't take any props and can be rendered anywhere within a route's component tree. If there is no matching child route, `` will render `null`.
+
+## The Scripts Component
+
+The `Scripts` component is used to render the body scripts of the document.
+
+It should be **rendered in the `` tag of your root route's layout.**
+
+## Route Tree Generation
+
+You may notice a `routeTree.gen.ts` file in your project.
+
+```
+src/
+├── routeTree.gen.ts <-- The generated route tree file
+```
+
+This file is automatically generated when you run TanStack Start (via `npm run dev` or `npm run start`). This file contains the generated route tree and a handful of TS utilities that make TanStack Start's type-safety extremely fast and fully inferred.
+
+**You may gitignore this file, since it is a build artifact.**
+
+## Nested Routing
+
+TanStack Router uses nested routing to match the URL with the correct component tree to render.
+
+For example, given the following routes:
+
+```
+routes/
+├── __root.tsx <-- Renders the component
+├── posts.tsx <-- Renders the component
+├── posts.$postId.tsx <-- Renders the component
+```
+
+And the URL: `/posts/123`
+
+The component tree would look like this:
+
+```
+
+
+
+
+
+```
+
+## Types of Routes
+
+There are a few different types of routes that you can create in your project.
+
+- Index Routes - Matched when the URL is exactly the same as the route's path
+- Dynamic/Wildcard/Splat Routes - Dynamically capture part or all of the URL path into a variable to use in your application
+
+There are also a few different utility route types that you can use to group and organize your routes
+
+- Pathless Layout Routes (Apply layout or logic to a group of routes without nesting them in a path)
+- Non-Nested Routes (Un-nest a route from its parents and render its own component tree)
+- Grouped Routes (Group routes together in a directory simply for organization, without affecting the path hierarchy)
+
+## Route Tree Configuration
+
+The route tree is configured in the `src/routes` directory.
+
+## Creating File Routes
+
+To create a route, create a new file that corresponds to the path of the route you want to create. For example:
+
+| Path | Filename | Type |
+| ---------------- | ------------------- | -------------- |
+| `/` | `index.tsx` | Index Route |
+| `/about` | `about.tsx` | Static Route |
+| | `posts.tsx` | "Layout" Route |
+| `/posts/` | `posts/index.tsx` | Index Route |
+| `/posts/:postId` | `posts/$postId.tsx` | Dynamic Route |
+| `/rest/*` | `rest/$.tsx` | Wildcard Route |
+
+## Defining Routes
+
+To define a route, use the `createFileRoute` function to export the route as the `Route` variable.
+
+For example, to handle the `/posts/:postId` route, you would create a file named `posts/$postId.tsx` here:
+
+```
+src/
+├── routes
+│ ├── posts/$postId.tsx
+```
+
+Then, define the route like this:
+
+```tsx
+// src/routes/posts/$postId.tsx
+import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/posts/$postId')({
+ component: PostComponent,
+})
+```
+
+> [!NOTE]
+> The path string passed to `createFileRoute` is **automatically written and managed by the router for you via the TanStack Router Bundler Plugin or Router CLI.** So, as you create new routes, move routes around or rename routes, the path will be updated for you automatically.
+
+## This is just the "start"
+
+This has been just a high-level overview of how to configure routes using TanStack Router. For more detailed information, please refer to the [TanStack Router documentation](/router/latest/docs/framework/react/routing/file-based-routing).
diff --git a/docs/start/framework/react/server-entry-point.md b/docs/start/framework/react/server-entry-point.md
new file mode 100644
index 0000000000..5325c585c2
--- /dev/null
+++ b/docs/start/framework/react/server-entry-point.md
@@ -0,0 +1,82 @@
+---
+id: server-entry-point
+title: Server Entry Point
+---
+
+# Server Entry Point
+
+> [!NOTE]
+> The server entry point is **optional** out of the box. If not provided, TanStack Start will automatically handle the server entry point for you using the below as a default.
+
+This is done via the `src/server.ts` file.
+
+```tsx
+// src/server.ts
+import {
+ createStartHandler,
+ defaultStreamHandler,
+} from '@tanstack/react-start/server'
+import { createRouter } from './router'
+
+const fetch = createStartHandler({
+ createRouter,
+})(defaultStreamHandler)
+
+export default {
+ fetch,
+}
+```
+
+The entry point must conform to the following interface:
+
+```tsx
+export default {
+ fetch(req: Request): Promise {
+ // ...
+ },
+}
+```
+
+Whether we are statically generating our app or serving it dynamically, the `server.ts` file is the entry point for doing all SSR-related work.
+
+- It's important that a new router is created for each request. This ensures that any data handled by the router is unique to the request.
+- The `defaultStreamHandler` function is used to render our application to a stream, allowing us to take advantage of streaming HTML to the client. (This is the default handler, but you can also use other handlers like `defaultRenderHandler`, or even build your own)
+
+## Custom Server Handlers
+
+You can create custom server handlers to modify how your application is rendered:
+
+```tsx
+// src/server.ts
+import {
+ createStartHandler,
+ defaultStreamHandler,
+} from '@tanstack/react-start/server'
+import { createRouter } from './router'
+
+// Custom handler example
+const customHandler = (request, response) => {
+ // Add custom logic here
+ return defaultStreamHandler(request, response)
+}
+
+const fetch = createStartHandler({
+ createRouter,
+})(customHandler)
+
+export default {
+ fetch,
+}
+```
+
+## Server Configuration
+
+The server entry point is where you can configure server-specific behavior:
+
+- Request/response middleware
+- Custom error handling
+- Authentication logic
+- Database connections
+- Logging and monitoring
+
+This flexibility allows you to customize how your TanStack Start application handles server-side rendering while maintaining the framework's conventions.
diff --git a/docs/start/framework/react/server-functions.md b/docs/start/framework/react/server-functions.md
index 2c6a075b35..7d5e7c6c2b 100644
--- a/docs/start/framework/react/server-functions.md
+++ b/docs/start/framework/react/server-functions.md
@@ -5,1032 +5,224 @@ title: Server Functions
## What are Server Functions?
-Server functions allow you to specify logic that can be invoked almost anywhere (even the client), but run **only** on the server. In fact, they are not so different from an API Route, but with a few key differences:
-
-- They do not have stable public URL.
-- They can be called from anywhere in your application, including loaders, hooks, components, server routes etc.
-
-However, they are similar to regular API Routes in that:
-
-- They have access to the request context, allowing you to read headers, set cookies, and more
-- They can access sensitive information, such as environment variables, without exposing them to the client
-- They can be used to perform any kind of server-side logic, such as fetching data from a database, sending emails, or interacting with other services
-- They can return any value, including primitives, JSON-serializable objects, and even raw Response objects
-- They can throw errors, including redirects and notFounds, which can be handled automatically by the router
-
-> How are server functions different from "React Server Functions"?
->
-> - TanStack Server Functions are not tied to a specific front-end framework, and can be used with any front-end framework or none at all.
-> - TanStack Server Functions are backed by standard HTTP requests and can be called as often as you like without suffering from serial-execution bottlenecks.
-
-## How do they work?
-
-Server functions can be defined anywhere in your application, but must be defined at the top level of a file. They can be called throughout your application, including loaders, hooks, etc. Traditionally, this pattern is known as a Remote Procedure Call (RPC), but due to the isomorphic nature of these functions, we refer to them as server functions.
-
-- On the server bundle, server functions logic is left alone. Nothing needs to be done since they are already in the correct place.
-- On the client, server functions will be removed; they exist only on the server. Any calls to the server function on the client will be replaced with a `fetch` request to the server to execute the server function, and send the response back to the client.
-
-## Server Function Middleware
-
-Server functions can use middleware to share logic, context, common operations, prerequisites, and much more. To learn more about server function middleware, be sure to read about them in the [Middleware guide](../middleware.md).
-
-## Defining Server Functions
-
-> We'd like to thank the [tRPC](https://trpc.io/) team for both the inspiration of TanStack Start's server function design and guidance while implementing it. We love (and recommend) using tRPC for API Routes so much that we insisted on server functions getting the same 1st class treatment and developer experience. Thank you!
-
-Server functions are defined with the `createServerFn` function, from the `@tanstack/react-start` package. This function takes an optional `options` argument for specifying configuration like the HTTP method and response type, and allows you to chain off the result to define things like the body of the server function, input validation, middleware, etc. Here's a simple example:
+Server functions let you define server-only logic that can be called from anywhere in your application - loaders, components, hooks, or other server functions. They run on the server but can be invoked from client code seamlessly.
```tsx
-// getServerTime.ts
import { createServerFn } from '@tanstack/react-start'
export const getServerTime = createServerFn().handler(async () => {
- // Wait for 1 second
- await new Promise((resolve) => setTimeout(resolve, 1000))
- // Return the current time
+ // This runs only on the server
return new Date().toISOString()
})
+
+// Call from anywhere - components, loaders, hooks, etc.
+const time = await getServerTime()
```
-### Configuration Options
+Server functions provide server capabilities (database access, environment variables, file system) while maintaining type safety across the network boundary.
-When creating a server function, you can provide configuration options to customize its behavior:
+## Basic Usage
+
+Server functions are created with `createServerFn()` and can specify HTTP method:
```tsx
import { createServerFn } from '@tanstack/react-start'
-export const getData = createServerFn({
- method: 'GET', // HTTP method to use
- response: 'data', // Response handling mode
-}).handler(async () => {
- // Function implementation
+// GET request (default)
+export const getData = createServerFn().handler(async () => {
+ return { message: 'Hello from server!' }
+})
+
+// POST request
+export const saveData = createServerFn({ method: 'POST' }).handler(async () => {
+ // Server-only logic
+ return { success: true }
})
```
-#### Available Options
+## Where to Call Server Functions
-**`method`**
+Call server functions from:
-Specifies the HTTP method for the server function request:
+- **Route loaders** - Perfect for data fetching
+- **Components** - Use with `useServerFn()` hook
+- **Other server functions** - Compose server logic
+- **Event handlers** - Handle form submissions, clicks, etc.
-```tsx
-method?: 'GET' | 'POST'
-```
-
-By default, server functions use `GET` if not specified.
-
-**`response`**
-
-Controls how responses are processed and returned:
-
-```tsx
-response?: 'data' | 'full' | 'raw'
-```
-
-- `'data'` (default): Automatically parses JSON responses and returns just the data
-- `'full'`: Returns a response object with result data, error information, and context
-- `'raw'`: Returns the raw Response object directly, enabling streaming responses and custom headers
-
-## Where can I call server functions?
-
-- From server-side code
-- From client-side code
-- From other server functions
-
-> [!WARNING]
-> Server functions cannot be called from API Routes. If you need to share business logic between server functions and API Routes, extract the shared logic into utility functions that can be imported by both.
-
-## Accepting Parameters
-
-Server functions accept a single parameter, which can be a variety of types:
-
-- Standard JavaScript types
- - `string`
- - `number`
- - `boolean`
- - `null`
- - `Array`
- - `Object`
-- FormData
-- ReadableStream (of any of the above)
-- Promise (of any of the above)
-
-Here's an example of a server function that accepts a simple string parameter:
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-
-export const greet = createServerFn({
- method: 'GET',
+````tsx
+// In a route loader
+export const Route = createFileRoute('/posts')({
+ loader: () => getPosts(),
})
- .validator((data: string) => data)
- .handler(async (ctx) => {
- return `Hello, ${ctx.data}!`
+
+// In a component
+function PostList() {
+ const getPosts = useServerFn(getServerPosts)
+
+ const { data } = useQuery({
+ queryKey: ['posts'],
+ queryFn: () => getPosts(),
})
-
-greet({
- data: 'John',
-})
-```
-
-## Runtime Input Validation / Type Safety
-
-Server functions can be configured to validate their input data at runtime, while adding type safety. This is useful for ensuring the input is of the correct type before executing the server function, and providing more friendly error messages.
-
-This is done with the `validator` method. It will accept whatever input is passed to the server function. The value (and type) you return from this function will become the input passed to the actual server function handler.
-
-Validators also integrate seamlessly with external validators, if you want to use something like Zod.
-
-### Basic Validation
-
-Here's a simple example of a server function that validates the input parameter:
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-
-type Person = {
- name: string
}
-export const greet = createServerFn({ method: 'GET' })
- .validator((person: unknown): Person => {
- if (typeof person !== 'object' || person === null) {
- throw new Error('Person must be an object')
- }
+## Parameters & Validation
- if ('name' in person && typeof person.name !== 'string') {
- throw new Error('Person.name must be a string')
- }
+Server functions accept a single `data` parameter. Since they cross the network boundary, validation ensures type safety and runtime correctness.
- return person as Person
- })
+### Basic Parameters
+
+```tsx
+import { createServerFn } from '@tanstack/react-start'
+
+export const greetUser = createServerFn({ method: 'GET' })
+ .validator((data: { name: string }) => data)
.handler(async ({ data }) => {
return `Hello, ${data.name}!`
})
-```
-### Using a Validation Library
+await greetUser({ data: { name: 'John' } })
+````
-Validation libraries like Zod can be used like so:
+### Validation with Zod
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-
-import { z } from 'zod'
-
-const Person = z.object({
- name: z.string(),
-})
-
-export const greet = createServerFn({ method: 'GET' })
- .validator((person: unknown) => {
- return Person.parse(person)
- })
- .handler(async (ctx) => {
- return `Hello, ${ctx.data.name}!`
- })
-
-greet({
- data: {
- name: 'John',
- },
-})
-```
-
-## Type Safety
-
-Since server-functions cross the network boundary, it's important to ensure the data being passed to them is not only the right type, but also validated at runtime. This is especially important when dealing with user input, as it can be unpredictable. To ensure developers validate their I/O data, types are reliant on validation. The return type of the `validator` function will be the input to the server function's handler.
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-
-type Person = {
- name: string
-}
-
-export const greet = createServerFn({ method: 'GET' })
- .validator((person: unknown): Person => {
- if (typeof person !== 'object' || person === null) {
- throw new Error('Person must be an object')
- }
-
- if ('name' in person && typeof person.name !== 'string') {
- throw new Error('Person.name must be a string')
- }
-
- return person as Person
- })
- .handler(
- async ({
- data, // Person
- }) => {
- return `Hello, ${data.name}!`
- },
- )
-
-function test() {
- greet({ data: { name: 'John' } }) // OK
- greet({ data: { name: 123 } }) // Error: Argument of type '{ name: number; }' is not assignable to parameter of type 'Person'.
-}
-```
-
-## Inference
-
-Server functions infer their input, and output types based on the input to the `validator`, and return value of `handler` functions, respectively. In fact, the `validator` you define can even have its own separate input/output types, which can be useful if your validator performs transformations on the input data.
-
-To illustrate this, let's take a look at an example using the `zod` validation library:
+For robust validation, use schema libraries like Zod:
```tsx
import { createServerFn } from '@tanstack/react-start'
import { z } from 'zod'
-const transactionSchema = z.object({
- amount: z.string().transform((val) => parseInt(val, 10)),
+const UserSchema = z.object({
+ name: z.string().min(1),
+ age: z.number().min(0),
})
-const createTransaction = createServerFn()
- .validator(transactionSchema)
- .handler(({ data }) => {
- return data.amount // Returns a number
- })
-
-createTransaction({
- data: {
- amount: '123', // Accepts a string
- },
-})
-```
-
-## Non-Validated Inference
-
-While we highly recommend using a validation library to validate your network I/O data, you may, for whatever reason _not_ want to validate your data, but still have type safety. To do this, provide type information to the server function using an identity function as the `validator`, that types the input, and or output to the correct types:
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-
-type Person = {
- name: string
-}
-
-export const greet = createServerFn({ method: 'GET' })
- .validator((d: Person) => d)
- .handler(async (ctx) => {
- return `Hello, ${ctx.data.name}!`
- })
-
-greet({
- data: {
- name: 'John',
- },
-})
-```
-
-## JSON Parameters
-
-Server functions can accept JSON-serializable objects as parameters. This is useful for passing complex data structures to the server:
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-
-type Person = {
- name: string
- age: number
-}
-
-export const greet = createServerFn({ method: 'GET' })
- .validator((data: Person) => data)
+export const createUser = createServerFn({ method: 'POST' })
+ .validator((data) => UserSchema.parse(data))
.handler(async ({ data }) => {
- return `Hello, ${data.name}! You are ${data.age} years old.`
+ // data is fully typed and validated
+ return `Created user: ${data.name}, age ${data.age}`
})
-
-greet({
- data: {
- name: 'John',
- age: 34,
- },
-})
```
-## FormData Parameters
+### Form Data
-Server functions can accept `FormData` objects as parameters
+Handle form submissions with FormData:
```tsx
-import { createServerFn } from '@tanstack/react-start'
-
-export const greetUser = createServerFn({ method: 'POST' })
+export const submitForm = createServerFn({ method: 'POST' })
.validator((data) => {
if (!(data instanceof FormData)) {
- throw new Error('Invalid form data')
- }
- const name = data.get('name')
- const age = data.get('age')
-
- if (!name || !age) {
- throw new Error('Name and age are required')
+ throw new Error('Expected FormData')
}
return {
- name: name.toString(),
- age: parseInt(age.toString(), 10),
+ name: data.get('name')?.toString() || '',
+ email: data.get('email')?.toString() || '',
}
})
- .handler(async ({ data: { name, age } }) => {
- return `Hello, ${name}! You are ${age} years old.`
+ .handler(async ({ data }) => {
+ // Process form data
+ return { success: true }
})
-
-// Usage
-function Test() {
- return (
-
- )
-}
```
-## Server Function Context
+## Error Handling & Redirects
-In addition to the single parameter that server functions accept, you can also access server request context from within any server function using utilities from `@tanstack/react-start/server`. Under the hood, we use [Unjs](https://unjs.io/)'s `h3` package to perform cross-platform HTTP requests.
+Server functions can throw errors, redirects, and not-found responses that are handled automatically when called from route lifecycles or components using `useServerFn()`.
-There are many context functions available to you for things like:
-
-- Accessing the request context
-- Accessing/setting headers
-- Accessing/setting sessions/cookies
-- Setting response status codes and status messages
-- Dealing with multi-part form data
-- Reading/Setting custom server context properties
-
-For a full list of available context functions, see all of the available [h3 Methods](https://h3.unjs.io/utils/request) or inspect the [@tanstack/start-server-core Source Code](https://github.com/TanStack/router/tree/main/packages/start-server-core/src).
-
-For starters, here are a few examples:
-
-## Accessing the Request Context
-
-Let's use the `getWebRequest` function to access the request itself from within a server function:
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-import { getWebRequest } from '@tanstack/react-start/server'
-
-export const getServerTime = createServerFn({ method: 'GET' }).handler(
- async () => {
- const request = getWebRequest()
-
- console.log(request.method) // GET
-
- console.log(request.headers.get('User-Agent')) // Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3
- },
-)
-```
-
-## Accessing Headers
-
-Use the `getHeaders` function to access all headers from within a server function:
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-import { getHeaders } from '@tanstack/react-start/server'
-
-export const getServerTime = createServerFn({ method: 'GET' }).handler(
- async () => {
- console.log(getHeaders())
- // {
- // "accept": "*/*",
- // "accept-encoding": "gzip, deflate, br",
- // "accept-language": "en-US,en;q=0.9",
- // "connection": "keep-alive",
- // "host": "localhost:3000",
- // ...
- // }
- },
-)
-```
-
-You can also access individual headers using the `getHeader` function:
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-import { getHeader } from '@tanstack/react-start/server'
-
-export const getServerTime = createServerFn({ method: 'GET' }).handler(
- async () => {
- console.log(getHeader('User-Agent')) // Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3
- },
-)
-```
-
-## Returning Values
-
-Server functions can return a few different types of values:
-
-- Primitives
-- JSON-serializable objects
-- `redirect` errors (can also be thrown)
-- `notFound` errors (can also be thrown)
-- Raw Response objects
-
-## Returning Primitives and JSON
-
-To return any primitive or JSON-serializable object, simply return the value from the server function:
+### Basic Errors
```tsx
import { createServerFn } from '@tanstack/react-start'
-export const getServerTime = createServerFn({ method: 'GET' }).handler(
- async () => {
- return new Date().toISOString()
- },
-)
-
-export const getServerData = createServerFn({ method: 'GET' }).handler(
- async () => {
- return {
- message: 'Hello, World!',
- }
- },
-)
-```
-
-By default, server functions assume that any non-Response object returned is either a primitive or JSON-serializable object.
-
-## Responding with Custom Headers
-
-To respond with custom headers, you can use the `setHeader` function:
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-import { setHeader } from '@tanstack/react-start/server'
-
-export const getServerTime = createServerFn({ method: 'GET' }).handler(
- async () => {
- setHeader('X-Custom-Header', 'value')
- return new Date().toISOString()
- },
-)
-```
-
-## Responding with Custom Status Codes
-
-To respond with a custom status code, you can use the `setResponseStatus` function:
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-import { setResponseStatus } from '@tanstack/react-start/server'
-
-export const getServerTime = createServerFn({ method: 'GET' }).handler(
- async () => {
- setResponseStatus(201)
- return new Date().toISOString()
- },
-)
-```
-
-## Returning Raw Response objects
-
-To return a raw Response object, return a Response object from the server function and set `response: 'raw'`:
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-
-export const getServerTime = createServerFn({
- method: 'GET',
- response: 'raw',
-}).handler(async () => {
- // Read a file from s3
- return fetch('https://example.com/time.txt')
-})
-```
-
-The response: 'raw' option also allows for streaming responses among other things:
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-
-export const streamEvents = createServerFn({
- method: 'GET',
- response: 'raw',
-}).handler(async ({ signal }) => {
- // Create a ReadableStream to send chunks of data
- const stream = new ReadableStream({
- async start(controller) {
- // Send initial response immediately
- controller.enqueue(new TextEncoder().encode('Connection established\n'))
-
- let count = 0
- const interval = setInterval(() => {
- // Check if the client disconnected
- if (signal.aborted) {
- clearInterval(interval)
- controller.close()
- return
- }
-
- // Send a data chunk
- controller.enqueue(
- new TextEncoder().encode(
- `Event ${++count}: ${new Date().toISOString()}\n`,
- ),
- )
-
- // End after 10 events
- if (count >= 10) {
- clearInterval(interval)
- controller.close()
- }
- }, 1000)
-
- // Ensure we clean up if the request is aborted
- signal.addEventListener('abort', () => {
- clearInterval(interval)
- controller.close()
- })
- },
- })
-
- // Return a streaming response
- return new Response(stream, {
- headers: {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- Connection: 'keep-alive',
- },
- })
-})
-```
-
-The `response: 'raw'` option is particularly useful for:
-
-- Streaming APIs where data is sent incrementally
-- Server-sent events
-- Long-polling responses
-- Custom content types and binary data
-
-## Throwing Errors
-
-Aside from special `redirect` and `notFound` errors, server functions can throw any custom error. These errors will be serialized and sent to the client as a JSON response along with a 500 status code.
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-
-export const doStuff = createServerFn({ method: 'GET' }).handler(async () => {
- throw new Error('Something went wrong!')
-})
-
-// Usage
-function Test() {
- try {
- await doStuff()
- } catch (error) {
- console.error(error)
- // {
- // message: "Something went wrong!",
- // stack: "Error: Something went wrong!\n at doStuff (file:///path/to/file.ts:3:3)"
- // }
+export const riskyFunction = createServerFn().handler(async () => {
+ if (Math.random() > 0.5) {
+ throw new Error('Something went wrong!')
}
+ return { success: true }
+})
+
+// Errors are serialized to the client
+try {
+ await riskyFunction()
+} catch (error) {
+ console.log(error.message) // "Something went wrong!"
}
```
-## Cancellation
+### Redirects
-On the client, server function calls can be cancelled via an `AbortSignal`.
-On the server, an `AbortSignal` will notify if the request closed before execution finished.
+Use redirects for authentication, navigation, etc:
```tsx
import { createServerFn } from '@tanstack/react-start'
+import { redirect } from '@tanstack/react-router'
-export const abortableServerFn = createServerFn().handler(
- async ({ signal }) => {
- return new Promise((resolve, reject) => {
- if (signal.aborted) {
- return reject(new Error('Aborted before start'))
- }
- const timerId = setTimeout(() => {
- console.log('server function finished')
- resolve('server function result')
- }, 1000)
- const onAbort = () => {
- clearTimeout(timerId)
- console.log('server function aborted')
- reject(new Error('Aborted'))
- }
- signal.addEventListener('abort', onAbort, { once: true })
- })
- },
-)
+export const requireAuth = createServerFn().handler(async () => {
+ const user = await getCurrentUser()
-// Usage
-function Test() {
- const controller = new AbortController()
- const serverFnPromise = abortableServerFn({
- signal: controller.signal,
- })
- await new Promise((resolve) => setTimeout(resolve, 500))
- controller.abort()
- try {
- const serverFnResult = await serverFnPromise
- console.log(serverFnResult) // should never get here
- } catch (error) {
- console.error(error) // "signal is aborted without reason"
+ if (!user) {
+ throw redirect({ to: '/login' })
}
-}
-```
-## Calling server functions from within route lifecycles
-
-Server functions can be called normally from route `loader`s, `beforeLoad`s, or any other router-controlled APIs. These APIs are equipped to handle errors, redirects, and notFounds thrown by server functions automatically.
-
-```tsx
-import { getServerTime } from './getServerTime'
-
-export const Route = createFileRoute('/time')({
- loader: async () => {
- const time = await getServerTime()
-
- return {
- time,
- }
- },
+ return user
})
```
-## Calling server functions from hooks and components
+### Not Found
-Server functions can throw `redirect`s or `notFound`s and while not required, it is recommended to catch these errors and handle them appropriately. To make this easier, the `@tanstack/react-start` package exports a `useServerFn` hook that can be used to bind server functions to components and hooks:
+Throw not-found errors for missing resources:
```tsx
-import { useServerFn } from '@tanstack/react-start'
-import { useQuery } from '@tanstack/react-query'
-import { getServerTime } from './getServerTime'
-
-export function Time() {
- const getTime = useServerFn(getServerTime)
-
- const timeQuery = useQuery({
- queryKey: 'time',
- queryFn: () => getTime(),
- })
-}
-```
-
-## Calling server functions anywhere else
-
-When using server functions, be aware that redirects and notFounds they throw will only be handled automatically when called from:
-
-- Route lifecycles
-- Components using the useServerFn hook
-
-For other usage locations, you'll need to handle these cases manually.
-
-## Redirects
-
-Server functions can throw a `redirect` error to redirect the user to a different URL. This is useful for handling authentication, authorization, or other scenarios where you need to redirect the user to a different page.
-
-- During SSR, redirects are handled by sending a 302 response to the client with the new location
-- On the client, redirects are handled by the router automatically from within a route lifecycle or a component that uses the `useServerFn` hook. If you call a server function from anywhere else, redirects will not be handled automatically.
-
-To throw a redirect, you can use the `redirect` function exported from the `@tanstack/react-router` package:
-
-```tsx
-import { redirect } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
-
-export const doStuff = createServerFn({ method: 'GET' }).handler(async () => {
- // Redirect the user to the home page
- throw redirect({
- to: '/',
- })
-})
-```
-
-Redirects can utilize all of the same options as `router.navigate`, `useNavigate()` and `` components. So feel free to also pass:
-
-- Path Params
-- Search Params
-- Hash
-
-Redirects can also set the status code of the response by passing a `status` option:
-
-```tsx
-import { redirect } from '@tanstack/react-router'
-import { createServerFn } from '@tanstack/react-start'
-
-export const doStuff = createServerFn({ method: 'GET' }).handler(async () => {
- // Redirect the user to the home page with a 301 status code
- throw redirect({
- to: '/',
- status: 301,
- })
-})
-```
-
-You can also redirect to an external target using `href`:
-
-```tsx
-import { redirect } from '@tanstack/react-router'
-import { createServerFn } from '@tanstack/react-start'
-
-export const auth = createServerFn({ method: 'GET' }).handler(async () => {
- // Redirect the user to the auth provider
- throw redirect({
- href: 'https://authprovider.com/login',
- })
-})
-```
-
-> ⚠️ Do not use `@tanstack/react-start/server`'s `sendRedirect` function to send soft redirects from within server functions. This will send the redirect using the `Location` header and will force a full page hard navigation on the client.
-
-## Redirect Headers
-
-You can also set custom headers on a redirect by passing a `headers` option:
-
-```tsx
-import { redirect } from '@tanstack/react-router'
-import { createServerFn } from '@tanstack/react-start'
-
-export const doStuff = createServerFn({ method: 'GET' }).handler(async () => {
- // Redirect the user to the home page with a custom header
- throw redirect({
- to: '/',
- headers: {
- 'X-Custom-Header': 'value',
- },
- })
-})
-```
-
-## Not Found
-
-While calling a server function from a `loader` or `beforeLoad` route lifecycle, a special `notFound` error can be thrown to indicate to the router that the requested resource was not found. This is more useful than a simple 404 status code, as it allows you to render a custom 404 page, or handle the error in a custom way. If notFound is thrown from a server function used outside of a route lifecycle, it will not be handled automatically.
-
-To throw a notFound, you can use the `notFound` function exported from the `@tanstack/react-router` package:
-
-```tsx
import { notFound } from '@tanstack/react-router'
-import { createServerFn } from '@tanstack/react-start'
-const getStuff = createServerFn({ method: 'GET' }).handler(async () => {
- // Randomly return a not found error
- if (Math.random() < 0.5) {
- throw notFound()
- }
+export const getPost = createServerFn()
+ .validator((data: { id: string }) => data)
+ .handler(async ({ data }) => {
+ const post = await db.findPost(data.id)
- // Or return some stuff
- return {
- stuff: 'stuff',
- }
-})
-
-export const Route = createFileRoute('/stuff')({
- loader: async () => {
- const stuff = await getStuff()
-
- return {
- stuff,
- }
- },
-})
-```
-
-Not found errors are a core feature of TanStack Router,
-
-## Handling Errors
-
-If a server function throws a (non-redirect/non-notFound) error, it will be serialized and sent to the client as a JSON response along with a 500 status code. This is useful for debugging, but you may want to handle these errors in a more user-friendly way. You can do this by catching the error and handling it in your route lifecycle, component, or hook as you normally would.
-
-```tsx
-import { createServerFn } from '@tanstack/react-start'
-
-export const doStuff = createServerFn({ method: 'GET' }).handler(async () => {
- undefined.foo()
-})
-
-export const Route = createFileRoute('/stuff')({
- loader: async () => {
- try {
- await doStuff()
- } catch (error) {
- // Handle the error:
- // error === {
- // message: "Cannot read property 'foo' of undefined",
- // stack: "TypeError: Cannot read property 'foo' of undefined\n at doStuff (file:///path/to/file.ts:3:3)"
- }
- },
-})
-```
-
-## No-JS Server Functions
-
-Without JavaScript enabled, there's only one way to execute server functions: by submitting a form.
-
-This is done by adding a `form` element to the page
-with [the HTML attribute `action`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/action).
-
-> Notice that we mentioned the **HTML** attribute `action`. This attribute only accepts a string in HTML, just like all
-> other attributes.
->
-> While React 19
-> [added support for passing a function to `action`](https://react.dev/reference/react-dom/components/form#form),
-> it's
-> a React-specific feature and not part of the HTML standard.
-
-The `action` attribute tells the browser where to send the form data when the form is submitted. In this case, we want
-to send the form data to the server function.
-
-To do this, we can utilize the `url` property of the server function:
-
-```ts
-const yourFn = createServerFn({ method: 'POST' })
- .validator((formData) => {
- if (!(formData instanceof FormData)) {
- throw new Error('Invalid form data')
+ if (!post) {
+ throw notFound()
}
- const name = formData.get('name')
-
- if (!name) {
- throw new Error('Name is required')
- }
-
- return name
+ return post
})
- .handler(async ({ data: name }) => {
- console.log(name) // 'John'
- })
-
-console.info(yourFn.url)
```
-And pass this to the `action` attribute of the form:
+## Advanced Topics
-```tsx
-function Component() {
- return (
-
- )
-}
-```
+For more advanced server function patterns and features, see these dedicated guides:
-When the form is submitted, the server function will be executed.
+### Server Context & Request Handling
-### No-JS Server Function Arguments
+Access request headers, cookies, and response customization:
-To pass arguments to a server function when submitting a form, you can use the `input` element with the `name` attribute
-to attach the argument to the [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) passed to your
-server function:
+- `getRequest()` - Access the full request object
+- `getRequestHeader()` - Read specific headers
+- `setResponseHeader()` - Set custom response headers
+- `setResponseStatus()` - Custom status codes
-```tsx
-const yourFn = createServerFn({ method: 'POST' })
- .validator((formData) => {
- if (!(formData instanceof FormData)) {
- throw new Error('Invalid form data')
- }
+### Streaming & Raw Responses
- const age = formData.get('age')
+Return `Response` objects for streaming, binary data, or custom content types.
- if (!age) {
- throw new Error('age is required')
- }
+### Progressive Enhancement
- return age.toString()
- })
- .handler(async ({ data: formData }) => {
- // `age` will be '123'
- const age = formData.get('age')
- // ...
- })
+Use server functions without JavaScript by leveraging the `.url` property with HTML forms.
-function Component() {
- return (
- // We need to tell the server that our data type is `multipart/form-data` by setting the `encType` attribute on the form.
-
- )
-}
-```
+### Middleware
-When the form is submitted, the server function will be executed with the form's data as an argument.
+Compose server functions with middleware for authentication, logging, and shared logic. See the [Middleware guide](../middleware.md).
-### No-JS Server Function Return Value
+### Static Server Functions
-Regardless of whether JavaScript is enabled, the server function will return a response to the HTTP request made from
-the client.
+Cache server function results at build time for static generation. See [Static Server Functions](../static-server-functions).
-When JavaScript is enabled, this response can be accessed as the return value of the server function in the client's
-JavaScript code.
+### Request Cancellation
-```ts
-const yourFn = createServerFn().handler(async () => {
- return 'Hello, world!'
-})
+Handle request cancellation with `AbortSignal` for long-running operations.
-// `.then` is not available when JavaScript is disabled
-yourFn().then(console.log)
-```
+---
-However, when JavaScript is disabled, there is no way to access the return value of the server function in the client's
-JavaScript code.
-
-Instead, the server function can provide a response to the client, telling the browser to navigate in a certain way.
-
-When combined with a `loader` from TanStack Router, we're able to provide an experience similar to a single-page application, even when
-JavaScript is disabled;
-all by telling the browser to reload the current page with new data piped through the `loader`:
-
-```tsx
-import * as fs from 'fs'
-import { createFileRoute } from '@tanstack/react-router'
-import { createServerFn } from '@tanstack/react-start'
-
-const filePath = 'count.txt'
-
-async function readCount() {
- return parseInt(
- await fs.promises.readFile(filePath, 'utf-8').catch(() => '0'),
- )
-}
-
-const getCount = createServerFn({
- method: 'GET',
-}).handler(() => {
- return readCount()
-})
-
-const updateCount = createServerFn({ method: 'POST' })
- .validator((formData) => {
- if (!(formData instanceof FormData)) {
- throw new Error('Invalid form data')
- }
-
- const addBy = formData.get('addBy')
-
- if (!addBy) {
- throw new Error('addBy is required')
- }
-
- return parseInt(addBy.toString())
- })
- .handler(async ({ data: addByAmount }) => {
- const count = await readCount()
- await fs.promises.writeFile(filePath, `${count + addByAmount}`)
- // Reload the page to trigger the loader again
- return new Response('ok', { status: 301, headers: { Location: '/' } })
- })
-
-export const Route = createFileRoute('/')({
- component: Home,
- loader: async () => await getCount(),
-})
-
-function Home() {
- const state = Route.useLoaderData()
-
- return (
-
-
-
{state}
-
- )
-}
-```
-
-## Static Server Functions
-
-When using prerendering/static-generation, server functions can also be "static", which enables their results to be cached at build time and served as static assets.
-
-Learn all about this pattern on the [Static Server Functions](../static-server-functions) page.
-
-## How are server functions compiled?
-
-Under the hood, server functions are extracted out of the client bundle and into a separate server bundle. On the server, they are executed as-is, and the result is sent back to the client. On the client, server functions proxy the request to the server, which executes the function and sends the result back to the client, all via `fetch`.
-
-The process looks like this:
-
-- When `createServerFn` is found in a file, the inner function is checked for a `use server` directive
-- If the `use server` directive is missing, it is added to the top of the function
-- On the client, the inner function is extracted out of the client bundle and into a separate server bundle
-- The client-side server function is replaced with a proxy function that sends a request to the server to execute the function that was extracted
-- On the server, the server function is not extracted, and is executed as-is
-- After extraction occurs, each bundle applies a dead-code elimination process to remove any unused code from each bundle.
+> **Note**: Server functions use a compilation process that extracts server code from client bundles while maintaining seamless calling patterns. On the client, calls become `fetch` requests to the server.
diff --git a/docs/start/framework/react/server-routes.md b/docs/start/framework/react/server-routes.md
index 0f2a92199a..081965f97d 100644
--- a/docs/start/framework/react/server-routes.md
+++ b/docs/start/framework/react/server-routes.md
@@ -11,10 +11,15 @@ Here's what a simple server route looks like:
```ts
// routes/hello.ts
+import { createFileRoute } from '@tanstack/react-router'
-export const ServerRoute = createServerFileRoute().methods({
- GET: async ({ request }) => {
- return new Response('Hello, World!')
+export const Route = createFileRoute('/hello')({
+ server: {
+ handlers: {
+ GET: async ({ request }) => {
+ return new Response('Hello, World!')
+ },
+ },
},
})
```
@@ -25,15 +30,17 @@ Because server routes can be defined in the same directory as your app routes, y
```tsx
// routes/hello.tsx
-
-export const ServerRoute = createServerFileRoute().methods({
- POST: async ({ request }) => {
- const body = await request.json()
- return new Response(JSON.stringify({ message: `Hello, ${body.name}!` }))
- },
-})
+import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/hello')({
+ server: {
+ handlers: {
+ POST: async ({ request }) => {
+ const body = await request.json()
+ return new Response(JSON.stringify({ message: `Hello, ${body.name}!` }))
+ },
+ },
+ },
component: HelloComponent,
})
@@ -64,7 +71,7 @@ function HelloComponent() {
## File Route Conventions
-Server routes in TanStack Start, follow the same file-based routing conventions as TanStack Router. This means that each file in your `routes` directory with a `ServerRoute` export will be treated as an API route. Here are a few examples:
+Server routes in TanStack Start follow the same file-based routing conventions as TanStack Router. This means that each file in your `routes` directory with a `server` property in the `createFileRoute` call will be treated as an API route. Here are a few examples:
- `/routes/users.ts` will create an API route at `/users`
- `/routes/users.index.ts` will **also** create an API route at `/users` (but will error if duplicate methods are defined)
@@ -99,85 +106,133 @@ In the examples above, you may have noticed that the file naming conventions are
## Handling Server Route Requests
-Server route requests are handled by Start's `createStartHandler` in your `server.ts` entry file.
-
-```tsx
-// server.ts
-import {
- createStartHandler,
- defaultStreamHandler,
-} from '@tanstack/react-start/server'
-import { createRouter } from './router'
-
-export default createStartHandler({
- createRouter,
-})(defaultStreamHandler)
-```
+Server route requests are handled by Start automatically by default or by Start's `createStartHandler` in your custom `src/server.ts` entry point file.
The start handler is responsible for matching an incoming request to a server route and executing the appropriate middleware and handler.
-Remember, if you need to customize the server handler, you can do so by creating a custom handler and then passing the event to the start handler:
-
-```tsx
-// server.ts
-import { createStartHandler } from '@tanstack/react-start/server'
-
-export default defineHandler((event) => {
- const startHandler = createStartHandler({
- createRouter,
- })(defaultStreamHandler)
-
- return startHandler(event)
-})
-```
+If you need to customize the server handler, you can do so by creating a custom handler and then passing the event to the start handler. See [The Server Entry Point](../learn-the-basics#the-server-entry-point-optional).
## Defining a Server Route
-Server routes are created by exporting a `ServerRoute` from a route file. The `ServerRoute` export should be created by calling the `createServerFileRoute` function. The resulting builder object can then be used to:
+Server routes are created by adding a `server` property to your `createFileRoute` call. The `server` property contains:
-- Add route-level middleware
-- Define handlers for each HTTP method
+- `handlers` - Either an object mapping HTTP methods to handler functions, or a function that receives `createHandlers` for more advanced use cases
+- `middleware` - Optional route-level middleware array that applies to all handlers
```ts
// routes/hello.ts
-export const ServerRoute = createServerFileRoute().methods({
- GET: async ({ request }) => {
- return new Response('Hello, World! from ' + request.url)
+import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/hello')({
+ server: {
+ handlers: {
+ GET: async ({ request }) => {
+ return new Response('Hello, World! from ' + request.url)
+ },
+ },
},
})
```
-## Defining a Server Route Handler
+## Defining Server Route Handlers
-There are two ways to define a handler for a server route.
+You can define handlers in two ways:
-- Provide a handler function directly to the method
-- By calling the `handler` method on the method builder object for more advanced use cases
+- **Simple handlers**: Provide handler functions directly in a handlers object
+- **Handlers with middleware**: Use the `createHandlers` function to define handlers with middleware
-### Providing a handler function directly to the method
+### Simple handlers
-For simple use cases, you can provide a handler function directly to the method.
+For simple use cases, you can provide handler functions directly in a handlers object.
```ts
// routes/hello.ts
-export const ServerRoute = createServerFileRoute().methods({
- GET: async ({ request }) => {
- return new Response('Hello, World! from ' + request.url)
+import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/hello')({
+ server: {
+ handlers: {
+ GET: async ({ request }) => {
+ return new Response('Hello, World! from ' + request.url)
+ },
+ },
},
})
```
-### Providing a handler function via the method builder object
+### Adding middleware to specific handlers
-For more complex use cases, you can provide a handler function via the method builder object. This allows you to add middleware to the method.
+For more complex use cases, you can add middleware to specific handlers. This requires using the `createHandlers` function:
```tsx
// routes/hello.ts
-export const ServerRoute = createServerFileRoute().methods((api) => ({
- GET: api.middleware([loggerMiddleware]).handler(async ({ request }) => {
- return new Response('Hello, World! from ' + request.url)
- }),
-}))
+import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/hello')({
+ server: {
+ handlers: ({ createHandlers }) =>
+ createHandlers({
+ GET: {
+ middleware: [loggerMiddleware],
+ handler: async ({ request }) => {
+ return new Response('Hello, World! from ' + request.url)
+ },
+ },
+ }),
+ },
+})
+```
+
+### Adding middleware to all handlers
+
+You can also add middleware that applies to all handlers in a route by using the `middleware` property at the server level:
+
+```tsx
+// routes/hello.ts
+import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/hello')({
+ server: {
+ middleware: [authMiddleware, loggerMiddleware], // Applies to all handlers
+ handlers: {
+ GET: async ({ request }) => {
+ return new Response('Hello, World! from ' + request.url)
+ },
+ POST: async ({ request }) => {
+ const body = await request.json()
+ return new Response(`Hello, ${body.name}!`)
+ },
+ },
+ },
+})
+```
+
+### Combining route-level and handler-specific middleware
+
+You can combine both approaches - route-level middleware will run first, followed by handler-specific middleware:
+
+```tsx
+// routes/hello.ts
+import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/hello')({
+ server: {
+ middleware: [authMiddleware], // Runs first for all handlers
+ handlers: ({ createHandlers }) =>
+ createHandlers({
+ GET: async ({ request }) => {
+ return new Response('Hello, World!')
+ },
+ POST: {
+ middleware: [validationMiddleware], // Runs after authMiddleware, only for POST
+ handler: async ({ request }) => {
+ const body = await request.json()
+ return new Response(`Hello, ${body.name}!`)
+ },
+ },
+ }),
+ },
+})
```
## Handler Context
@@ -196,10 +251,16 @@ Server routes support dynamic path parameters in the same way as TanStack Router
```ts
// routes/users/$id.ts
-export const ServerRoute = createServerFileRoute().methods({
- GET: async ({ params }) => {
- const { id } = params
- return new Response(`User ID: ${id}`)
+import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/users/$id')({
+ server: {
+ handlers: {
+ GET: async ({ params }) => {
+ const { id } = params
+ return new Response(`User ID: ${id}`)
+ },
+ },
},
})
@@ -211,10 +272,16 @@ You can also have multiple dynamic path parameters in a single route. For exampl
```ts
// routes/users/$id/posts/$postId.ts
-export const ServerRoute = createServerFileRoute().methods({
- GET: async ({ params }) => {
- const { id, postId } = params
- return new Response(`User ID: ${id}, Post ID: ${postId}`)
+import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/users/$id/posts/$postId')({
+ server: {
+ handlers: {
+ GET: async ({ params }) => {
+ const { id, postId } = params
+ return new Response(`User ID: ${id}, Post ID: ${postId}`)
+ },
+ },
},
})
@@ -228,10 +295,16 @@ Server routes also support wildcard parameters at the end of the path, which are
```ts
// routes/file/$.ts
-export const ServerRoute = createServerFileRoute().methods({
- GET: async ({ params }) => {
- const { _splat } = params
- return new Response(`File: ${_splat}`)
+import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/file/$')({
+ server: {
+ handlers: {
+ GET: async ({ params }) => {
+ const { _splat } = params
+ return new Response(`File: ${_splat}`)
+ },
+ },
},
})
@@ -245,10 +318,16 @@ To handle POST requests,you can add a `POST` handler to the route object. The ha
```ts
// routes/hello.ts
-export const ServerRoute = createServerFileRoute().methods({
- POST: async ({ request }) => {
- const body = await request.json()
- return new Response(`Hello, ${body.name}!`)
+import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/hello')({
+ server: {
+ handlers: {
+ POST: async ({ request }) => {
+ const body = await request.json()
+ return new Response(`Hello, ${body.name}!`)
+ },
+ },
},
})
@@ -268,13 +347,19 @@ When returning JSON using a Response object, this is a common pattern:
```ts
// routes/hello.ts
-export const ServerRoute = createServerFileRoute().methods({
- GET: async ({ request }) => {
- return new Response(JSON.stringify({ message: 'Hello, World!' }), {
- headers: {
- 'Content-Type': 'application/json',
+import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/hello')({
+ server: {
+ handlers: {
+ GET: async ({ request }) => {
+ return new Response(JSON.stringify({ message: 'Hello, World!' }), {
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ })
},
- })
+ },
},
})
@@ -288,11 +373,16 @@ Or you can use the `json` helper function to automatically set the `Content-Type
```ts
// routes/hello.ts
+import { createFileRoute } from '@tanstack/react-router'
import { json } from '@tanstack/react-start'
-export const ServerRoute = createServerFileRoute().methods({
- GET: async ({ request }) => {
- return json({ message: 'Hello, World!' })
+export const Route = createFileRoute('/hello')({
+ server: {
+ handlers: {
+ GET: async ({ request }) => {
+ return json({ message: 'Hello, World!' })
+ },
+ },
},
})
@@ -308,17 +398,22 @@ You can set the status code of the response by either:
```ts
// routes/hello.ts
+ import { createFileRoute } from '@tanstack/react-router'
import { json } from '@tanstack/react-start'
- export const ServerRoute = createServerFileRoute().methods({
- GET: async ({ request, params }) => {
- const user = await findUser(params.id)
- if (!user) {
- return new Response('User not found', {
- status: 404,
- })
- }
- return json(user)
+ export const Route = createFileRoute('/hello')({
+ server: {
+ handlers: {
+ GET: async ({ request, params }) => {
+ const user = await findUser(params.id)
+ if (!user) {
+ return new Response('User not found', {
+ status: 404,
+ })
+ }
+ return json(user)
+ },
+ },
},
})
```
@@ -327,17 +422,22 @@ You can set the status code of the response by either:
```ts
// routes/hello.ts
+ import { createFileRoute } from '@tanstack/react-router'
import { json } from '@tanstack/react-start'
import { setResponseStatus } from '@tanstack/react-start/server'
- export const ServerRoute = createServerFileRoute().methods({
- GET: async ({ request, params }) => {
- const user = await findUser(params.id)
- if (!user) {
- setResponseStatus(404)
- return new Response('User not found')
- }
- return json(user)
+ export const Route = createFileRoute('/hello')({
+ server: {
+ handlers: {
+ GET: async ({ request, params }) => {
+ const user = await findUser(params.id)
+ if (!user) {
+ setResponseStatus(404)
+ return new Response('User not found')
+ }
+ return json(user)
+ },
+ },
},
})
```
@@ -352,13 +452,19 @@ Sometimes you may need to set headers in the response. You can do this by either
```ts
// routes/hello.ts
- export const ServerRoute = createServerFileRoute().methods({
- GET: async ({ request }) => {
- return new Response('Hello, World!', {
- headers: {
- 'Content-Type': 'text/plain',
+ import { createFileRoute } from '@tanstack/react-router'
+
+ export const Route = createFileRoute('/hello')({
+ server: {
+ handlers: {
+ GET: async ({ request }) => {
+ return new Response('Hello, World!', {
+ headers: {
+ 'Content-Type': 'text/plain',
+ },
+ })
},
- })
+ },
},
})
@@ -366,18 +472,23 @@ Sometimes you may need to set headers in the response. You can do this by either
// Hello, World!
```
-- Or using the `setHeaders` helper function from `@tanstack/react-start/server`.
+- Or using the `setResponseHeaders` helper function from `@tanstack/react-start/server`.
```ts
// routes/hello.ts
- import { setHeaders } from '@tanstack/react-start/server'
+ import { createFileRoute } from '@tanstack/react-router'
+ import { setResponseHeaders } from '@tanstack/react-start/server'
- export const ServerRoute = createServerFileRoute().methods({
- GET: async ({ request }) => {
- setHeaders({
- 'Content-Type': 'text/plain',
- })
- return new Response('Hello, World!')
+ export const Route = createFileRoute('/hello')({
+ server: {
+ handlers: {
+ GET: async ({ request }) => {
+ setResponseHeaders({
+ 'Content-Type': 'text/plain',
+ })
+ return new Response('Hello, World!')
+ },
+ },
},
})
```
diff --git a/docs/start/framework/react/static-prerendering.md b/docs/start/framework/react/static-prerendering.md
index 995c5c4728..3f1c0048fd 100644
--- a/docs/start/framework/react/static-prerendering.md
+++ b/docs/start/framework/react/static-prerendering.md
@@ -13,6 +13,7 @@ TanStack Start can prerender your application to static HTML files, which can th
// vite.config.ts
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
+import viteReact from '@vitejs/plugin-react'
export default defineConfig({
plugins: [
@@ -53,6 +54,7 @@ export default defineConfig({
},
],
}),
+ viteReact(),
],
})
```
diff --git a/docs/start/framework/react/static-server-functions.md b/docs/start/framework/react/static-server-functions.md
index 92c7adc932..8f86238bdd 100644
--- a/docs/start/framework/react/static-server-functions.md
+++ b/docs/start/framework/react/static-server-functions.md
@@ -3,50 +3,33 @@ id: static-server-functions
title: Static Server Functions
---
+> [!WARNING]
+> Static Server Functions are experimental!
+
## What are Static Server Functions?
-Static server functions are server functions that are executed at build time and cached as static assets when using prerendering/static-generation. They can be set to "static" mode by passing the `type: 'static'` option to `createServerFn`:
+Static server functions are server functions that are executed at build time and cached as static assets when using prerendering/static-generation. They can be set to "static" mode by applying the `staticFunctionMiddleware` middleware to `createServerFn`:
```tsx
-const myServerFn = createServerFn({ type: 'static' }).handler(async () => {
- return 'Hello, world!'
-})
+import { createServerFn } from '@tanstack/react-start'
+import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions'
+
+const myServerFn = createServerFn({ method: 'GET' })
+ .middleware([staticFunctionMiddleware])
+ .handler(async () => {
+ return 'Hello, world!'
+ })
```
+Ensure that `staticFunctionMiddleware` is the final middleware!
+
This pattern goes as follows:
- Build-time
- - During build-time prerendering, a server function with `type: 'static'` is executed
+ - During build-time prerendering, a server function with `staticFunctionMiddleware` is executed
- The result is cached with your build output as a static JSON file under a derived key (function ID + params/payload hash)
- The result is returned as normal during prerendering/static-generation and used to prerender the page
- Runtime
- Initially, the prerendered page's html is served and the server function data is embedded in the html
- When the client mounts, the embedded server function data is hydrated
- For future client-side invocations, the server function is replaced with a fetch call to the static JSON file
-
-## Customizing the Server Functions Static Cache
-
-By default, the static server function cache implementation stores and retrieves static data in the build output directory via node's `fs` module and likewise fetches the data at runtime using a `fetch` call to the same static file.
-
-This interface can be customized by importing and calling the `createServerFnStaticCache` function to create a custom cache implementation and then calling `setServerFnStaticCache` to set it:
-
-```tsx
-import {
- createServerFnStaticCache,
- setServerFnStaticCache,
-} from '@tanstack/react-start/client'
-
-const myCustomStaticCache = createServerFnStaticCache({
- setItem: async (ctx, data) => {
- // Store the static data in your custom cache
- },
- getItem: async (ctx) => {
- // Retrieve the static data from your custom cache
- },
- fetchItem: async (ctx) => {
- // During runtime, fetch the static data from your custom cache
- },
-})
-
-setServerFnStaticCache(myCustomStaticCache)
-```
diff --git a/docs/start/framework/react/tailwind-integration.md b/docs/start/framework/react/tailwind-integration.md
index 90d674ca78..b57a95fb38 100644
--- a/docs/start/framework/react/tailwind-integration.md
+++ b/docs/start/framework/react/tailwind-integration.md
@@ -29,12 +29,13 @@ import { defineConfig } from 'vite'
import tsConfigPaths from 'vite-tsconfig-paths'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import tailwindcss from '@tailwindcss/vite'
+import viteReact from '@vitejs/plugin-react'
export default defineConfig({
server: {
port: 3000,
},
- plugins: [tsConfigPaths(), tanstackStart(), tailwindcss()],
+ plugins: [tsConfigPaths(), tanstackStart(), viteReact(), tailwindcss()],
})
```
diff --git a/docs/start/framework/solid/authentication-overview.md b/docs/start/framework/solid/authentication-overview.md
new file mode 100644
index 0000000000..623d28df7e
--- /dev/null
+++ b/docs/start/framework/solid/authentication-overview.md
@@ -0,0 +1,9 @@
+---
+ref: docs/start/framework/react/authentication-overview.md
+replace:
+ {
+ '@tanstack/react-start': '@tanstack/solid-start',
+ 'React': 'SolidJS',
+ 'react-router': 'solid-router',
+ }
+---
diff --git a/docs/start/framework/solid/authentication.md b/docs/start/framework/solid/authentication.md
index eee03da9da..7a6f8f01d6 100644
--- a/docs/start/framework/solid/authentication.md
+++ b/docs/start/framework/solid/authentication.md
@@ -1,33 +1,9 @@
---
-id: authentication
-title: Authentication
+ref: docs/start/framework/react/authentication.md
+replace:
+ {
+ '@tanstack/react-start': '@tanstack/solid-start',
+ 'React': 'SolidJS',
+ 'react-router': 'solid-router',
+ }
---
-
-
-
-Authentication is the process of verifying the identity of a user. This is a critical part of any application that requires users to log in or access protected resources. TanStack Start provides the necessary full-stack APIs to implement authentication in your application.
-
-## What should I use?
-
-TanStack Start is **designed to work with any authentication provider**, so if you already have an authentication provider or strategy in mind, you can use either find an existing example or implement your own authentication logic using the full-stack APIs provided by TanStack Start.
-
-That said, authentication is not something to be taken lightly. After much vetting, usage and reviewing on our end, we highly recommend using [Clerk](https://clerk.dev) for the best possible authentication experience. Clerk provides a full suite of authentication APIs and UI components that make it easy to implement authentication in your application and provide a seamless user experience.
-
-## What is Clerk?
-
-
-
-
-
-
-
-
-
-Clerk is a modern authentication platform that provides a full suite of authentication APIs and UI components to help you implement authentication in your application. Clerk is designed to be easy to use and provides a seamless user experience. With Clerk, you can implement authentication in your application in minutes and provide your users with a secure and reliable authentication experience.
-
-- To learn more about Clerk, visit the [Clerk website](https://go.clerk.com/wOwHtuJ)
-- To sign up, visit the [Clerk dashboard](https://go.clerk.com/PrSDXti)
-
-## Documentation & APIs
-
-Documentation for implementing your own authentication logic with TanStack Start is coming soon!
diff --git a/docs/start/framework/solid/build-from-scratch.md b/docs/start/framework/solid/build-from-scratch.md
index b83876b70a..b414ff7fe6 100644
--- a/docs/start/framework/solid/build-from-scratch.md
+++ b/docs/start/framework/solid/build-from-scratch.md
@@ -1,259 +1,9 @@
---
-id: build-from-scratch
-title: Build a Project from Scratch
+ref: docs/start/framework/react/build-from-scratch.md
+replace:
+ {
+ '@tanstack/react-start': '@tanstack/solid-start',
+ 'React': 'SolidJS',
+ 'react-router': 'solid-router',
+ }
---
-
-> [!NOTE]
-> If you chose to quick start with an example or cloned project, you can skip this guide and move on to the [Learn the Basics](../learn-the-basics.md) guide.
-
-_So you want to build a TanStack Start project from scratch?_
-
-This guide will help you build a **very** basic TanStack Start web application. Together, we will use TanStack Start to:
-
-- Serve an index page...
-- Which displays a counter...
-- With a button to increment the counter persistently.
-
-[Here is what that will look like](https://stackblitz.com/github/tanstack/router/tree/main/examples/solid/start-bare)
-
-Let's create a new project directory and initialize it.
-
-```shell
-mkdir myApp
-cd myApp
-npm init -y
-```
-
-> [!NOTE] > We use `npm` in all of these examples, but you can use your package manager of choice instead.
-
-## TypeScript Configuration
-
-We highly recommend using TypeScript with TanStack Start. Create a `tsconfig.json` file with at least the following settings:
-
-```json
-{
- "compilerOptions": {
- "jsx": "preserve",
- "jsxImportSource": "solid-js",
- "moduleResolution": "Bundler",
- "module": "ESNext",
- "target": "ES2022",
- "skipLibCheck": true,
- "strictNullChecks": true
- }
-}
-```
-
-> [!NOTE] > Enabling `verbatimModuleSyntax` can result in server bundles leaking into client bundles. It is recommended to keep this option disabled.
-
-## Install Dependencies
-
-TanStack Start is powered by [Vite](https://vite.dev/) and [TanStack Router](https://tanstack.com/router) and requires them as dependencies.
-
-To install them, run:
-
-```shell
-npm i @tanstack/solid-start @tanstack/solid-router vite
-```
-
-You'll also need Solid:
-
-```shell
-npm i solid-js
-```
-
-and some TypeScript:
-
-```shell
-npm i -D typescript vite-tsconfig-paths
-```
-
-## Update Configuration Files
-
-We'll then update our `package.json` to use Vite's CLI and set `"type": "module"`:
-
-```json
-{
- // ...
- "type": "module",
- "scripts": {
- "dev": "vite dev",
- "build": "vite build"
- }
-}
-```
-
-Then configure TanStack Start's Vite plugin in `vite.config.ts`:
-
-> [!NOTE]
-> TanStack Start will stop auto-configuring React/Solid Vite plugins. You’ll get full control - choose `vite-plugin-solid`. Set `customViteSolidPlugin: true` to opt in to this feature right now!
-
-```ts
-// vite.config.ts
-import { defineConfig } from 'vite'
-import tsConfigPaths from 'vite-tsconfig-paths'
-import { tanstackStart } from '@tanstack/solid-start/plugin/vite'
-import viteSolid from 'vite-plugin-solid'
-
-export default defineConfig({
- server: {
- port: 3000,
- },
- plugins: [
- tsConfigPaths(),
- tanstackStart({ customViteSolidPlugin: true }),
- viteSolid({ ssr: true }),
- ],
-})
-```
-
-## Add the Basic Templating
-
-There are 2 required files for TanStack Start usage:
-
-1. The router configuration
-2. The root of your application
-
-Once configuration is done, we'll have a file tree that looks like the following:
-
-```
-.
-├── src/
-│ ├── routes/
-│ │ └── `__root.tsx`
-│ ├── `router.tsx`
-│ ├── `routeTree.gen.ts`
-├── `.gitignore`
-├── `vite.config.ts`
-├── `package.json`
-└── `tsconfig.json`
-```
-
-## The Router Configuration
-
-This is the file that will dictate the behavior of TanStack Router used within Start. Here, you can configure everything
-from the default [preloading functionality](/router/latest/docs/framework/solid/guide/preloading) to [caching staleness](/router/latest/docs/framework/solid/guide/data-loading).
-
-> [!NOTE]
-> You won't have a `routeTree.gen.ts` file yet. This file will be generated when you run TanStack Start for the first time.
-
-```tsx
-// src/router.tsx
-import { createRouter as createTanStackRouter } from '@tanstack/solid-router'
-import { routeTree } from './routeTree.gen'
-
-export function createRouter() {
- const router = createTanStackRouter({
- routeTree,
- scrollRestoration: true,
- })
-
- return router
-}
-
-declare module '@tanstack/solid-router' {
- interface Register {
- router: ReturnType
- }
-}
-```
-
-> [!NOTE]
-> TanStack Start provides **default server and client entry points** to handle requests and client-entry + hydration. You can customize these entry points by adding a `server.ts` and/or `client.tsx` file in the root of your project, but for now, we'll use the defaults.
-
-## The Root of Your Application
-
-Finally, we need to create the root of our application. This is the entry point for all other routes. The code in this file will wrap all other routes in the application.
-
-```tsx
-// src/routes/__root.tsx
-import {
- Outlet,
- createRootRoute,
- HeadContent,
- Scripts,
-} from '@tanstack/solid-router'
-
-export const Route = createRootRoute({
- head: () => ({
- meta: [
- {
- charset: 'utf-8',
- },
- {
- name: 'viewport',
- content: 'width=device-width, initial-scale=1',
- },
- {
- title: 'TanStack Start Starter',
- },
- ],
- }),
- component: RootComponent,
-})
-
-function RootComponent() {
- return
-}
-```
-
-## Writing Your First Route
-
-Now that we have the basic templating setup, we can write our first route. This is done by creating a new file in the `app/routes` directory.
-
-```tsx
-// src/routes/index.tsx
-import * as fs from 'node:fs'
-import { createFileRoute, useRouter } from '@tanstack/solid-router'
-import { createServerFn } from '@tanstack/solid-start'
-
-const filePath = 'count.txt'
-
-async function readCount() {
- return parseInt(
- await fs.promises.readFile(filePath, 'utf-8').catch(() => '0'),
- )
-}
-
-const getCount = createServerFn({
- method: 'GET',
-}).handler(() => {
- return readCount()
-})
-
-const updateCount = createServerFn({ method: 'POST' })
- .validator((d: number) => d)
- .handler(async ({ data }) => {
- const count = await readCount()
- await fs.promises.writeFile(filePath, `${count + data}`)
- })
-
-export const Route = createFileRoute('/')({
- component: Home,
- loader: async () => await getCount(),
-})
-
-function Home() {
- const router = useRouter()
- const state = Route.useLoaderData()
-
- return (
-
- )
-}
-```
-
-That's it! 🤯 You've now set up a TanStack Start project and written your first route. 🎉
-
-You can now run `npm run dev` to start your server and navigate to `http://localhost:3000` to see your route in action.
-
-You want to deploy your application? Check out the [hosting guide](../hosting.md).
diff --git a/docs/start/framework/solid/client-entry-point.md b/docs/start/framework/solid/client-entry-point.md
new file mode 100644
index 0000000000..41ff8a3abd
--- /dev/null
+++ b/docs/start/framework/solid/client-entry-point.md
@@ -0,0 +1,5 @@
+---
+ref: docs/start/framework/react/client-entry-point.md
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
+---
diff --git a/docs/start/framework/solid/code-execution-patterns.md b/docs/start/framework/solid/code-execution-patterns.md
new file mode 100644
index 0000000000..2db5979f75
--- /dev/null
+++ b/docs/start/framework/solid/code-execution-patterns.md
@@ -0,0 +1,5 @@
+---
+ref: docs/start/framework/react/code-execution-patterns.md
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
+---
diff --git a/docs/start/framework/solid/databases.md b/docs/start/framework/solid/databases.md
index 1aeb1fa2b3..3af89fe312 100644
--- a/docs/start/framework/solid/databases.md
+++ b/docs/start/framework/solid/databases.md
@@ -1,3 +1,5 @@
---
ref: docs/start/framework/react/databases.md
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
---
diff --git a/docs/start/framework/solid/environment-variables.md b/docs/start/framework/solid/environment-variables.md
new file mode 100644
index 0000000000..743c7b56d6
--- /dev/null
+++ b/docs/start/framework/solid/environment-variables.md
@@ -0,0 +1,5 @@
+---
+ref: docs/start/framework/react/environment-variables.md
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
+---
diff --git a/docs/start/framework/solid/execution-model.md b/docs/start/framework/solid/execution-model.md
new file mode 100644
index 0000000000..c9e717a7e4
--- /dev/null
+++ b/docs/start/framework/solid/execution-model.md
@@ -0,0 +1,5 @@
+---
+ref: docs/start/framework/react/execution-model.md
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
+---
diff --git a/docs/start/framework/solid/getting-started.md b/docs/start/framework/solid/getting-started.md
index eb735aeef0..ecfec25770 100644
--- a/docs/start/framework/solid/getting-started.md
+++ b/docs/start/framework/solid/getting-started.md
@@ -1,3 +1,9 @@
---
ref: docs/start/framework/react/getting-started.md
+replace:
+ {
+ '@tanstack/react-start': '@tanstack/solid-start',
+ 'React': 'SolidJS',
+ 'react-router': 'solid-router',
+ }
---
diff --git a/docs/start/framework/solid/hosting.md b/docs/start/framework/solid/hosting.md
index f6d15dd188..ce646d636e 100644
--- a/docs/start/framework/solid/hosting.md
+++ b/docs/start/framework/solid/hosting.md
@@ -1,163 +1,5 @@
---
-id: hosting
-title: Hosting
+ref: docs/start/framework/react/hosting.md
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
---
-
-Hosting is the process of deploying your application to the internet so that users can access it. This is a critical part of any web development project, ensuring your application is available to the world. TanStack Start is built on [Nitro](https://nitro.unjs.io/), a powerful server toolkit for deploying web applications anywhere. Nitro allows TanStack Start to provide a unified API for SSR, streaming, and hydration on any hosting provider.
-
-## What should I use?
-
-TanStack Start is **designed to work with any hosting provider**, so if you already have a hosting provider in mind, you can deploy your application there using the full-stack APIs provided by TanStack Start.
-
-However, since hosting is one of the most crucial aspects of your application's performance, reliability, and scalability, we highly recommend using our Official Hosting Partner [Netlify](https://www.netlify.com?utm_source=tanstack).
-
-## What is Netlify?
-
-
-
-
-
-
-
-
-
-Netlify is a leading hosting platform that provides a fast, secure, and reliable environment for deploying your web applications. With Netlify, you can deploy your TanStack Start application in just a few clicks and benefit from features like a global edge network, automatic scaling, and seamless integrations with GitHub and GitLab. Netlify is designed to make your development process as smooth as possible, from local development to production deployment.
-
-- To learn more about Netlify, visit the [Netlify website](https://www.netlify.com?utm_source=tanstack)
-- To sign up, visit the [Netlify dashboard](https://www.netlify.com/signup?utm_source=tanstack)
-
-## Deployment
-
-> [!WARNING]
-> The page is still a work in progress. We'll keep updating this page with guides on deployment to different hosting providers soon!
-
-When a TanStack Start application is being deployed, the `target` value in the `vite.config.ts` file determines the deployment target. The deployment target can be set to one of the following values:
-
-- [`netlify`](#netlify): Deploy to Netlify
-- [`vercel`](#vercel): Deploy to Vercel
-- [`cloudflare-pages`](#cloudflare-pages): Deploy to Cloudflare Pages
-- [`node-server`](#nodejs): Deploy to a Node.js server
-- [`bun`](#bun): Deploy to a Bun server
-- ... and more to come!
-
-Once you've chosen a deployment target, you can follow the deployment guidelines below to deploy your TanStack Start application to the hosting provider of your choice.
-
-### Netlify
-
-Set the `target` value to `netlify` in your `vite.config.ts` file.
-
-```ts
-// vite.config.ts
-import { tanstackStart } from '@tanstack/solid-start/plugin/vite'
-import { defineConfig } from 'vite'
-
-export default defineConfig({
- plugins: [tanstackStart({ target: 'netlify' })],
-})
-```
-
-Deploy your application to Netlify using their one-click deployment process, and you're ready to go!
-
-### Vercel
-
-Deploying your TanStack Start application to Vercel is easy and straightforward. Just set the `target` value to `vercel` in your `vite.config.ts` file, and you're ready to deploy your application to Vercel.
-
-```ts
-// vite.config.ts
-import { tanstackStart } from '@tanstack/solid-start/plugin/vite'
-import { defineConfig } from 'vite'
-
-export default defineConfig({
- plugins: [tanstackStart({ target: 'vercel' })],
-})
-```
-
-Deploy you application to Vercel using their one-click deployment process, and you're ready to go!
-
-### Cloudflare Pages
-
-When deploying to Cloudflare Pages, you'll need to complete a few extra steps before your users can start using your app.
-
-1. Update `vite.config.ts`
-
-Set the `target` value to `cloudflare-pages` in your `vite.config.ts` file.
-
-```ts
-// vite.config.ts
-import { tanstackStart } from '@tanstack/solid-start/plugin/vite'
-import { defineConfig } from 'vite'
-
-export default defineConfig({
- plugins: [tanstackStart({ target: 'cloudflare-module' })],
-})
-```
-
-2. Add a `wrangler.toml` config file
-
-```toml
-# wrangler.toml
-name = "your-cloudflare-project-name"
-pages_build_output_dir = "./dist"
-compatibility_flags = ["nodejs_compat"]
-compatibility_date = "2024-11-13"
-```
-
-Deploy you application to Cloudflare Pages using their one-click deployment process, and you're ready to go!
-
-### Node.js
-
-Set the `target` value to `node-server` in your `vite.config.ts` file.
-
-```ts
-// vite.config.ts
-import { tanstackStart } from '@tanstack/solid-start/plugin/vite'
-import { defineConfig } from 'vite'
-
-export default defineConfig({
- plugins: [tanstackStart({ target: 'node-server' })],
-})
-```
-
-Then you can run the following command to build and start your application:
-
-```sh
-npm run build
-```
-
-You're now ready to deploy your application to a Node.js server. You can start your application by running:
-
-```sh
-node .output/server/index.mjs
-```
-
-### Bun
-
-Make sure that your `solid-js` in your `package.json` file. If not, run the following command to upgrade the packages:
-
-```sh
-npm install solid-js
-```
-
-Set the `target` value to `bun` in your `vite.config.ts` file.
-
-```ts
-// vite.config.ts
-import { tanstackStart } from '@tanstack/solid-start/plugin/vite'
-import { defineConfig } from 'vite'
-
-export default defineConfig({
- plugins: [tanstackStart({ target: 'bun' })],
-})
-```
-
-Then you can run the following command to build and start your application:
-
-```sh
-bun run build
-```
-
-You're now ready to deploy your application to a Bun server. You can start your application by running:
-
-```sh
-bun run .output/server/index.mjs
-```
diff --git a/docs/start/framework/solid/learn-the-basics.md b/docs/start/framework/solid/learn-the-basics.md
deleted file mode 100644
index a7a7d2c545..0000000000
--- a/docs/start/framework/solid/learn-the-basics.md
+++ /dev/null
@@ -1,289 +0,0 @@
----
-id: learn-the-basics
-title: Learn the Basics
----
-
-This guide will help you learn the basics behind how TanStack Start works, regardless of how you set up your project.
-
-## Dependencies
-
-TanStack Start is powered by [Vite](https://vite.dev/) and [TanStack Router](https://tanstack.com/router).
-
-- **TanStack Router**: A router for building web applications.
-- **Vite**: A build tool for bundling your application.
-
-## It all "Starts" with the Router
-
-This is the file that will dictate the behavior of TanStack Router used within Start. Here, you can configure everything
-from the default [preloading functionality](/router/latest/docs/framework/solid/guide/preloading) to [caching staleness](/router/latest/docs/framework/solid/guide/data-loading).
-
-```tsx
-// app/router.tsx
-import { createRouter as createTanStackRouter } from '@tanstack/solid-router'
-import { routeTree } from './routeTree.gen'
-
-export function createRouter() {
- const router = createTanStackRouter({
- routeTree,
- scrollRestoration: true,
- })
-
- return router
-}
-
-declare module '@tanstack/solid-router' {
- interface Register {
- router: ReturnType
- }
-}
-```
-
-- Notice the `scrollRestoration` property. This is used to restore the scroll position of the page when navigating between routes.
-
-## Route Generation
-
-The `routeTree.gen.ts` file is generated when you run TanStack Start (via `npm run dev` or `npm run start`) for the first time. This file contains the generated route tree and a handful of TS utilities that make TanStack Start fully type-safe.
-
-## The Server Entry Point (Optional)
-
-> [!NOTE]
-> The server entry point is **optional** out of the box. If not provided, TanStack Start will automatically handle the server entry point for you using the below as a default.
-
-This is done via the `src/server.ts` file:
-
-```tsx
-// src/server.ts
-import {
- createStartHandler,
- defaultStreamHandler,
-} from '@tanstack/solid-start/server'
-
-import { createRouter } from './router'
-
-export default createStartHandler({
- createRouter,
-})(defaultStreamHandler)
-```
-
-Whether we are statically generating our app or serving it dynamically, the `server.ts` file is the entry point for doing all SSR-related work.
-
-- It's important that a new router is created for each request. This ensures that any data handled by the router is unique to the request.
-- The `defaultStreamHandler` function is used to render our application to a stream, allowing us to take advantage of streaming HTML to the client. (This is the default handler, but you can also use other handlers like `defaultRenderHandler`, or even build your own)
-
-## The Client Entry Point (Optional)
-
-> [!NOTE]
-> The client entry point is **optional** out of the box. If not provided, TanStack Start will automatically handle the client entry point for you using the below as a default.
-
-Getting our html to the client is only half the battle. Once there, we need to hydrate our client-side JavaScript once the route resolves to the client. We do this by hydrating the root of our application with the `StartClient` component:
-
-```tsx
-// app/client.tsx
-import { hydrate } from 'solid-js/web'
-import { StartClient } from '@tanstack/solid-start'
-import { createRouter } from './router'
-
-const router = createRouter()
-
-hydrate(() => , document)
-```
-
-This enables us to kick off client-side routing once the user's initial server request has fulfilled.
-
-## The Root of Your Application
-
-Other than the client entry point (which is optional by default), the `__root` route of your application is the entry point for your application. The code in this file will wrap all other routes in the app, including your home page. It behaves like a pathless layout route for your whole application.
-
-Because it is **always rendered**, it is the perfect place to construct your application shell and take care of any global logic.
-
-```tsx
-// app/routes/__root.tsx
-import {
- Outlet,
- createRootRoute,
- HeadContent,
- Scripts,
-} from '@tanstack/solid-router'
-
-export const Route = createRootRoute({
- head: () => ({
- meta: [
- {
- charSet: 'utf-8',
- },
- {
- name: 'viewport',
- content: 'width=device-width, initial-scale=1',
- },
- {
- title: 'TanStack Start Starter',
- },
- ],
- }),
- component: RootComponent,
-})
-
-function RootComponent() {
- return
-}
-```
-
-- This layout may change in the future as we roll out SPA mode, which allows the root route to render the SPA shell without any page-specific content.
-- Notice the `Scripts` component. This is used to load all of the client-side JavaScript for the application.
-
-## Routes
-
-Routes are an extensive feature of TanStack Router, and are covered thoroughly in the [Routing Guide](/router/latest/docs/framework/solid/routing/file-based-routing). As a summary:
-
-- Routes are defined using the `createFileRoute` function.
-- Routes are automatically code-split and lazy-loaded.
-- Critical data fetching is coordinated from a Route's loader
-- Much more!
-
-```tsx
-// app/routes/index.tsx
-import * as fs from 'node:fs'
-import { createFileRoute, useRouter } from '@tanstack/solid-router'
-import { createServerFn } from '@tanstack/solid-start'
-
-const filePath = 'count.txt'
-
-async function readCount() {
- return parseInt(
- await fs.promises.readFile(filePath, 'utf-8').catch(() => '0'),
- )
-}
-
-const getCount = createServerFn({
- method: 'GET',
-}).handler(() => {
- return readCount()
-})
-
-const updateCount = createServerFn({ method: 'POST' })
- .validator((d: number) => d)
- .handler(async ({ data }) => {
- const count = await readCount()
- await fs.promises.writeFile(filePath, `${count + data}`)
- })
-
-export const Route = createFileRoute('/')({
- component: Home,
- loader: async () => await getCount(),
-})
-
-function Home() {
- const router = useRouter()
- const state = Route.useLoaderData()
-
- return (
-
- )
-}
-```
-
-## Navigation
-
-TanStack Start builds 100% on top of TanStack Router, so all of the navigation features of TanStack Router are available to you. In summary:
-
-- Use the `Link` component to navigate to a new route.
-- Use the `useNavigate` hook to navigate imperatively.
-- Use the `useRouter` hook anywhere in your application to access the router instance and perform invalidations.
-- Every router hook that returns state is reactive, meaning it will automatically re-run when the appropriate state changes.
-
-Here's a quick example of how you can use the `Link` component to navigate to a new route:
-
-```tsx
-import { Link } from '@tanstack/solid-router'
-
-function Home() {
- return About
-}
-```
-
-For more in-depth information on navigation, check out the [navigation guide](/router/latest/docs/framework/solid/guide/navigation).
-
-## Server Functions (RPCs)
-
-You may have noticed the **server function** we created above using `createServerFn`. This is one of TanStack's most powerful features, allowing you to create server-side functions that can be called from both the server during SSR and the client!
-
-Here's a quick overview of how server functions work:
-
-- Server functions are created using the `createServerFn` function.
-- They can be called from both the server during SSR and the client.
-- They can be used to fetch data from the server, or to perform other server-side actions.
-
-Here's a quick example of how you can use server functions to fetch and return data from the server:
-
-```tsx
-import { createServerFn } from '@tanstack/solid-start'
-import * as fs from 'node:fs'
-import { z } from 'zod'
-
-const getUserById = createServerFn({ method: 'GET' })
- // Always validate data sent to the function, here we use Zod
- .validator(z.string())
- // The handler function is where you perform the server-side logic
- .handler(async ({ data }) => {
- return db.query.users.findFirst({ where: eq(users.id, data) })
- })
-
-// Somewhere else in your application
-const user = await getUserById({ data: '1' })
-```
-
-To learn more about server functions, check out the [server functions guide](../server-functions).
-
-### Mutations
-
-Server Functions can also be used to perform mutations on the server. This is also done using the same `createServerFn` function, but with the additional requirement that you invalidate any data on the client that was affected by the mutation.
-
-- If you're using TanStack Router only, you can use the `router.invalidate()` method to invalidate all router data and re-fetch it.
-- If you're using TanStack Query, you can use the `queryClient.invalidateQueries()` method to invalidate data, among other more specific methods to target specific queries.
-
-Here's a quick example of how you can use server functions to perform a mutation on the server and invalidate the data on the client:
-
-```tsx
-import { createServerFn } from '@tanstack/solid-start'
-
-const UserSchema = z.object({
- id: z.string(),
- name: z.string(),
-})
-
-const updateUser = createServerFn({ method: 'POST' })
- .validator(UserSchema)
- .handler(async ({ data }) => {
- return db
- .update(users)
- .set({ name: data.name })
- .where(eq(users.id, data.id))
- })
-
-// Somewhere else in your application
-await updateUser({ data: { id: '1', name: 'John' } })
-```
-
-To learn more about mutations, check out the [mutations guide](/router/latest/docs/framework/solid/guide/data-mutations).
-
-## Data Loading
-
-Another powerful feature of TanStack Router is data loading. This allows you to fetch data for SSR and preload route data before it is rendered. This is done using the `loader` function of a route.
-
-Here's a quick overview of how data loading works:
-
-- Data loading is done using the `loader` function of a route.
-- Data loaders are **isomorphic**, meaning they are executed on both the server and the client.
-- For performing server-only logic, call a server function from within the loader.
-- Similar to TanStack Query, data loaders are cached on the client and are re-used and even re-fetched in the background when the data is stale.
-
-To learn more about data loading, check out the [data loading guide](/router/latest/docs/framework/solid/guide/data-loading).
diff --git a/docs/start/framework/solid/middleware.md b/docs/start/framework/solid/middleware.md
index 97b0c03271..f2362385c3 100644
--- a/docs/start/framework/solid/middleware.md
+++ b/docs/start/framework/solid/middleware.md
@@ -1,4 +1,5 @@
---
ref: docs/start/framework/react/middleware.md
-replace: { 'react': 'solid' }
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
---
diff --git a/docs/start/framework/solid/observability.md b/docs/start/framework/solid/observability.md
index 5de4cf3764..5d7eebdf45 100644
--- a/docs/start/framework/solid/observability.md
+++ b/docs/start/framework/solid/observability.md
@@ -1,3 +1,5 @@
---
ref: docs/start/framework/react/observability.md
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
---
diff --git a/docs/start/framework/solid/overview.md b/docs/start/framework/solid/overview.md
index b9df6becf5..76b10d0136 100644
--- a/docs/start/framework/solid/overview.md
+++ b/docs/start/framework/solid/overview.md
@@ -1,10 +1,9 @@
---
-title: TanStack Start Overview
ref: docs/start/framework/react/overview.md
replace:
{
- 'TanStack Start is a full-stack React': 'TanStack Start (**Experimental for Solid**) is a full-stack',
- "- You're looking for a React-Server-Component-first framework. [(]We'll support RSCs soon in our own awesome flavor![)]": '',
- 'React': 'Solid',
+ '@tanstack/react-start': '@tanstack/solid-start',
+ 'React': 'SolidJS',
+ 'react-router': 'solid-router',
}
---
diff --git a/docs/start/framework/solid/path-aliases.md b/docs/start/framework/solid/path-aliases.md
index c076b7d8ea..29f29aae64 100644
--- a/docs/start/framework/solid/path-aliases.md
+++ b/docs/start/framework/solid/path-aliases.md
@@ -1,4 +1,5 @@
---
ref: docs/start/framework/react/path-aliases.md
-replace: { 'react': 'solid' }
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
---
diff --git a/docs/start/framework/solid/quick-start.md b/docs/start/framework/solid/quick-start.md
index 4006381156..3789efe962 100644
--- a/docs/start/framework/solid/quick-start.md
+++ b/docs/start/framework/solid/quick-start.md
@@ -1,57 +1,9 @@
---
-id: quick-start
-title: Quick Start
+ref: docs/start/framework/react/quick-start.md
+replace:
+ {
+ '@tanstack/react-start': '@tanstack/solid-start',
+ 'React': 'SolidJS',
+ 'react-router': 'solid-router',
+ }
---
-
-## Impatient?
-
-If you're impatient, you can clone and run the [Basic](https://github.com/TanStack/router/tree/main/examples/solid/start-basic) example right away with the following commands:
-
-```bash
-npx degit https://github.com/tanstack/router/examples/solid/start-basic start-basic
-cd start-basic
-npm install
-npm run dev
-```
-
-If you'd like to use a different example, you can replace `start-basic` above with the slug of the example you'd like to use from the list below.
-
-Once you've cloned the example you want, head back to the [Learn the Basics](../learn-the-basics) guide to learn how to use TanStack Start!
-
-## Examples
-
-TanStack Start has load of examples to get you started. Pick one of the examples below to get started!
-
-- [Basic](https://github.com/TanStack/router/tree/main/examples/solid/start-basic) (start-basic)
-- [Bare](https://github.com/TanStack/router/tree/main/examples/solid/start-bare) (start-bare)
-
-### Stackblitz
-
-Each example above has an embedded stackblitz preview to find the one that feels like a good starting point
-
-### Quick Deploy
-
-To quickly deploy an example, click the **Deploy to Netlify** button on an example's page to both clone and deploy the example to Netlify.
-
-### Manual Deploy
-
-To manually clone and deploy the example to anywhere else you'd like, use the following commands replacing `EXAMPLE_SLUG` with the slug of the example you'd like to use from above:
-
-```bash
-npx degit https://github.com/tanstack/router/examples/solid/EXAMPLE_SLUG my-new-project
-cd my-new-project
-npm install
-npm run dev
-```
-
-Once you've clone or deployed an example, head back to the [Learn the Basics](../learn-the-basics) guide to learn how to use TanStack Start!
-
-## Other Router Examples
-
-While not Start-specific examples, these may help you understand more about how TanStack Router works:
-
-- [Quickstart (file-based)](/router/latest/docs/framework/solid/examples/quickstart-file-based)
-- [Basic (file-based)](/router/latest/docs/framework/solid/examples/basic-file-based)
-- [Basic + Solid Query (file-based)](/router/latest/docs/framework/solid/examples/basic-solid-query-file-based)
-- [Basic + Solid Query (code-based)](/router/latest/docs/framework/solid/examples/basic-solid-query)
-- [Kitchen Sink (file-based)](/router/latest/docs/framework/solid/examples/kitchen-sink-file-based)
diff --git a/docs/start/framework/solid/reading-writing-file.md b/docs/start/framework/solid/reading-writing-file.md
new file mode 100644
index 0000000000..00642fef61
--- /dev/null
+++ b/docs/start/framework/solid/reading-writing-file.md
@@ -0,0 +1,5 @@
+---
+ref: docs/start/framework/react/reading-writing-file.md
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
+---
diff --git a/docs/start/framework/solid/routing.md b/docs/start/framework/solid/routing.md
new file mode 100644
index 0000000000..51cde2dddc
--- /dev/null
+++ b/docs/start/framework/solid/routing.md
@@ -0,0 +1,9 @@
+---
+ref: docs/start/framework/react/routing.md
+replace:
+ {
+ '@tanstack/react-start': '@tanstack/solid-start',
+ 'React': 'SolidJS',
+ 'react-router': 'solid-router',
+ }
+---
diff --git a/docs/start/framework/solid/selective-ssr.md b/docs/start/framework/solid/selective-ssr.md
index 1c4d3a7106..2586080db1 100644
--- a/docs/start/framework/solid/selective-ssr.md
+++ b/docs/start/framework/solid/selective-ssr.md
@@ -1,188 +1,5 @@
---
-id: selective-ssr
-title: Selective Server-Side Rendering (SSR)
+ref: docs/start/framework/react/selective-ssr.md
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
---
-
-## What is Selective SSR?
-
-In TanStack Start, routes matching the initial request are rendered on the server by default. This means `beforeLoad` and `loader` are executed on the server, followed by rendering the route components. The resulting HTML is sent to the client, which hydrates the markup into a fully interactive application.
-
-However, there are cases where you might want to disable SSR for certain routes or all routes, such as:
-
-- When `beforeLoad` or `loader` requires browser-only APIs (e.g., `localStorage`).
-- When the route component depends on browser-only APIs (e.g., `canvas`).
-
-TanStack Start's Selective SSR feature lets you configure:
-
-- Which routes should execute `beforeLoad` or `loader` on the server.
-- Which route components should be rendered on the server.
-
-## How does this compare to SPA mode?
-
-TanStack Start's [SPA mode](../spa-mode) completely disables server-side execution of `beforeLoad` and `loader`, as well as server-side rendering of route components. Selective SSR allows you to configure server-side handling on a per-route basis, either statically or dynamically.
-
-## Configuration
-
-You can control how a route is handled during the initial server request using the `ssr` property. If this property is not set, it defaults to `true`. You can change this default using the `defaultSsr` option in `createRouter`:
-
-```tsx
-// src/router.tsx
-import { createRouter as createTanStackRouter } from '@tanstack/solid-router'
-import { routeTree } from './routeTree.gen'
-
-export function createRouter() {
- const router = createTanStackRouter({
- routeTree,
- scrollRestoration: true,
- defaultPendingComponent: () =>
Loading...
,
- // Disable SSR by default
- defaultSsr: false,
- })
-
- return router
-}
-```
-
-### `ssr: true`
-
-This is the default behavior unless otherwise configured. On the initial request, it will:
-
-- Run `beforeLoad` on the server and send the resulting context to the client.
-- Run `loader` on the server and send the loader data to the client.
-- Render the component on the server and send the HTML markup to the client.
-
-```tsx
-// src/routes/posts/$postId.tsx
-export const Route = createFileRoute('/posts/$postId')({
- ssr: true,
- beforeLoad: () => {
- console.log('Executes on the server during the initial request')
- console.log('Executes on the client for subsequent navigation')
- },
- loader: () => {
- console.log('Executes on the server during the initial request')
- console.log('Executes on the client for subsequent navigation')
- },
- component: () =>
This component is rendered on the client
,
-})
-```
-
-### `ssr: false`
-
-This disables server-side:
-
-- Execution of the route's `beforeLoad` and `loader`.
-- Rendering of the route component.
-
-```tsx
-// src/routes/posts/$postId.tsx
-export const Route = createFileRoute('/posts/$postId')({
- ssr: false,
- beforeLoad: () => {
- console.log('Executes on the client during hydration')
- },
- loader: () => {
- console.log('Executes on the client during hydration')
- },
- component: () =>
This component is rendered on the client
,
-})
-```
-
-### `ssr: 'data-only'`
-
-This hybrid option will:
-
-- Run `beforeLoad` on the server and send the resulting context to the client.
-- Run `loader` on the server and send the loader data to the client.
-- Disable server-side rendering of the route component.
-
-```tsx
-// src/routes/posts/$postId.tsx
-export const Route = createFileRoute('/posts/$postId')({
- ssr: 'data-only',
- beforeLoad: () => {
- console.log('Executes on the server during the initial request')
- console.log('Executes on the client for subsequent navigation')
- },
- loader: () => {
- console.log('Executes on the server during the initial request')
- console.log('Executes on the client for subsequent navigation')
- },
- component: () =>
This component is rendered on the client
,
-})
-```
-
-### Functional Form
-
-For more flexibility, you can use the functional form of the `ssr` property to decide at runtime whether to SSR a route:
-
-```tsx
-// src/routes/docs/$docType/$docId.tsx
-export const Route = createFileRoute('/docs/$docType/$docId')({
- validateSearch: z.object({ details: z.boolean().optional() }),
- ssr: ({ params, search }) => {
- if (params.status === 'success' && params.value.docType === 'sheet') {
- return false
- }
- if (search.status === 'success' && search.value.details) {
- return 'data-only'
- }
- },
- beforeLoad: () => {
- console.log('Executes on the server depending on the result of ssr()')
- },
- loader: () => {
- console.log('Executes on the server depending on the result of ssr()')
- },
- component: () =>
This component is rendered on the client
,
-})
-```
-
-The `ssr` function runs only on the server during the initial request and is stripped from the client bundle.
-
-`search` and `params` are passed in after validation as a discriminated union:
-
-```tsx
-params:
- | { status: 'success'; value: Expand> }
- | { status: 'error'; error: unknown }
-search:
- | { status: 'success'; value: Expand> }
- | { status: 'error'; error: unknown }
-```
-
-If validation fails, `status` will be `error` and `error` will contain the failure details. Otherwise, `status` will be `success` and `value` will contain the validated data.
-
-### Inheritance
-
-At runtime, a child route inherits the Selective SSR configuration of its parent. For example:
-
-```tsx
-root { ssr: undefined }
- posts { ssr: false }
- $postId { ssr: true }
-```
-
-- `root` defaults to `ssr: true`.
-- `posts` explicitly sets `ssr: false`, so neither `beforeLoad` nor `loader` will run on the server, and the route component won't be rendered on the server.
-- `$postId` sets `ssr: true`, but inherits `ssr: false` from its parent.
-
-Another example:
-
-```tsx
-root { ssr: undefined }
- posts { ssr: 'data-only' }
- $postId { ssr: true }
- details { ssr: false }
-```
-
-- `root` defaults to `ssr: true`.
-- `posts` sets `ssr: 'data-only'`, so `beforeLoad` and `loader` run on the server, but the route component isn't rendered on the server.
-- `$postId` sets `ssr: true`, but inherits `ssr: 'data-only'` from its parent.
-- `details` sets `ssr: false`, so neither `beforeLoad` nor `loader` will run on the server, and the route component won't be rendered on the server.
-
-## Fallback Rendering
-
-For the first route with `ssr: false` or `ssr: 'data-only'`, the server will render the route's `pendingComponent` as a fallback. If `pendingComponent` isn't configured, the `defaultPendingComponent` will be rendered. If neither is configured, no fallback will be rendered.
-
-On the client during hydration, this fallback will be displayed for at least `minPendingMs` (or `defaultPendingMinMs` if not configured), even if the route doesn't have `beforeLoad` or `loader` defined.
diff --git a/docs/start/framework/solid/server-entry-point.md b/docs/start/framework/solid/server-entry-point.md
new file mode 100644
index 0000000000..986c7c7339
--- /dev/null
+++ b/docs/start/framework/solid/server-entry-point.md
@@ -0,0 +1,5 @@
+---
+ref: docs/start/framework/react/server-entry-point.md
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
+---
diff --git a/docs/start/framework/solid/server-functions.md b/docs/start/framework/solid/server-functions.md
index 2e04beaf50..177d665a31 100644
--- a/docs/start/framework/solid/server-functions.md
+++ b/docs/start/framework/solid/server-functions.md
@@ -1,10 +1,5 @@
---
ref: docs/start/framework/react/server-functions.md
replace:
- {
- 'react': 'solid',
- 'React Server Functions': 'Solid Server Functions',
- '{state}': '{state()}',
- 'While React 19': 'For context, while React 19',
- }
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
---
diff --git a/docs/start/framework/solid/server-routes.md b/docs/start/framework/solid/server-routes.md
index 9fe19933d0..d089b385dc 100644
--- a/docs/start/framework/solid/server-routes.md
+++ b/docs/start/framework/solid/server-routes.md
@@ -1,4 +1,5 @@
---
ref: docs/start/framework/react/server-routes.md
-replace: { 'react': 'solid' }
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
---
diff --git a/docs/start/framework/solid/spa-mode.md b/docs/start/framework/solid/spa-mode.md
index 0124b857d2..2e8f4a6cb5 100644
--- a/docs/start/framework/solid/spa-mode.md
+++ b/docs/start/framework/solid/spa-mode.md
@@ -1,3 +1,5 @@
---
ref: docs/start/framework/react/spa-mode.md
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
---
diff --git a/docs/start/framework/solid/static-prerendering.md b/docs/start/framework/solid/static-prerendering.md
index 37e662958e..65a2fafb0d 100644
--- a/docs/start/framework/solid/static-prerendering.md
+++ b/docs/start/framework/solid/static-prerendering.md
@@ -1,4 +1,5 @@
---
ref: docs/start/framework/react/static-prerendering.md
-replace: { 'react': 'solid' }
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
---
diff --git a/docs/start/framework/solid/static-server-functions.md b/docs/start/framework/solid/static-server-functions.md
index b97841934d..9a91dc3f27 100644
--- a/docs/start/framework/solid/static-server-functions.md
+++ b/docs/start/framework/solid/static-server-functions.md
@@ -1,4 +1,5 @@
---
ref: docs/start/framework/react/static-server-functions.md
-replace: { 'react': 'solid' }
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
---
diff --git a/docs/start/framework/solid/tailwind-integration.md b/docs/start/framework/solid/tailwind-integration.md
index 8e7683acbc..edb778d696 100644
--- a/docs/start/framework/solid/tailwind-integration.md
+++ b/docs/start/framework/solid/tailwind-integration.md
@@ -1,138 +1,5 @@
---
-id: tailwind-integration
-title: Tailwind CSS Integration
+ref: docs/start/framework/react/tailwind-integration.md
+replace:
+ { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
---
-
-_So you want to use Tailwind CSS in your TanStack Start project?_
-
-This guide will help you use Tailwind CSS in your TanStack Start project.
-
-## Tailwind CSS Version 4 (Latest)
-
-The latest version of Tailwind CSS is 4. And it has some configuration changes that majorly differ from Tailwind CSS Version 3. It's **easier and recommended** to set up Tailwind CSS Version 4 in a TanStack Start project, as TanStack Start uses Vite as its build tool.
-
-### Install Tailwind CSS
-
-Install Tailwind CSS and it's Vite plugin.
-
-```shell
-npm install tailwindcss @tailwindcss/vite
-```
-
-### Configure The Vite Plugin
-
-Add the `@tailwindcss/vite` plugin to your Vite configuration.
-
-```ts
-// vite.config.ts
-import { defineConfig } from 'vite'
-import tsConfigPaths from 'vite-tsconfig-paths'
-import { tanstackStart } from '@tanstack/solid-start/plugin/vite'
-import tailwindcss from '@tailwindcss/vite'
-
-export default defineConfig({
- server: {
- port: 3000,
- },
- plugins: [tsConfigPaths(), tanstackStart(), tailwindcss()],
-})
-```
-
-### Import Tailwind in your CSS file
-
-You need to create a CSS file to configure Tailwind CSS instead of the configuration file in version 4. You can do this by creating a `src/styles/app.css` file or name it whatever you want.
-
-```css
-/* src/styles/app.css */
-@import 'tailwindcss';
-```
-
-## Import the CSS file in your `__root.tsx` file
-
-Import the CSS file in your `__root.tsx` file with the `?url` query and make sure to add the **triple slash** directive to the top of the file.
-
-```tsx
-// src/routes/__root.tsx
-///
-// other imports...
-
-import appCss from '../styles/app.css?url'
-
-export const Route = createRootRoute({
- head: () => ({
- meta: [
- // your meta tags and site config
- ],
- links: [{ rel: 'stylesheet', href: appCss }],
- // other head config
- }),
- component: RootComponent,
-})
-```
-
-## Use Tailwind CSS anywhere in your project
-
-You can now use Tailwind CSS anywhere in your project.
-
-```tsx
-// src/routes/index.tsx
-import { createFileRoute } from '@tanstack/solid-router'
-
-export const Route = createFileRoute('/')({
- component: Home,
-})
-
-function Home() {
- return
+
+ Return To Home
+
+
+ Return To Index
+
+
+ Reload
+
+
+ Back
+
+
+ To Relative Link A
+
+
+ To Relative Link B
+
+
+ To Deeply Nested
+
+
+ To Path Param A
+
+
+ To With Search Params
+
+
+
+ Return To Home
+
+
+ Return To Index
+
+
+ Reload
+
+
+ Back
+
+
+ To Relative Link A
+
+
+ To Relative Link B
+
+
+ To Deeply Nested
+
+
+ To Path Param A
+
+
+ To With Search Params
+
+