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 + + + + + + WorkOS logo + + + +- **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 + + + + + + Clerk logo + + + +- **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 - - - - - Clerk logo - - +**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 ( +
+ {/* Form fields */} + +
+ ) +} +``` + +### 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 ( +
+ setQuery(e.target.value)} + /> + Search}> + search(query)} /> + +
+ ) +} +``` + +### 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
{new Date().toLocaleString()}
+} + +// ✅ Consistent rendering +function CurrentTime() { + const [time, setTime] = useState() + + useEffect(() => { + setTime(new Date().toLocaleString()) + }, []) + + return
{time || 'Loading...'}
+} +``` + +## 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 logo - - - -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 + + + + + Cloudflare logo + + 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_ + + + + + + Netlify logo + + + +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 - Convex logo + Sentry logo -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
Dashboard content
+} +``` + +### Health Check Endpoints + +Create server routes for health monitoring: + +```tsx +// routes/health.ts +import { createFileRoute } from '@tanstack/react-router' +import { json } from '@tanstack/react-start' + +export const Route = createFileRoute('/health')({ + server: { + handlers: { + GET: async () => { + const checks = { + status: 'healthy', + timestamp: new Date().toISOString(), + uptime: process.uptime(), + memory: process.memoryUsage(), + database: await checkDatabase(), + version: process.env.npm_package_version, + } + + return json(checks) + }, + }, + }, +}) + +async function checkDatabase() { + try { + await db.raw('SELECT 1') + return { status: 'connected', latency: 0 } + } catch (error) { + return { status: 'error', error: error.message } + } +} +``` + +### Error Boundaries + +Implement comprehensive error handling: + +```tsx +// Client-side error boundary +import { ErrorBoundary } from 'react-error-boundary' + +function ErrorFallback({ error, resetErrorBoundary }: any) { + // Log client errors + console.error('[CLIENT ERROR]:', error) + + // Could also send to external service + // sendErrorToService(error) + + return ( +
+

Something went wrong

+ +
+ ) +} + +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** - - - - - Clerk logo - - - 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** - - - - - Netlify logo - - - 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** - - - - - Neon logo - - - 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** - - - - - Convex logo - - - 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** - - - - - Sentry logo - - - 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 ( -
{ - event.preventDefault() - const formData = new FormData(event.currentTarget) - const response = await greetUser({ data: formData }) - console.log(response) - }} - > - - - -
- ) -} ``` -## 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? - - - - - - Convex logo - - - -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 logo - - - -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
Hello World
-} -``` - -That's it! You can now use Tailwind CSS anywhere in your project 🎉. - -## Tailwind CSS Version 3 (Legacy) - -If you are want to use Tailwind CSS Version 3, you can use the following steps. - -### Install Tailwind CSS - -Install Tailwind CSS and it's peer dependencies. - -```shell -npm install -D tailwindcss@3 postcss autoprefixer -``` - -Then generate the Tailwind and PostCSS configuration files. - -```shell -npx tailwindcss init -p -``` - -### Configure your template paths - -Add the paths to all of your template files in the `tailwind.config.js` file. - -```js -// tailwind.config.js -/** @type {import('tailwindcss').Config} */ -export default { - content: ['./src/**/*.{js,ts,jsx,tsx}'], - theme: { - extend: {}, - }, - plugins: [], -} -``` - -### Add the Tailwind directives to your CSS file - -Add the `@tailwind` directives for each of Tailwind's layers to your `src/styles/app.css` file. - -```css -/* src/styles/app.css */ -@tailwind base; -@tailwind components; -@tailwind utilities; -``` - -> [!NOTE] -> Jump to [Import the CSS file in your `__root.tsx` file](#import-the-css-file-in-your-__roottsx-file) to see how to import the CSS file in your `__root.tsx` file. diff --git a/e2e/e2e-utils/package.json b/e2e/e2e-utils/package.json index 7376c0bca4..ad1b3f10e0 100644 --- a/e2e/e2e-utils/package.json +++ b/e2e/e2e-utils/package.json @@ -9,7 +9,8 @@ "type": "module", "exports": { ".": { - "import": "./src/index.ts" + "import": "./src/index.ts", + "default": "./src/index.ts" }, "./package.json": "./package.json" }, diff --git a/e2e/react-router/sentry-integration/tests/fixture.ts b/e2e/e2e-utils/src/fixture.ts similarity index 100% rename from e2e/react-router/sentry-integration/tests/fixture.ts rename to e2e/e2e-utils/src/fixture.ts diff --git a/e2e/e2e-utils/src/index.ts b/e2e/e2e-utils/src/index.ts index 59cbb0bc62..2a4219ddcf 100644 --- a/e2e/e2e-utils/src/index.ts +++ b/e2e/e2e-utils/src/index.ts @@ -4,3 +4,4 @@ export { toRuntimePath } from './to-runtime-path' export { resolveRuntimeSuffix } from './resolve-runtime-suffix' export { e2eStartDummyServer, e2eStopDummyServer } from './e2eSetupTeardown' export type { Post } from './posts' +export { test } from './fixture' diff --git a/e2e/react-router/basic-file-based-code-splitting/package.json b/e2e/react-router/basic-file-based-code-splitting/package.json index f77929bac7..f6b16f53d8 100644 --- a/e2e/react-router/basic-file-based-code-splitting/package.json +++ b/e2e/react-router/basic-file-based-code-splitting/package.json @@ -29,6 +29,6 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/e2e/react-router/basic-file-based/package.json b/e2e/react-router/basic-file-based/package.json index bd25d40f69..4b528e0735 100644 --- a/e2e/react-router/basic-file-based/package.json +++ b/e2e/react-router/basic-file-based/package.json @@ -30,6 +30,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "combinate": "^1.1.11", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/e2e/react-router/basic-file-based/src/routeTree.gen.ts b/e2e/react-router/basic-file-based/src/routeTree.gen.ts index e44ac41896..62af050d6e 100644 --- a/e2e/react-router/basic-file-based/src/routeTree.gen.ts +++ b/e2e/react-router/basic-file-based/src/routeTree.gen.ts @@ -23,6 +23,7 @@ import { Route as LayoutRouteImport } from './routes/_layout' import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' import { Route as IndexRouteImport } from './routes/index' import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' +import { Route as RelativeIndexRouteImport } from './routes/relative/index' import { Route as RedirectIndexRouteImport } from './routes/redirect/index' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as ParamsPsIndexRouteImport } from './routes/params-ps/index' @@ -35,9 +36,15 @@ import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside import { Route as groupInsideRouteImport } from './routes/(group)/inside' import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' +import { Route as RelativeUseNavigateRouteRouteImport } from './routes/relative/useNavigate/route' +import { Route as RelativeLinkRouteRouteImport } from './routes/relative/link/route' import { Route as RedirectTargetIndexRouteImport } from './routes/redirect/$target/index' import { Route as ParamsPsWildcardIndexRouteImport } from './routes/params-ps/wildcard/index' import { Route as ParamsPsNamedIndexRouteImport } from './routes/params-ps/named/index' +import { Route as RelativeUseNavigateRelativeUseNavigateBRouteImport } from './routes/relative/useNavigate/relative-useNavigate-b' +import { Route as RelativeUseNavigateRelativeUseNavigateARouteImport } from './routes/relative/useNavigate/relative-useNavigate-a' +import { Route as RelativeLinkRelativeLinkBRouteImport } from './routes/relative/link/relative-link-b' +import { Route as RelativeLinkRelativeLinkARouteImport } from './routes/relative/link/relative-link-a' import { Route as RedirectPreloadThirdRouteImport } from './routes/redirect/preload/third' import { Route as RedirectPreloadSecondRouteImport } from './routes/redirect/preload/second' import { Route as RedirectPreloadFirstRouteImport } from './routes/redirect/preload/first' @@ -55,6 +62,16 @@ import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layo import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' import { Route as groupLayoutInsidelayoutRouteImport } from './routes/(group)/_layout.insidelayout' +import { Route as RelativeUseNavigateWithSearchIndexRouteImport } from './routes/relative/useNavigate/with-search/index' +import { Route as RelativeUseNavigatePathIndexRouteImport } from './routes/relative/useNavigate/path/index' +import { Route as RelativeUseNavigateNestedIndexRouteImport } from './routes/relative/useNavigate/nested/index' +import { Route as RelativeLinkWithSearchIndexRouteImport } from './routes/relative/link/with-search/index' +import { Route as RelativeLinkPathIndexRouteImport } from './routes/relative/link/path/index' +import { Route as RelativeLinkNestedIndexRouteImport } from './routes/relative/link/nested/index' +import { Route as RelativeUseNavigatePathPathIndexRouteImport } from './routes/relative/useNavigate/path/$path/index' +import { Route as RelativeUseNavigateNestedDeepIndexRouteImport } from './routes/relative/useNavigate/nested/deep/index' +import { Route as RelativeLinkPathPathIndexRouteImport } from './routes/relative/link/path/$path/index' +import { Route as RelativeLinkNestedDeepIndexRouteImport } from './routes/relative/link/nested/deep/index' const groupRouteImport = createFileRoute('/(group)')() @@ -122,6 +139,11 @@ const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ path: '/', getParentRoute: () => SearchParamsRouteRoute, } as any) +const RelativeIndexRoute = RelativeIndexRouteImport.update({ + id: '/relative/', + path: '/relative/', + getParentRoute: () => rootRouteImport, +} as any) const RedirectIndexRoute = RedirectIndexRouteImport.update({ id: '/redirect/', path: '/redirect/', @@ -184,6 +206,17 @@ const anotherGroupOnlyrouteinsideRoute = path: '/onlyrouteinside', getParentRoute: () => rootRouteImport, } as any) +const RelativeUseNavigateRouteRoute = + RelativeUseNavigateRouteRouteImport.update({ + id: '/relative/useNavigate', + path: '/relative/useNavigate', + getParentRoute: () => rootRouteImport, + } as any) +const RelativeLinkRouteRoute = RelativeLinkRouteRouteImport.update({ + id: '/relative/link', + path: '/relative/link', + getParentRoute: () => rootRouteImport, +} as any) const RedirectTargetIndexRoute = RedirectTargetIndexRouteImport.update({ id: '/', path: '/', @@ -199,6 +232,30 @@ const ParamsPsNamedIndexRoute = ParamsPsNamedIndexRouteImport.update({ path: '/params-ps/named/', getParentRoute: () => rootRouteImport, } as any) +const RelativeUseNavigateRelativeUseNavigateBRoute = + RelativeUseNavigateRelativeUseNavigateBRouteImport.update({ + id: '/relative-useNavigate-b', + path: '/relative-useNavigate-b', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeUseNavigateRelativeUseNavigateARoute = + RelativeUseNavigateRelativeUseNavigateARouteImport.update({ + id: '/relative-useNavigate-a', + path: '/relative-useNavigate-a', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeLinkRelativeLinkBRoute = + RelativeLinkRelativeLinkBRouteImport.update({ + id: '/relative-link-b', + path: '/relative-link-b', + getParentRoute: () => RelativeLinkRouteRoute, + } as any) +const RelativeLinkRelativeLinkARoute = + RelativeLinkRelativeLinkARouteImport.update({ + id: '/relative-link-a', + path: '/relative-link-a', + getParentRoute: () => RelativeLinkRouteRoute, + } as any) const RedirectPreloadThirdRoute = RedirectPreloadThirdRouteImport.update({ id: '/redirect/preload/third', path: '/redirect/preload/third', @@ -289,6 +346,64 @@ const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({ path: '/insidelayout', getParentRoute: () => groupLayoutRoute, } as any) +const RelativeUseNavigateWithSearchIndexRoute = + RelativeUseNavigateWithSearchIndexRouteImport.update({ + id: '/with-search/', + path: '/with-search/', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeUseNavigatePathIndexRoute = + RelativeUseNavigatePathIndexRouteImport.update({ + id: '/path/', + path: '/path/', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeUseNavigateNestedIndexRoute = + RelativeUseNavigateNestedIndexRouteImport.update({ + id: '/nested/', + path: '/nested/', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeLinkWithSearchIndexRoute = + RelativeLinkWithSearchIndexRouteImport.update({ + id: '/with-search/', + path: '/with-search/', + getParentRoute: () => RelativeLinkRouteRoute, + } as any) +const RelativeLinkPathIndexRoute = RelativeLinkPathIndexRouteImport.update({ + id: '/path/', + path: '/path/', + getParentRoute: () => RelativeLinkRouteRoute, +} as any) +const RelativeLinkNestedIndexRoute = RelativeLinkNestedIndexRouteImport.update({ + id: '/nested/', + path: '/nested/', + getParentRoute: () => RelativeLinkRouteRoute, +} as any) +const RelativeUseNavigatePathPathIndexRoute = + RelativeUseNavigatePathPathIndexRouteImport.update({ + id: '/path/$path/', + path: '/path/$path/', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeUseNavigateNestedDeepIndexRoute = + RelativeUseNavigateNestedDeepIndexRouteImport.update({ + id: '/nested/deep/', + path: '/nested/deep/', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeLinkPathPathIndexRoute = + RelativeLinkPathPathIndexRouteImport.update({ + id: '/path/$path/', + path: '/path/$path/', + getParentRoute: () => RelativeLinkRouteRoute, + } as any) +const RelativeLinkNestedDeepIndexRoute = + RelativeLinkNestedDeepIndexRouteImport.update({ + id: '/nested/deep/', + path: '/nested/deep/', + getParentRoute: () => RelativeLinkRouteRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof groupLayoutRouteWithChildren @@ -301,6 +416,8 @@ export interface FileRoutesByFullPath { '/posts': typeof PostsRouteWithChildren '/remountDeps': typeof RemountDepsRoute '/대한민국': typeof Char45824Char54620Char48124Char44397Route + '/relative/link': typeof RelativeLinkRouteRouteWithChildren + '/relative/useNavigate': typeof RelativeUseNavigateRouteRouteWithChildren '/onlyrouteinside': typeof anotherGroupOnlyrouteinsideRoute '/inside': typeof groupInsideRoute '/lazyinside': typeof groupLazyinsideRoute @@ -311,6 +428,7 @@ export interface FileRoutesByFullPath { '/params-ps': typeof ParamsPsIndexRoute '/posts/': typeof PostsIndexRoute '/redirect': typeof RedirectIndexRoute + '/relative': typeof RelativeIndexRoute '/search-params/': typeof SearchParamsIndexRoute '/insidelayout': typeof groupLayoutInsidelayoutRoute '/subfolder/inside': typeof groupSubfolderInsideRoute @@ -329,9 +447,23 @@ export interface FileRoutesByFullPath { '/redirect/preload/first': typeof RedirectPreloadFirstRoute '/redirect/preload/second': typeof RedirectPreloadSecondRoute '/redirect/preload/third': typeof RedirectPreloadThirdRoute + '/relative/link/relative-link-a': typeof RelativeLinkRelativeLinkARoute + '/relative/link/relative-link-b': typeof RelativeLinkRelativeLinkBRoute + '/relative/useNavigate/relative-useNavigate-a': typeof RelativeUseNavigateRelativeUseNavigateARoute + '/relative/useNavigate/relative-useNavigate-b': typeof RelativeUseNavigateRelativeUseNavigateBRoute '/params-ps/named': typeof ParamsPsNamedIndexRoute '/params-ps/wildcard': typeof ParamsPsWildcardIndexRoute '/redirect/$target/': typeof RedirectTargetIndexRoute + '/relative/link/nested': typeof RelativeLinkNestedIndexRoute + '/relative/link/path': typeof RelativeLinkPathIndexRoute + '/relative/link/with-search': typeof RelativeLinkWithSearchIndexRoute + '/relative/useNavigate/nested': typeof RelativeUseNavigateNestedIndexRoute + '/relative/useNavigate/path': typeof RelativeUseNavigatePathIndexRoute + '/relative/useNavigate/with-search': typeof RelativeUseNavigateWithSearchIndexRoute + '/relative/link/nested/deep': typeof RelativeLinkNestedDeepIndexRoute + '/relative/link/path/$path': typeof RelativeLinkPathPathIndexRoute + '/relative/useNavigate/nested/deep': typeof RelativeUseNavigateNestedDeepIndexRoute + '/relative/useNavigate/path/$path': typeof RelativeUseNavigatePathPathIndexRoute } export interface FileRoutesByTo { '/': typeof groupLayoutRouteWithChildren @@ -342,6 +474,8 @@ export interface FileRoutesByTo { '/notRemountDeps': typeof NotRemountDepsRoute '/remountDeps': typeof RemountDepsRoute '/대한민국': typeof Char45824Char54620Char48124Char44397Route + '/relative/link': typeof RelativeLinkRouteRouteWithChildren + '/relative/useNavigate': typeof RelativeUseNavigateRouteRouteWithChildren '/onlyrouteinside': typeof anotherGroupOnlyrouteinsideRoute '/inside': typeof groupInsideRoute '/lazyinside': typeof groupLazyinsideRoute @@ -351,6 +485,7 @@ export interface FileRoutesByTo { '/params-ps': typeof ParamsPsIndexRoute '/posts': typeof PostsIndexRoute '/redirect': typeof RedirectIndexRoute + '/relative': typeof RelativeIndexRoute '/search-params': typeof SearchParamsIndexRoute '/insidelayout': typeof groupLayoutInsidelayoutRoute '/subfolder/inside': typeof groupSubfolderInsideRoute @@ -369,9 +504,23 @@ export interface FileRoutesByTo { '/redirect/preload/first': typeof RedirectPreloadFirstRoute '/redirect/preload/second': typeof RedirectPreloadSecondRoute '/redirect/preload/third': typeof RedirectPreloadThirdRoute + '/relative/link/relative-link-a': typeof RelativeLinkRelativeLinkARoute + '/relative/link/relative-link-b': typeof RelativeLinkRelativeLinkBRoute + '/relative/useNavigate/relative-useNavigate-a': typeof RelativeUseNavigateRelativeUseNavigateARoute + '/relative/useNavigate/relative-useNavigate-b': typeof RelativeUseNavigateRelativeUseNavigateBRoute '/params-ps/named': typeof ParamsPsNamedIndexRoute '/params-ps/wildcard': typeof ParamsPsWildcardIndexRoute '/redirect/$target': typeof RedirectTargetIndexRoute + '/relative/link/nested': typeof RelativeLinkNestedIndexRoute + '/relative/link/path': typeof RelativeLinkPathIndexRoute + '/relative/link/with-search': typeof RelativeLinkWithSearchIndexRoute + '/relative/useNavigate/nested': typeof RelativeUseNavigateNestedIndexRoute + '/relative/useNavigate/path': typeof RelativeUseNavigatePathIndexRoute + '/relative/useNavigate/with-search': typeof RelativeUseNavigateWithSearchIndexRoute + '/relative/link/nested/deep': typeof RelativeLinkNestedDeepIndexRoute + '/relative/link/path/$path': typeof RelativeLinkPathPathIndexRoute + '/relative/useNavigate/nested/deep': typeof RelativeUseNavigateNestedDeepIndexRoute + '/relative/useNavigate/path/$path': typeof RelativeUseNavigatePathPathIndexRoute } export interface FileRoutesById { __root__: typeof rootRouteImport @@ -386,6 +535,8 @@ export interface FileRoutesById { '/posts': typeof PostsRouteWithChildren '/remountDeps': typeof RemountDepsRoute '/대한민국': typeof Char45824Char54620Char48124Char44397Route + '/relative/link': typeof RelativeLinkRouteRouteWithChildren + '/relative/useNavigate': typeof RelativeUseNavigateRouteRouteWithChildren '/(another-group)/onlyrouteinside': typeof anotherGroupOnlyrouteinsideRoute '/(group)': typeof groupRouteWithChildren '/(group)/_layout': typeof groupLayoutRouteWithChildren @@ -399,6 +550,7 @@ export interface FileRoutesById { '/params-ps/': typeof ParamsPsIndexRoute '/posts/': typeof PostsIndexRoute '/redirect/': typeof RedirectIndexRoute + '/relative/': typeof RelativeIndexRoute '/search-params/': typeof SearchParamsIndexRoute '/(group)/_layout/insidelayout': typeof groupLayoutInsidelayoutRoute '/(group)/subfolder/inside': typeof groupSubfolderInsideRoute @@ -417,9 +569,23 @@ export interface FileRoutesById { '/redirect/preload/first': typeof RedirectPreloadFirstRoute '/redirect/preload/second': typeof RedirectPreloadSecondRoute '/redirect/preload/third': typeof RedirectPreloadThirdRoute + '/relative/link/relative-link-a': typeof RelativeLinkRelativeLinkARoute + '/relative/link/relative-link-b': typeof RelativeLinkRelativeLinkBRoute + '/relative/useNavigate/relative-useNavigate-a': typeof RelativeUseNavigateRelativeUseNavigateARoute + '/relative/useNavigate/relative-useNavigate-b': typeof RelativeUseNavigateRelativeUseNavigateBRoute '/params-ps/named/': typeof ParamsPsNamedIndexRoute '/params-ps/wildcard/': typeof ParamsPsWildcardIndexRoute '/redirect/$target/': typeof RedirectTargetIndexRoute + '/relative/link/nested/': typeof RelativeLinkNestedIndexRoute + '/relative/link/path/': typeof RelativeLinkPathIndexRoute + '/relative/link/with-search/': typeof RelativeLinkWithSearchIndexRoute + '/relative/useNavigate/nested/': typeof RelativeUseNavigateNestedIndexRoute + '/relative/useNavigate/path/': typeof RelativeUseNavigatePathIndexRoute + '/relative/useNavigate/with-search/': typeof RelativeUseNavigateWithSearchIndexRoute + '/relative/link/nested/deep/': typeof RelativeLinkNestedDeepIndexRoute + '/relative/link/path/$path/': typeof RelativeLinkPathPathIndexRoute + '/relative/useNavigate/nested/deep/': typeof RelativeUseNavigateNestedDeepIndexRoute + '/relative/useNavigate/path/$path/': typeof RelativeUseNavigatePathPathIndexRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath @@ -434,6 +600,8 @@ export interface FileRouteTypes { | '/posts' | '/remountDeps' | '/대한민국' + | '/relative/link' + | '/relative/useNavigate' | '/onlyrouteinside' | '/inside' | '/lazyinside' @@ -444,6 +612,7 @@ export interface FileRouteTypes { | '/params-ps' | '/posts/' | '/redirect' + | '/relative' | '/search-params/' | '/insidelayout' | '/subfolder/inside' @@ -462,9 +631,23 @@ export interface FileRouteTypes { | '/redirect/preload/first' | '/redirect/preload/second' | '/redirect/preload/third' + | '/relative/link/relative-link-a' + | '/relative/link/relative-link-b' + | '/relative/useNavigate/relative-useNavigate-a' + | '/relative/useNavigate/relative-useNavigate-b' | '/params-ps/named' | '/params-ps/wildcard' | '/redirect/$target/' + | '/relative/link/nested' + | '/relative/link/path' + | '/relative/link/with-search' + | '/relative/useNavigate/nested' + | '/relative/useNavigate/path' + | '/relative/useNavigate/with-search' + | '/relative/link/nested/deep' + | '/relative/link/path/$path' + | '/relative/useNavigate/nested/deep' + | '/relative/useNavigate/path/$path' fileRoutesByTo: FileRoutesByTo to: | '/' @@ -475,6 +658,8 @@ export interface FileRouteTypes { | '/notRemountDeps' | '/remountDeps' | '/대한민국' + | '/relative/link' + | '/relative/useNavigate' | '/onlyrouteinside' | '/inside' | '/lazyinside' @@ -484,6 +669,7 @@ export interface FileRouteTypes { | '/params-ps' | '/posts' | '/redirect' + | '/relative' | '/search-params' | '/insidelayout' | '/subfolder/inside' @@ -502,9 +688,23 @@ export interface FileRouteTypes { | '/redirect/preload/first' | '/redirect/preload/second' | '/redirect/preload/third' + | '/relative/link/relative-link-a' + | '/relative/link/relative-link-b' + | '/relative/useNavigate/relative-useNavigate-a' + | '/relative/useNavigate/relative-useNavigate-b' | '/params-ps/named' | '/params-ps/wildcard' | '/redirect/$target' + | '/relative/link/nested' + | '/relative/link/path' + | '/relative/link/with-search' + | '/relative/useNavigate/nested' + | '/relative/useNavigate/path' + | '/relative/useNavigate/with-search' + | '/relative/link/nested/deep' + | '/relative/link/path/$path' + | '/relative/useNavigate/nested/deep' + | '/relative/useNavigate/path/$path' id: | '__root__' | '/' @@ -518,6 +718,8 @@ export interface FileRouteTypes { | '/posts' | '/remountDeps' | '/대한민국' + | '/relative/link' + | '/relative/useNavigate' | '/(another-group)/onlyrouteinside' | '/(group)' | '/(group)/_layout' @@ -531,6 +733,7 @@ export interface FileRouteTypes { | '/params-ps/' | '/posts/' | '/redirect/' + | '/relative/' | '/search-params/' | '/(group)/_layout/insidelayout' | '/(group)/subfolder/inside' @@ -549,9 +752,23 @@ export interface FileRouteTypes { | '/redirect/preload/first' | '/redirect/preload/second' | '/redirect/preload/third' + | '/relative/link/relative-link-a' + | '/relative/link/relative-link-b' + | '/relative/useNavigate/relative-useNavigate-a' + | '/relative/useNavigate/relative-useNavigate-b' | '/params-ps/named/' | '/params-ps/wildcard/' | '/redirect/$target/' + | '/relative/link/nested/' + | '/relative/link/path/' + | '/relative/link/with-search/' + | '/relative/useNavigate/nested/' + | '/relative/useNavigate/path/' + | '/relative/useNavigate/with-search/' + | '/relative/link/nested/deep/' + | '/relative/link/path/$path/' + | '/relative/useNavigate/nested/deep/' + | '/relative/useNavigate/path/$path/' fileRoutesById: FileRoutesById } export interface RootRouteChildren { @@ -566,12 +783,15 @@ export interface RootRouteChildren { PostsRoute: typeof PostsRouteWithChildren RemountDepsRoute: typeof RemountDepsRoute Char45824Char54620Char48124Char44397Route: typeof Char45824Char54620Char48124Char44397Route + RelativeLinkRouteRoute: typeof RelativeLinkRouteRouteWithChildren + RelativeUseNavigateRouteRoute: typeof RelativeUseNavigateRouteRouteWithChildren anotherGroupOnlyrouteinsideRoute: typeof anotherGroupOnlyrouteinsideRoute groupRoute: typeof groupRouteWithChildren RedirectTargetRoute: typeof RedirectTargetRouteWithChildren StructuralSharingEnabledRoute: typeof StructuralSharingEnabledRoute ParamsPsIndexRoute: typeof ParamsPsIndexRoute RedirectIndexRoute: typeof RedirectIndexRoute + RelativeIndexRoute: typeof RelativeIndexRoute ParamsPsNamedFooRoute: typeof ParamsPsNamedFooRoute ParamsPsNamedPrefixChar123fooChar125Route: typeof ParamsPsNamedPrefixChar123fooChar125Route ParamsPsNamedChar123fooChar125suffixRoute: typeof ParamsPsNamedChar123fooChar125suffixRoute @@ -680,6 +900,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SearchParamsIndexRouteImport parentRoute: typeof SearchParamsRouteRoute } + '/relative/': { + id: '/relative/' + path: '/relative' + fullPath: '/relative' + preLoaderRoute: typeof RelativeIndexRouteImport + parentRoute: typeof rootRouteImport + } '/redirect/': { id: '/redirect/' path: '/redirect' @@ -764,6 +991,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport parentRoute: typeof rootRouteImport } + '/relative/useNavigate': { + id: '/relative/useNavigate' + path: '/relative/useNavigate' + fullPath: '/relative/useNavigate' + preLoaderRoute: typeof RelativeUseNavigateRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/relative/link': { + id: '/relative/link' + path: '/relative/link' + fullPath: '/relative/link' + preLoaderRoute: typeof RelativeLinkRouteRouteImport + parentRoute: typeof rootRouteImport + } '/redirect/$target/': { id: '/redirect/$target/' path: '/' @@ -785,6 +1026,34 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ParamsPsNamedIndexRouteImport parentRoute: typeof rootRouteImport } + '/relative/useNavigate/relative-useNavigate-b': { + id: '/relative/useNavigate/relative-useNavigate-b' + path: '/relative-useNavigate-b' + fullPath: '/relative/useNavigate/relative-useNavigate-b' + preLoaderRoute: typeof RelativeUseNavigateRelativeUseNavigateBRouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute + } + '/relative/useNavigate/relative-useNavigate-a': { + id: '/relative/useNavigate/relative-useNavigate-a' + path: '/relative-useNavigate-a' + fullPath: '/relative/useNavigate/relative-useNavigate-a' + preLoaderRoute: typeof RelativeUseNavigateRelativeUseNavigateARouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute + } + '/relative/link/relative-link-b': { + id: '/relative/link/relative-link-b' + path: '/relative-link-b' + fullPath: '/relative/link/relative-link-b' + preLoaderRoute: typeof RelativeLinkRelativeLinkBRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } + '/relative/link/relative-link-a': { + id: '/relative/link/relative-link-a' + path: '/relative-link-a' + fullPath: '/relative/link/relative-link-a' + preLoaderRoute: typeof RelativeLinkRelativeLinkARouteImport + parentRoute: typeof RelativeLinkRouteRoute + } '/redirect/preload/third': { id: '/redirect/preload/third' path: '/redirect/preload/third' @@ -904,6 +1173,76 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport parentRoute: typeof groupLayoutRoute } + '/relative/useNavigate/with-search/': { + id: '/relative/useNavigate/with-search/' + path: '/with-search' + fullPath: '/relative/useNavigate/with-search' + preLoaderRoute: typeof RelativeUseNavigateWithSearchIndexRouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute + } + '/relative/useNavigate/path/': { + id: '/relative/useNavigate/path/' + path: '/path' + fullPath: '/relative/useNavigate/path' + preLoaderRoute: typeof RelativeUseNavigatePathIndexRouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute + } + '/relative/useNavigate/nested/': { + id: '/relative/useNavigate/nested/' + path: '/nested' + fullPath: '/relative/useNavigate/nested' + preLoaderRoute: typeof RelativeUseNavigateNestedIndexRouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute + } + '/relative/link/with-search/': { + id: '/relative/link/with-search/' + path: '/with-search' + fullPath: '/relative/link/with-search' + preLoaderRoute: typeof RelativeLinkWithSearchIndexRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } + '/relative/link/path/': { + id: '/relative/link/path/' + path: '/path' + fullPath: '/relative/link/path' + preLoaderRoute: typeof RelativeLinkPathIndexRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } + '/relative/link/nested/': { + id: '/relative/link/nested/' + path: '/nested' + fullPath: '/relative/link/nested' + preLoaderRoute: typeof RelativeLinkNestedIndexRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } + '/relative/useNavigate/path/$path/': { + id: '/relative/useNavigate/path/$path/' + path: '/path/$path' + fullPath: '/relative/useNavigate/path/$path' + preLoaderRoute: typeof RelativeUseNavigatePathPathIndexRouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute + } + '/relative/useNavigate/nested/deep/': { + id: '/relative/useNavigate/nested/deep/' + path: '/nested/deep' + fullPath: '/relative/useNavigate/nested/deep' + preLoaderRoute: typeof RelativeUseNavigateNestedDeepIndexRouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute + } + '/relative/link/path/$path/': { + id: '/relative/link/path/$path/' + path: '/path/$path' + fullPath: '/relative/link/path/$path' + preLoaderRoute: typeof RelativeLinkPathPathIndexRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } + '/relative/link/nested/deep/': { + id: '/relative/link/nested/deep/' + path: '/nested/deep' + fullPath: '/relative/link/nested/deep' + preLoaderRoute: typeof RelativeLinkNestedDeepIndexRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } } } @@ -957,6 +1296,60 @@ const PostsRouteChildren: PostsRouteChildren = { const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) +interface RelativeLinkRouteRouteChildren { + RelativeLinkRelativeLinkARoute: typeof RelativeLinkRelativeLinkARoute + RelativeLinkRelativeLinkBRoute: typeof RelativeLinkRelativeLinkBRoute + RelativeLinkNestedIndexRoute: typeof RelativeLinkNestedIndexRoute + RelativeLinkPathIndexRoute: typeof RelativeLinkPathIndexRoute + RelativeLinkWithSearchIndexRoute: typeof RelativeLinkWithSearchIndexRoute + RelativeLinkNestedDeepIndexRoute: typeof RelativeLinkNestedDeepIndexRoute + RelativeLinkPathPathIndexRoute: typeof RelativeLinkPathPathIndexRoute +} + +const RelativeLinkRouteRouteChildren: RelativeLinkRouteRouteChildren = { + RelativeLinkRelativeLinkARoute: RelativeLinkRelativeLinkARoute, + RelativeLinkRelativeLinkBRoute: RelativeLinkRelativeLinkBRoute, + RelativeLinkNestedIndexRoute: RelativeLinkNestedIndexRoute, + RelativeLinkPathIndexRoute: RelativeLinkPathIndexRoute, + RelativeLinkWithSearchIndexRoute: RelativeLinkWithSearchIndexRoute, + RelativeLinkNestedDeepIndexRoute: RelativeLinkNestedDeepIndexRoute, + RelativeLinkPathPathIndexRoute: RelativeLinkPathPathIndexRoute, +} + +const RelativeLinkRouteRouteWithChildren = + RelativeLinkRouteRoute._addFileChildren(RelativeLinkRouteRouteChildren) + +interface RelativeUseNavigateRouteRouteChildren { + RelativeUseNavigateRelativeUseNavigateARoute: typeof RelativeUseNavigateRelativeUseNavigateARoute + RelativeUseNavigateRelativeUseNavigateBRoute: typeof RelativeUseNavigateRelativeUseNavigateBRoute + RelativeUseNavigateNestedIndexRoute: typeof RelativeUseNavigateNestedIndexRoute + RelativeUseNavigatePathIndexRoute: typeof RelativeUseNavigatePathIndexRoute + RelativeUseNavigateWithSearchIndexRoute: typeof RelativeUseNavigateWithSearchIndexRoute + RelativeUseNavigateNestedDeepIndexRoute: typeof RelativeUseNavigateNestedDeepIndexRoute + RelativeUseNavigatePathPathIndexRoute: typeof RelativeUseNavigatePathPathIndexRoute +} + +const RelativeUseNavigateRouteRouteChildren: RelativeUseNavigateRouteRouteChildren = + { + RelativeUseNavigateRelativeUseNavigateARoute: + RelativeUseNavigateRelativeUseNavigateARoute, + RelativeUseNavigateRelativeUseNavigateBRoute: + RelativeUseNavigateRelativeUseNavigateBRoute, + RelativeUseNavigateNestedIndexRoute: RelativeUseNavigateNestedIndexRoute, + RelativeUseNavigatePathIndexRoute: RelativeUseNavigatePathIndexRoute, + RelativeUseNavigateWithSearchIndexRoute: + RelativeUseNavigateWithSearchIndexRoute, + RelativeUseNavigateNestedDeepIndexRoute: + RelativeUseNavigateNestedDeepIndexRoute, + RelativeUseNavigatePathPathIndexRoute: + RelativeUseNavigatePathPathIndexRoute, + } + +const RelativeUseNavigateRouteRouteWithChildren = + RelativeUseNavigateRouteRoute._addFileChildren( + RelativeUseNavigateRouteRouteChildren, + ) + interface groupLayoutRouteChildren { groupLayoutInsidelayoutRoute: typeof groupLayoutInsidelayoutRoute } @@ -1014,12 +1407,15 @@ const rootRouteChildren: RootRouteChildren = { RemountDepsRoute: RemountDepsRoute, Char45824Char54620Char48124Char44397Route: Char45824Char54620Char48124Char44397Route, + RelativeLinkRouteRoute: RelativeLinkRouteRouteWithChildren, + RelativeUseNavigateRouteRoute: RelativeUseNavigateRouteRouteWithChildren, anotherGroupOnlyrouteinsideRoute: anotherGroupOnlyrouteinsideRoute, groupRoute: groupRouteWithChildren, RedirectTargetRoute: RedirectTargetRouteWithChildren, StructuralSharingEnabledRoute: StructuralSharingEnabledRoute, ParamsPsIndexRoute: ParamsPsIndexRoute, RedirectIndexRoute: RedirectIndexRoute, + RelativeIndexRoute: RelativeIndexRoute, ParamsPsNamedFooRoute: ParamsPsNamedFooRoute, ParamsPsNamedPrefixChar123fooChar125Route: ParamsPsNamedPrefixChar123fooChar125Route, diff --git a/e2e/react-router/basic-file-based/src/routes/__root.tsx b/e2e/react-router/basic-file-based/src/routes/__root.tsx index 4062165c86..06734a3b95 100644 --- a/e2e/react-router/basic-file-based/src/routes/__root.tsx +++ b/e2e/react-router/basic-file-based/src/routes/__root.tsx @@ -122,6 +122,14 @@ function RootComponent() { > redirect {' '} + + relative routing + {' '} +
+ Relative Routing Tests - Home +
+
+ Using Links + Using useNavigate +
+
+ +
+ + ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/link/nested/deep/index.tsx b/e2e/react-router/basic-file-based/src/routes/relative/link/nested/deep/index.tsx new file mode 100644 index 0000000000..5cc4b4e58a --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/link/nested/deep/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/relative/link/nested/deep/')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+ Hello "/relative/link/nested/deep/"! +
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/link/nested/index.tsx b/e2e/react-router/basic-file-based/src/routes/relative/link/nested/index.tsx new file mode 100644 index 0000000000..afca201e02 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/link/nested/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/relative/link/nested/')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+ Hello "/relative/link/nested/"! +
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/link/path/$path/index.tsx b/e2e/react-router/basic-file-based/src/routes/relative/link/path/$path/index.tsx new file mode 100644 index 0000000000..30b13cb09d --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/link/path/$path/index.tsx @@ -0,0 +1,31 @@ +import { Link, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/relative/link/path/$path/')({ + component: RouteComponent, + loader: ({ params }) => { + return params + }, +}) + +function RouteComponent() { + const { path } = Route.useParams() + + return ( +
+
+ Hello from "/relative/links/path/{path}"! +
+
+ + To {path === 'a' ? 'b' : 'a'} + +
+
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/link/path/index.tsx b/e2e/react-router/basic-file-based/src/routes/relative/link/path/index.tsx new file mode 100644 index 0000000000..be1c7b7a47 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/link/path/index.tsx @@ -0,0 +1,18 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/relative/link/path/')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+
+ Relative Routing Tests - Path Params +
+
+ +
+
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/link/relative-link-a.tsx b/e2e/react-router/basic-file-based/src/routes/relative/link/relative-link-a.tsx new file mode 100644 index 0000000000..72a1ee20ec --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/link/relative-link-a.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/relative/link/relative-link-a')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+ Hello "/relative/link/relative-link-a"! +
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/link/relative-link-b.tsx b/e2e/react-router/basic-file-based/src/routes/relative/link/relative-link-b.tsx new file mode 100644 index 0000000000..e751331b3f --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/link/relative-link-b.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/relative/link/relative-link-b')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+ Hello "/relative/link/relative-link-b"! +
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/link/route.tsx b/e2e/react-router/basic-file-based/src/routes/relative/link/route.tsx new file mode 100644 index 0000000000..ae3193613f --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/link/route.tsx @@ -0,0 +1,103 @@ +import { + Link, + Outlet, + createFileRoute, + useNavigate, +} from '@tanstack/react-router' +import { useEffect } from 'react' + +export const Route = createFileRoute('/relative/link')({ + component: RouteComponent, +}) + +function RouteComponent() { + const navigate = useNavigate() + + useEffect(() => { + console.log('navigate') + }, [navigate]) + + return ( +
+
+ Relative Routing - Links - Index +
+
+ + 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 + +
+
+ +
+
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/link/with-search/index.tsx b/e2e/react-router/basic-file-based/src/routes/relative/link/with-search/index.tsx new file mode 100644 index 0000000000..9891d26cc0 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/link/with-search/index.tsx @@ -0,0 +1,28 @@ +import { Link, createFileRoute } from '@tanstack/react-router' +import { z } from 'zod' + +export const Route = createFileRoute('/relative/link/with-search/')({ + component: RouteComponent, + validateSearch: z.object({ + searchParam: z.string().default('1'), + }), +}) + +function RouteComponent() { + const { searchParam } = Route.useSearch() + return ( + <> +
+ Hello "/relative/link/with-search/" searchParam: {searchParam}! +
+
+ + Update Search + + + ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/nested/deep/index.tsx b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/nested/deep/index.tsx new file mode 100644 index 0000000000..453a088d63 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/nested/deep/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/relative/useNavigate/nested/deep/')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+ Hello "/relative/useNavigate/nested/deep/"! +
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/nested/index.tsx b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/nested/index.tsx new file mode 100644 index 0000000000..ace502df18 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/nested/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/relative/useNavigate/nested/')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+ Hello "/relative/useNavigate/nested/"! +
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/path/$path/index.tsx b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/path/$path/index.tsx new file mode 100644 index 0000000000..2e6d4c59de --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/path/$path/index.tsx @@ -0,0 +1,40 @@ +import { createFileRoute, useNavigate } from '@tanstack/react-router' + +export const Route = createFileRoute('/relative/useNavigate/path/$path/')({ + component: RouteComponent, + loader: ({ params }) => { + return params + }, +}) + +function RouteComponent() { + const navigate = useNavigate() + + const { path } = Route.useParams() + + return ( +
+
+ Hello from "/relative/useNavigate/path/{path}"! +
+
+ +
+
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/path/index.tsx b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/path/index.tsx new file mode 100644 index 0000000000..18abb4af18 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/path/index.tsx @@ -0,0 +1,18 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/relative/useNavigate/path/')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+
+ Relative Routing Tests - Path Params +
+
+ +
+
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/relative-useNavigate-a.tsx b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/relative-useNavigate-a.tsx new file mode 100644 index 0000000000..e236d80f63 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/relative-useNavigate-a.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute( + '/relative/useNavigate/relative-useNavigate-a', +)({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+ Hello "/relative/useNavigate/relative-useNavigate-a"! +
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/relative-useNavigate-b.tsx b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/relative-useNavigate-b.tsx new file mode 100644 index 0000000000..b6e1d607dd --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/relative-useNavigate-b.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute( + '/relative/useNavigate/relative-useNavigate-b', +)({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+ Hello "/relative/useNavigate/relative-useNavigate-b"! +
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/route.tsx b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/route.tsx new file mode 100644 index 0000000000..567df92e8b --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/route.tsx @@ -0,0 +1,134 @@ +import { Outlet, createFileRoute, useNavigate } from '@tanstack/react-router' +import { useEffect } from 'react' + +export const Route = createFileRoute('/relative/useNavigate')({ + component: RouteComponent, +}) + +function RouteComponent() { + const navigate = useNavigate() + + useEffect(() => { + console.log('navigate') + }, [navigate]) + + return ( +
+
+ Relative Routing - Links - Index +
+
+ + + + + + + + + +
+
+ +
+
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/with-search/index.tsx b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/with-search/index.tsx new file mode 100644 index 0000000000..7342202e1d --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/relative/useNavigate/with-search/index.tsx @@ -0,0 +1,34 @@ +import { createFileRoute, useNavigate } from '@tanstack/react-router' +import { z } from 'zod' + +export const Route = createFileRoute('/relative/useNavigate/with-search/')({ + component: RouteComponent, + validateSearch: z.object({ + searchParam: z.string().default('1'), + }), +}) + +function RouteComponent() { + const navigate = useNavigate() + const { searchParam } = Route.useSearch() + + return ( + <> +
+ Hello "/relative/useNavigate/with-search/" searchParam: {searchParam}! +
+
+ + + ) +} diff --git a/e2e/react-router/basic-file-based/tests/relative.spec.ts b/e2e/react-router/basic-file-based/tests/relative.spec.ts new file mode 100644 index 0000000000..4850d3630d --- /dev/null +++ b/e2e/react-router/basic-file-based/tests/relative.spec.ts @@ -0,0 +1,273 @@ +import { expect, test } from '@playwright/test' +import combinateImport from 'combinate' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } + +// somehow playwright does not correctly import default exports +const combinate = (combinateImport as any).default as typeof combinateImport + +const PORT = await getTestServerPort(packageJson.name) + +test.describe('relative_routing', () => { + const internalNavigationTestMatrix = combinate({ + navigation: ['link', 'useNavigate'] as const, + }) + + internalNavigationTestMatrix.forEach(({ navigation }) => { + test(`simple relative navigation. navigation: ${navigation}`, async ({ + page, + }) => { + await page.waitForLoadState('networkidle') + await page.goto(`/relative/${navigation}`) + await page.waitForURL(`http://localhost:${PORT}/relative/${navigation}`) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + const indexLink = page.getByTestId(`relative-${navigation}-index`) + const backLink = page.getByTestId(`relative-${navigation}-back`) + const relativeRouteA = page.getByTestId(`relative-${navigation}-a`) + const relativeRouteB = page.getByTestId(`relative-${navigation}-b`) + + await relativeRouteA.click() + + await page.waitForURL( + `http://localhost:${PORT}/relative/${navigation}/relative-${navigation}-a`, + ) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + await expect( + page.getByTestId(`relative-${navigation}-a-header`), + ).toBeInViewport() + + await relativeRouteB.click() + + await page.waitForURL( + `http://localhost:${PORT}/relative/${navigation}/relative-${navigation}-b`, + ) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + await expect( + page.getByTestId(`relative-${navigation}-b-header`), + ).toBeInViewport() + + await indexLink.click() + + await page.waitForURL(`http://localhost:${PORT}/relative/${navigation}`) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + await expect( + page.getByTestId(`relative-${navigation}-b-header`), + ).not.toBeInViewport() + + await backLink.click() + + await page.waitForURL(`http://localhost:${PORT}/relative`) + + await expect(page.getByTestId(`relative-routing-home`)).toBeInViewport() + }) + + test(`nested chilren. navigation: ${navigation}`, async ({ page }) => { + await page.waitForLoadState('networkidle') + await page.goto(`/relative/${navigation}`) + await page.waitForURL(`http://localhost:${PORT}/relative/${navigation}`) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + const backLink = page.getByTestId(`relative-${navigation}-back`) + + const deeplyNestedChildRoute = page.getByTestId( + `relative-${navigation}-deeply-nested`, + ) + + await deeplyNestedChildRoute.click() + + await page.waitForURL( + `http://localhost:${PORT}/relative/${navigation}/nested/deep`, + ) + + await expect( + page.getByTestId(`relative-${navigation}-nested-deep-header`), + ).toBeInViewport() + + await backLink.click() + + await page.waitForURL( + `http://localhost:${PORT}/relative/${navigation}/nested`, + ) + + await expect( + page.getByTestId(`relative-${navigation}-nested-header`), + ).toBeInViewport() + }) + + test(`with path params. navigation: ${navigation}`, async ({ page }) => { + await page.waitForLoadState('networkidle') + await page.goto(`/relative/${navigation}`) + await page.waitForURL(`http://localhost:${PORT}/relative/${navigation}`) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + const pathParamRoute = page.getByTestId(`relative-${navigation}-path`) + + await pathParamRoute.click() + + await page.waitForURL( + `http://localhost:${PORT}/relative/${navigation}/path/a`, + ) + + expect(page.url().endsWith('/path/a')).toBe(true) + + await expect( + page.getByTestId(`relative-${navigation}-path-param-header`), + ).toBeInViewport() + + const switchParamLink = page.getByTestId( + `relative-${navigation}-path-param-switchAB`, + ) + + await switchParamLink.click() + + await page.waitForURL( + `http://localhost:${PORT}/relative/${navigation}/path/b`, + ) + + expect(page.url().endsWith('/path/b')).toBe(true) + + await expect( + page.getByTestId(`relative-${navigation}-path-param-header`), + ).toBeInViewport() + }) + + test(`with search params. navigation: ${navigation}`, async ({ page }) => { + await page.waitForLoadState('networkidle') + await page.goto(`/relative/${navigation}`) + await page.waitForURL(`http://localhost:${PORT}/relative/${navigation}`) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + const searchParamRoute = page.getByTestId( + `relative-${navigation}-withSearch`, + ) + + await searchParamRoute.click() + + let expectedUrl = new URL( + `http://localhost:${PORT}/relative/${navigation}/with-search?searchParam="1"`, + ) + + await page.waitForLoadState('domcontentloaded') + + expect(page.url().toString()).toBe(expectedUrl.toString()) + + await expect( + page.getByTestId(`relative-${navigation}-withSearch-header`), + ).toBeInViewport() + + await expect( + page.getByTestId(`relative-${navigation}-withSearch-header`), + ).toContainText('searchParam: 1') + + const updateSearchLink = page.getByTestId( + `relative-${navigation}-withSearch-update-param`, + ) + + await updateSearchLink.click() + + await page.waitForLoadState('domcontentloaded') + + expectedUrl = new URL( + `http://localhost:${PORT}/relative/${navigation}/with-search?searchParam="2"`, + ) + + expect(page.url().toString()).toBe(expectedUrl.toString()) + + await expect( + page.getByTestId(`relative-${navigation}-withSearch-header`), + ).toContainText('searchParam: 2') + + await expect( + page.getByTestId(`relative-${navigation}-withSearch-header`), + ).toBeInViewport() + }) + + test(`shouldn't cause excessive rendering. navigation: ${navigation}`, async ({ + page, + }) => { + let navigateMsgs = 0 + + page.on('console', (msg) => { + if (msg.text() === 'navigate') { + navigateMsgs++ + } + }) + + await page.waitForLoadState('networkidle') + await page.goto(`/relative/${navigation}`) + await page.waitForURL(`http://localhost:${PORT}/relative/${navigation}`) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + expect(navigateMsgs).toBe(1) + const indexLink = page.getByTestId(`relative-${navigation}-index`) + const backLink = page.getByTestId(`relative-${navigation}-back`) + const relativeRouteA = page.getByTestId(`relative-${navigation}-a`) + const relativeRouteB = page.getByTestId(`relative-${navigation}-b`) + const deeplyNestedChildRoute = page.getByTestId( + `relative-${navigation}-deeply-nested`, + ) + const pathParamRoute = page.getByTestId(`relative-${navigation}-path`) + const searchParamRoute = page.getByTestId( + `relative-${navigation}-withSearch`, + ) + + await relativeRouteA.click() + await page.waitForLoadState('domcontentloaded') + await relativeRouteB.click() + await page.waitForLoadState('domcontentloaded') + await deeplyNestedChildRoute.click() + await page.waitForLoadState('domcontentloaded') + await backLink.click() + await page.waitForLoadState('domcontentloaded') + await pathParamRoute.click() + await page.waitForLoadState('domcontentloaded') + const switchParamLink = page.getByTestId( + `relative-${navigation}-path-param-switchAB`, + ) + await switchParamLink.click() + await page.waitForLoadState('domcontentloaded') + await searchParamRoute.click() + await page.waitForLoadState('domcontentloaded') + + const updateSearchLink = page.getByTestId( + `relative-${navigation}-withSearch-update-param`, + ) + + await updateSearchLink.click() + await page.waitForLoadState('domcontentloaded') + + await indexLink.click() + await page.waitForLoadState('domcontentloaded') + + expect(navigateMsgs).toBe(1) + }) + }) +}) diff --git a/e2e/react-router/basic-react-query-file-based/package.json b/e2e/react-router/basic-react-query-file-based/package.json index d19c42b64b..07f8813421 100644 --- a/e2e/react-router/basic-react-query-file-based/package.json +++ b/e2e/react-router/basic-react-query-file-based/package.json @@ -30,6 +30,6 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/e2e/react-router/basic-react-query/package.json b/e2e/react-router/basic-react-query/package.json index b1d3692705..e3e11f2383 100644 --- a/e2e/react-router/basic-react-query/package.json +++ b/e2e/react-router/basic-react-query/package.json @@ -28,6 +28,6 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/e2e/react-router/basic-scroll-restoration/package.json b/e2e/react-router/basic-scroll-restoration/package.json index dab75904e2..e84569ebb3 100644 --- a/e2e/react-router/basic-scroll-restoration/package.json +++ b/e2e/react-router/basic-scroll-restoration/package.json @@ -27,6 +27,6 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/e2e/react-router/basic-virtual-file-based/package.json b/e2e/react-router/basic-virtual-file-based/package.json index ccfaa1ff49..49e8a3fe1a 100644 --- a/e2e/react-router/basic-virtual-file-based/package.json +++ b/e2e/react-router/basic-virtual-file-based/package.json @@ -29,6 +29,6 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/e2e/react-router/basic-virtual-named-export-config-file-based/package.json b/e2e/react-router/basic-virtual-named-export-config-file-based/package.json index cc0549be9c..74d013545f 100644 --- a/e2e/react-router/basic-virtual-named-export-config-file-based/package.json +++ b/e2e/react-router/basic-virtual-named-export-config-file-based/package.json @@ -29,6 +29,6 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/e2e/react-router/basic/package.json b/e2e/react-router/basic/package.json index bf74680fad..0cb559c6b9 100644 --- a/e2e/react-router/basic/package.json +++ b/e2e/react-router/basic/package.json @@ -26,6 +26,6 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/e2e/react-router/generator-cli-only/package.json b/e2e/react-router/generator-cli-only/package.json index 10b802ae62..08f90293f3 100644 --- a/e2e/react-router/generator-cli-only/package.json +++ b/e2e/react-router/generator-cli-only/package.json @@ -27,6 +27,6 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/e2e/react-router/js-only-file-based/package.json b/e2e/react-router/js-only-file-based/package.json index f8881a588a..46a351989d 100644 --- a/e2e/react-router/js-only-file-based/package.json +++ b/e2e/react-router/js-only-file-based/package.json @@ -27,6 +27,6 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/package.json b/e2e/react-router/scroll-restoration-sandbox-vite/package.json index 1a28218b4f..8469b9a79c 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/react-router/scroll-restoration-sandbox-vite/package.json @@ -32,6 +32,6 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/e2e/react-router/sentry-integration/package.json b/e2e/react-router/sentry-integration/package.json index e653d74ffb..44fa594fa0 100644 --- a/e2e/react-router/sentry-integration/package.json +++ b/e2e/react-router/sentry-integration/package.json @@ -29,6 +29,6 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/e2e/react-router/sentry-integration/tests/app.spec.ts b/e2e/react-router/sentry-integration/tests/app.spec.ts index 9a3b53a966..1de2800c80 100644 --- a/e2e/react-router/sentry-integration/tests/app.spec.ts +++ b/e2e/react-router/sentry-integration/tests/app.spec.ts @@ -1,6 +1,5 @@ import { expect } from '@playwright/test' - -import { test } from './fixture' +import { test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-start/basic-auth/package.json b/e2e/react-start/basic-auth/package.json index f5ee14762e..4578e784a3 100644 --- a/e2e/react-start/basic-auth/package.json +++ b/e2e/react-start/basic-auth/package.json @@ -21,7 +21,7 @@ "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwind-merge": "^2.6.0", - "vite": "^6.3.5" + "vite": "^7.1.1" }, "devDependencies": { "@playwright/test": "^1.50.1", diff --git a/e2e/react-start/basic-auth/vite.config.ts b/e2e/react-start/basic-auth/vite.config.ts index 1df337cd40..dc57f144e4 100644 --- a/e2e/react-start/basic-auth/vite.config.ts +++ b/e2e/react-start/basic-auth/vite.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ plugins: [ @@ -8,5 +9,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/e2e/react-start/basic-react-query/package.json b/e2e/react-start/basic-react-query/package.json index 284e0626f7..ac0c200bd6 100644 --- a/e2e/react-start/basic-react-query/package.json +++ b/e2e/react-start/basic-react-query/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -21,7 +21,7 @@ "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwind-merge": "^2.6.0", - "vite": "^6.3.5" + "vite": "^7.1.1" }, "devDependencies": { "@playwright/test": "^1.50.1", @@ -32,6 +32,7 @@ "@vitejs/plugin-react": "^4.3.4", "autoprefixer": "^10.4.20", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", "vite-tsconfig-paths": "^5.1.4" diff --git a/e2e/react-start/basic-react-query/vite.config.ts b/e2e/react-start/basic-react-query/vite.config.ts index 1df337cd40..dc57f144e4 100644 --- a/e2e/react-start/basic-react-query/vite.config.ts +++ b/e2e/react-start/basic-react-query/vite.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ plugins: [ @@ -8,5 +9,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/e2e/react-start/basic-rsc/package.json b/e2e/react-start/basic-rsc/package.json index 9c820c9ccd..30ac070db2 100644 --- a/e2e/react-start/basic-rsc/package.json +++ b/e2e/react-start/basic-rsc/package.json @@ -17,7 +17,7 @@ "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwind-merge": "^2.6.0", - "vite": "^6.3.5" + "vite": "^7.1.1" }, "devDependencies": { "@types/react": "^19.0.8", diff --git a/e2e/react-start/basic-rsc/vite.config.ts b/e2e/react-start/basic-rsc/vite.config.ts index 1df337cd40..dc57f144e4 100644 --- a/e2e/react-start/basic-rsc/vite.config.ts +++ b/e2e/react-start/basic-rsc/vite.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ plugins: [ @@ -8,5 +9,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/e2e/react-start/basic-tsr-config/package.json b/e2e/react-start/basic-tsr-config/package.json index 6e36695183..a41ed7d467 100644 --- a/e2e/react-start/basic-tsr-config/package.json +++ b/e2e/react-start/basic-tsr-config/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "rimraf ./count.txt && vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -15,13 +15,14 @@ "@tanstack/react-start": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "vite": "^6.3.5" + "vite": "^7.1.1" }, "devDependencies": { "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", + "srvx": "^0.8.6", "typescript": "^5.7.2" } } diff --git a/e2e/react-start/basic-tsr-config/tests/app.spec.ts b/e2e/react-start/basic-tsr-config/tests/app.spec.ts index e3488df952..07a562fcb3 100644 --- a/e2e/react-start/basic-tsr-config/tests/app.spec.ts +++ b/e2e/react-start/basic-tsr-config/tests/app.spec.ts @@ -2,9 +2,14 @@ import { expect, test } from '@playwright/test' test('opening the app', async ({ page }) => { await page.goto('/') - - await expect(page.getByTestId('add-button')).toContainText('Add 1 to 0?') - await page.getByTestId('add-button').click() await page.waitForLoadState('networkidle') - await expect(page.getByTestId('add-button')).toContainText('Add 1 to 1?') + + const button = page.getByTestId('add-button') + + await expect(button).toContainText('Add 1 to 0?') + + await button.click() + await page.waitForLoadState('networkidle') + + await expect(button).toContainText('Add 1 to 1?') }) diff --git a/e2e/react-start/basic-tsr-config/vite.config.ts b/e2e/react-start/basic-tsr-config/vite.config.ts index 69045b5a44..92aabad3ba 100644 --- a/e2e/react-start/basic-tsr-config/vite.config.ts +++ b/e2e/react-start/basic-tsr-config/vite.config.ts @@ -7,9 +7,7 @@ export default defineConfig({ }, plugins: [ tanstackStart({ - tsr: { - srcDirectory: './src/app', - }, + srcDirectory: './src/app', }), ], }) diff --git a/e2e/react-start/basic/package.json b/e2e/react-start/basic/package.json index 57309b87a4..b3f2fe4b23 100644 --- a/e2e/react-start/basic/package.json +++ b/e2e/react-start/basic/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -17,9 +17,7 @@ "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", - "vite": "6.3.5", - "zod": "^3.24.2" + "tailwind-merge": "^2.6.0" }, "devDependencies": { "@playwright/test": "^1.50.1", @@ -31,8 +29,11 @@ "autoprefixer": "^10.4.20", "combinate": "^1.1.11", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite-tsconfig-paths": "^5.1.4" + "vite": "^7.1.1", + "vite-tsconfig-paths": "^5.1.4", + "zod": "^3.24.2" } } diff --git a/e2e/react-start/basic/src/server.ts b/e2e/react-start/basic/src/server.ts index 77cb4a1316..00d13b4d17 100644 --- a/e2e/react-start/basic/src/server.ts +++ b/e2e/react-start/basic/src/server.ts @@ -1,13 +1,11 @@ // DO NOT DELETE THIS FILE!!! // This file is a good smoke test to make sure the custom server entry is working -import { - createStartHandler, - defaultStreamHandler, -} from '@tanstack/react-start/server' -import { createRouter } from './router' +import handler from '@tanstack/react-start/server-entry' console.log("[server-entry]: using custom server entry in 'src/server.ts'") -export default createStartHandler({ - createRouter, -})(defaultStreamHandler) +export default { + fetch(request: Request) { + return handler.fetch(request) + }, +} diff --git a/e2e/react-start/basic/tests/fixture.ts b/e2e/react-start/basic/tests/fixture.ts deleted file mode 100644 index abb7b1d564..0000000000 --- a/e2e/react-start/basic/tests/fixture.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { test as base, expect } from '@playwright/test' - -export interface TestFixtureOptions { - whitelistErrors: Array -} -export const test = base.extend({ - whitelistErrors: [[], { option: true }], - page: async ({ page, whitelistErrors }, use) => { - const errorMessages: Array = [] - page.on('console', (m) => { - if (m.type() === 'error') { - const text = m.text() - for (const whitelistError of whitelistErrors) { - if ( - (typeof whitelistError === 'string' && - text.includes(whitelistError)) || - (whitelistError instanceof RegExp && whitelistError.test(text)) - ) { - return - } - } - errorMessages.push(text) - } - }) - await use(page) - expect(errorMessages).toEqual([]) - }, -}) diff --git a/e2e/react-start/basic/tests/navigation.spec.ts b/e2e/react-start/basic/tests/navigation.spec.ts index 5d21f2adbe..6ecc900716 100644 --- a/e2e/react-start/basic/tests/navigation.spec.ts +++ b/e2e/react-start/basic/tests/navigation.spec.ts @@ -1,5 +1,12 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' + +test.use({ + whitelistErrors: [ + /Failed to load resource: the server responded with a status of 404/, + ], +}) test('Navigating to post', async ({ page }) => { await page.goto('/') diff --git a/e2e/react-start/basic/tests/not-found.spec.ts b/e2e/react-start/basic/tests/not-found.spec.ts index 0d83ab5280..ab1c94eee9 100644 --- a/e2e/react-start/basic/tests/not-found.spec.ts +++ b/e2e/react-start/basic/tests/not-found.spec.ts @@ -1,6 +1,6 @@ import { expect } from '@playwright/test' import combinateImport from 'combinate' -import { test } from './fixture' +import { test } from '@tanstack/router-e2e-utils' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport diff --git a/e2e/react-start/basic/tests/params.spec.ts b/e2e/react-start/basic/tests/params.spec.ts index b22c3e2655..737c82f35d 100644 --- a/e2e/react-start/basic/tests/params.spec.ts +++ b/e2e/react-start/basic/tests/params.spec.ts @@ -1,9 +1,16 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' + +import { test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') }) +test.use({ + whitelistErrors: [ + /Failed to load resource: the server responded with a status of 404/, + ], +}) test.describe('Unicode route rendering', () => { test('should render non-latin route correctly', async ({ page, baseURL }) => { await page.goto('/대한민국') diff --git a/e2e/react-start/basic/tests/redirect.spec.ts b/e2e/react-start/basic/tests/redirect.spec.ts index 87e93a42e6..78c57d6a00 100644 --- a/e2e/react-start/basic/tests/redirect.spec.ts +++ b/e2e/react-start/basic/tests/redirect.spec.ts @@ -4,9 +4,9 @@ import combinateImport from 'combinate' import { getDummyServerPort, getTestServerPort, + test, } from '@tanstack/router-e2e-utils' import packageJson from '../package.json' with { type: 'json' } -import { test } from './fixture' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport @@ -184,6 +184,8 @@ test.describe('redirects', () => { await page.goto(`/redirect/${target}/serverFn/via-useServerFn?${q}`) + await page.waitForLoadState('networkidle') + const button = page.getByTestId('redirect-on-click') let fullPageLoad = false diff --git a/e2e/react-start/basic/tests/search-params.spec.ts b/e2e/react-start/basic/tests/search-params.spec.ts index 23cd97517d..d7ce617890 100644 --- a/e2e/react-start/basic/tests/search-params.spec.ts +++ b/e2e/react-start/basic/tests/search-params.spec.ts @@ -1,5 +1,5 @@ import { expect } from '@playwright/test' -import { test } from './fixture' +import { test } from '@tanstack/router-e2e-utils' import type { Response } from '@playwright/test' function expectRedirect(response: Response | null, endsWith: string) { diff --git a/e2e/react-start/basic/tests/streaming.spec.ts b/e2e/react-start/basic/tests/streaming.spec.ts index 252bb192aa..15f60b7deb 100644 --- a/e2e/react-start/basic/tests/streaming.spec.ts +++ b/e2e/react-start/basic/tests/streaming.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' test('Navigating to deferred route', async ({ page }) => { await page.goto('/') diff --git a/e2e/react-start/basic/vite.config.ts b/e2e/react-start/basic/vite.config.ts index 5443069826..4124c73694 100644 --- a/e2e/react-start/basic/vite.config.ts +++ b/e2e/react-start/basic/vite.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { @@ -10,6 +11,7 @@ export default defineConfig({ tsConfigPaths({ projects: ['./tsconfig.json'], }), - tanstackStart({ tsr: { verboseFileRoutes: false } }), + tanstackStart({ router: { verboseFileRoutes: false } }), + viteReact(), ], }) diff --git a/e2e/react-start/clerk-basic/package.disabled.json b/e2e/react-start/clerk-basic/package.disabled.json index d819677f46..43d26930a6 100644 --- a/e2e/react-start/clerk-basic/package.disabled.json +++ b/e2e/react-start/clerk-basic/package.disabled.json @@ -11,7 +11,7 @@ "test:e2e": "exit 0; rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { - "@clerk/tanstack-react-start": "^0.12.0", + "@clerk/tanstack-react-start": "^0.19.0", "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/react-start": "workspace:^", @@ -19,7 +19,7 @@ "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwind-merge": "^2.6.0", - "vite": "^6.3.5" + "vite": "^7.1.1" }, "devDependencies": { "@playwright/test": "^1.50.1", diff --git a/e2e/react-start/clerk-basic/src/routeTree.gen.ts b/e2e/react-start/clerk-basic/src/routeTree.gen.ts index 00f53c8623..8ac0e6e8c3 100644 --- a/e2e/react-start/clerk-basic/src/routeTree.gen.ts +++ b/e2e/react-start/clerk-basic/src/routeTree.gen.ts @@ -8,11 +8,7 @@ // You should NOT make any changes in this file as it will be overwritten. // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. -import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/react-router' - -// Import Routes - -import { Route as rootRoute } from './routes/__root' +import { Route as rootRouteImport } from './routes/__root' import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' @@ -20,151 +16,125 @@ import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.ind import { Route as AuthedProfileSplatRouteImport } from './routes/_authed/profile.$' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -// Create/Update Routes - const AuthedRoute = AuthedRouteImport.update({ id: '/_authed', - getParentRoute: () => rootRoute, + getParentRoute: () => rootRouteImport, } as any) - const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => rootRoute, + getParentRoute: () => rootRouteImport, } as any) - const AuthedPostsRoute = AuthedPostsRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => AuthedRoute, } as any) - const AuthedPostsIndexRoute = AuthedPostsIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => AuthedPostsRoute, } as any) - const AuthedProfileSplatRoute = AuthedProfileSplatRouteImport.update({ id: '/profile/$', path: '/profile/$', getParentRoute: () => AuthedRoute, } as any) - const AuthedPostsPostIdRoute = AuthedPostsPostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => AuthedPostsRoute, } as any) -// Populate the FileRoutesByPath interface +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/posts': typeof AuthedPostsRouteWithChildren + '/posts/$postId': typeof AuthedPostsPostIdRoute + '/profile/$': typeof AuthedProfileSplatRoute + '/posts/': typeof AuthedPostsIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/posts/$postId': typeof AuthedPostsPostIdRoute + '/profile/$': typeof AuthedProfileSplatRoute + '/posts': typeof AuthedPostsIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/_authed': typeof AuthedRouteWithChildren + '/_authed/posts': typeof AuthedPostsRouteWithChildren + '/_authed/posts/$postId': typeof AuthedPostsPostIdRoute + '/_authed/profile/$': typeof AuthedProfileSplatRoute + '/_authed/posts/': typeof AuthedPostsIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/posts' | '/posts/$postId' | '/profile/$' | '/posts/' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/posts/$postId' | '/profile/$' | '/posts' + id: + | '__root__' + | '/' + | '/_authed' + | '/_authed/posts' + | '/_authed/posts/$postId' + | '/_authed/profile/$' + | '/_authed/posts/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AuthedRoute: typeof AuthedRouteWithChildren +} declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRoute - } '/_authed': { id: '/_authed' path: '' fullPath: '' preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRoute + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/_authed/posts': { id: '/_authed/posts' path: '/posts' fullPath: '/posts' preLoaderRoute: typeof AuthedPostsRouteImport - parentRoute: typeof AuthedRouteImport - } - '/_authed/posts/$postId': { - id: '/_authed/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof AuthedPostsPostIdRouteImport - parentRoute: typeof AuthedPostsRouteImport - } - '/_authed/profile/$': { - id: '/_authed/profile/$' - path: '/profile/$' - fullPath: '/profile/$' - preLoaderRoute: typeof AuthedProfileSplatRouteImport - parentRoute: typeof AuthedRouteImport + parentRoute: typeof AuthedRoute } '/_authed/posts/': { id: '/_authed/posts/' path: '/' fullPath: '/posts/' preLoaderRoute: typeof AuthedPostsIndexRouteImport - parentRoute: typeof AuthedPostsRouteImport + parentRoute: typeof AuthedPostsRoute + } + '/_authed/profile/$': { + id: '/_authed/profile/$' + path: '/profile/$' + fullPath: '/profile/$' + preLoaderRoute: typeof AuthedProfileSplatRouteImport + parentRoute: typeof AuthedRoute + } + '/_authed/posts/$postId': { + id: '/_authed/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof AuthedPostsPostIdRouteImport + parentRoute: typeof AuthedPostsRoute } } } -// Add type-safety to the createFileRoute function across the route tree - -declare module './routes/index' { - const createFileRoute: CreateFileRoute< - '/', - FileRoutesByPath['/']['parentRoute'], - FileRoutesByPath['/']['id'], - FileRoutesByPath['/']['path'], - FileRoutesByPath['/']['fullPath'] - > -} -declare module './routes/_authed' { - const createFileRoute: CreateFileRoute< - '/_authed', - FileRoutesByPath['/_authed']['parentRoute'], - FileRoutesByPath['/_authed']['id'], - FileRoutesByPath['/_authed']['path'], - FileRoutesByPath['/_authed']['fullPath'] - > -} -declare module './routes/_authed/posts' { - const createFileRoute: CreateFileRoute< - '/_authed/posts', - FileRoutesByPath['/_authed/posts']['parentRoute'], - FileRoutesByPath['/_authed/posts']['id'], - FileRoutesByPath['/_authed/posts']['path'], - FileRoutesByPath['/_authed/posts']['fullPath'] - > -} -declare module './routes/_authed/posts.$postId' { - const createFileRoute: CreateFileRoute< - '/_authed/posts/$postId', - FileRoutesByPath['/_authed/posts/$postId']['parentRoute'], - FileRoutesByPath['/_authed/posts/$postId']['id'], - FileRoutesByPath['/_authed/posts/$postId']['path'], - FileRoutesByPath['/_authed/posts/$postId']['fullPath'] - > -} -declare module './routes/_authed/profile.$' { - const createFileRoute: CreateFileRoute< - '/_authed/profile/$', - FileRoutesByPath['/_authed/profile/$']['parentRoute'], - FileRoutesByPath['/_authed/profile/$']['id'], - FileRoutesByPath['/_authed/profile/$']['path'], - FileRoutesByPath['/_authed/profile/$']['fullPath'] - > -} -declare module './routes/_authed/posts.index' { - const createFileRoute: CreateFileRoute< - '/_authed/posts/', - FileRoutesByPath['/_authed/posts/']['parentRoute'], - FileRoutesByPath['/_authed/posts/']['id'], - FileRoutesByPath['/_authed/posts/']['path'], - FileRoutesByPath['/_authed/posts/']['fullPath'] - > -} - -// Create and export the route tree - interface AuthedPostsRouteChildren { AuthedPostsPostIdRoute: typeof AuthedPostsPostIdRoute AuthedPostsIndexRoute: typeof AuthedPostsIndexRoute @@ -192,103 +162,10 @@ const AuthedRouteChildren: AuthedRouteChildren = { const AuthedRouteWithChildren = AuthedRoute._addFileChildren(AuthedRouteChildren) -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '': typeof AuthedRouteWithChildren - '/posts': typeof AuthedPostsRouteWithChildren - '/posts/$postId': typeof AuthedPostsPostIdRoute - '/profile/$': typeof AuthedProfileSplatRoute - '/posts/': typeof AuthedPostsIndexRoute -} - -export interface FileRoutesByTo { - '/': typeof IndexRoute - '': typeof AuthedRouteWithChildren - '/posts/$postId': typeof AuthedPostsPostIdRoute - '/profile/$': typeof AuthedProfileSplatRoute - '/posts': typeof AuthedPostsIndexRoute -} - -export interface FileRoutesById { - __root__: typeof rootRoute - '/': typeof IndexRoute - '/_authed': typeof AuthedRouteWithChildren - '/_authed/posts': typeof AuthedPostsRouteWithChildren - '/_authed/posts/$postId': typeof AuthedPostsPostIdRoute - '/_authed/profile/$': typeof AuthedProfileSplatRoute - '/_authed/posts/': typeof AuthedPostsIndexRoute -} - -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '' | '/posts' | '/posts/$postId' | '/profile/$' | '/posts/' - fileRoutesByTo: FileRoutesByTo - to: '/' | '' | '/posts/$postId' | '/profile/$' | '/posts' - id: - | '__root__' - | '/' - | '/_authed' - | '/_authed/posts' - | '/_authed/posts/$postId' - | '/_authed/profile/$' - | '/_authed/posts/' - fileRoutesById: FileRoutesById -} - -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AuthedRoute: typeof AuthedRouteWithChildren -} - const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, AuthedRoute: AuthedRouteWithChildren, } - -export const routeTree = rootRoute +export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) ._addFileTypes() - -/* ROUTE_MANIFEST_START -{ - "routes": { - "__root__": { - "filePath": "__root.tsx", - "children": [ - "/", - "/_authed" - ] - }, - "/": { - "filePath": "index.tsx" - }, - "/_authed": { - "filePath": "_authed.tsx", - "children": [ - "/_authed/posts", - "/_authed/profile/$" - ] - }, - "/_authed/posts": { - "filePath": "_authed/posts.tsx", - "parent": "/_authed", - "children": [ - "/_authed/posts/$postId", - "/_authed/posts/" - ] - }, - "/_authed/posts/$postId": { - "filePath": "_authed/posts.$postId.tsx", - "parent": "/_authed/posts" - }, - "/_authed/profile/$": { - "filePath": "_authed/profile.$.tsx", - "parent": "/_authed" - }, - "/_authed/posts/": { - "filePath": "_authed/posts.index.tsx", - "parent": "/_authed/posts" - } - } -} -ROUTE_MANIFEST_END */ diff --git a/e2e/react-start/clerk-basic/src/routes/__root.tsx b/e2e/react-start/clerk-basic/src/routes/__root.tsx index 51f8705b28..f2a475c95f 100644 --- a/e2e/react-start/clerk-basic/src/routes/__root.tsx +++ b/e2e/react-start/clerk-basic/src/routes/__root.tsx @@ -17,13 +17,13 @@ import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' import { createServerFn } from '@tanstack/react-start' import * as React from 'react' import { getAuth } from '@clerk/tanstack-react-start/server' -import { getWebRequest } from '@tanstack/react-start/server' +import { getRequest } from '@tanstack/react-start/server' import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' const fetchClerkAuth = createServerFn({ method: 'GET' }).handler(async () => { - const user = await getAuth(getWebRequest()!) + const user = await getAuth(getRequest()!) return { user, diff --git a/e2e/react-start/clerk-basic/src/routes/_authed.tsx b/e2e/react-start/clerk-basic/src/routes/_authed.tsx index 6242975272..226ae0829f 100644 --- a/e2e/react-start/clerk-basic/src/routes/_authed.tsx +++ b/e2e/react-start/clerk-basic/src/routes/_authed.tsx @@ -1,6 +1,7 @@ +import { createFileRoute } from '@tanstack/react-router' import { SignIn } from '@clerk/tanstack-react-start' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_authed')({ beforeLoad: ({ context }) => { if (!context.user.userId) { throw new Error('Not authenticated') diff --git a/e2e/react-start/clerk-basic/src/routes/_authed/posts.$postId.tsx b/e2e/react-start/clerk-basic/src/routes/_authed/posts.$postId.tsx index 49cad9b374..27296b9658 100644 --- a/e2e/react-start/clerk-basic/src/routes/_authed/posts.$postId.tsx +++ b/e2e/react-start/clerk-basic/src/routes/_authed/posts.$postId.tsx @@ -1,10 +1,10 @@ -import { ErrorComponent } from '@tanstack/react-router' +import { ErrorComponent, createFileRoute } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' import { NotFound } from '~/components/NotFound.js' import { fetchPost } from '~/utils/posts.js' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_authed/posts/$postId')({ loader: ({ params: { postId } }) => fetchPost({ data: postId }), errorComponent: PostErrorComponent, component: PostComponent, diff --git a/e2e/react-start/clerk-basic/src/routes/_authed/posts.index.tsx b/e2e/react-start/clerk-basic/src/routes/_authed/posts.index.tsx index 13529228bb..de01fe5dde 100644 --- a/e2e/react-start/clerk-basic/src/routes/_authed/posts.index.tsx +++ b/e2e/react-start/clerk-basic/src/routes/_authed/posts.index.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/_authed/posts/')({ component: PostsIndexComponent, }) diff --git a/e2e/react-start/clerk-basic/src/routes/_authed/posts.tsx b/e2e/react-start/clerk-basic/src/routes/_authed/posts.tsx index 6c37957e8c..c01f12c49a 100644 --- a/e2e/react-start/clerk-basic/src/routes/_authed/posts.tsx +++ b/e2e/react-start/clerk-basic/src/routes/_authed/posts.tsx @@ -1,8 +1,8 @@ -import { Link, Outlet } from '@tanstack/react-router' +import { Link, Outlet, createFileRoute } from '@tanstack/react-router' import { fetchPosts } from '~/utils/posts.js' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_authed/posts')({ loader: () => fetchPosts(), component: PostsComponent, }) diff --git a/e2e/react-start/clerk-basic/src/routes/_authed/profile.$.tsx b/e2e/react-start/clerk-basic/src/routes/_authed/profile.$.tsx index 6c37957e8c..1e5a8b1429 100644 --- a/e2e/react-start/clerk-basic/src/routes/_authed/profile.$.tsx +++ b/e2e/react-start/clerk-basic/src/routes/_authed/profile.$.tsx @@ -1,8 +1,8 @@ -import { Link, Outlet } from '@tanstack/react-router' +import { Link, Outlet, createFileRoute } from '@tanstack/react-router' import { fetchPosts } from '~/utils/posts.js' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_authed/profile/$')({ loader: () => fetchPosts(), component: PostsComponent, }) diff --git a/e2e/react-start/clerk-basic/src/routes/index.tsx b/e2e/react-start/clerk-basic/src/routes/index.tsx index 66baf1e9f1..00ce18725b 100644 --- a/e2e/react-start/clerk-basic/src/routes/index.tsx +++ b/e2e/react-start/clerk-basic/src/routes/index.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/')({ component: Home, }) diff --git a/e2e/react-start/clerk-basic/src/server.ts b/e2e/react-start/clerk-basic/src/server.ts new file mode 100644 index 0000000000..39afb5c85f --- /dev/null +++ b/e2e/react-start/clerk-basic/src/server.ts @@ -0,0 +1,15 @@ +import { + createStartHandler, + defaultStreamHandler, +} from '@tanstack/react-start/server' +import { createClerkHandler } from '@clerk/tanstack-react-start/server' +import { createRouter } from './router' + +const startHandler = createStartHandler({ + createRouter, +}) +const fetch = createClerkHandler(startHandler)(defaultStreamHandler) + +export default { + fetch, +} diff --git a/e2e/react-start/clerk-basic/src/server.tsx b/e2e/react-start/clerk-basic/src/server.tsx deleted file mode 100644 index 2987216e24..0000000000 --- a/e2e/react-start/clerk-basic/src/server.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { - createStartHandler, - defaultStreamHandler, - defineEventHandler, -} from '@tanstack/react-start/server' -import { createClerkHandler } from '@clerk/tanstack-react-start/server' -import { createRouter } from './router' - -export default defineEventHandler((event) => { - const startHandler = createStartHandler({ - createRouter, - }) - - const withClerkHandler = - createClerkHandler(startHandler)(defaultStreamHandler) - - return withClerkHandler(event) -}) diff --git a/e2e/react-start/clerk-basic/vite.config.ts b/e2e/react-start/clerk-basic/vite.config.ts index 1df337cd40..dc57f144e4 100644 --- a/e2e/react-start/clerk-basic/vite.config.ts +++ b/e2e/react-start/clerk-basic/vite.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ plugins: [ @@ -8,5 +9,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/e2e/react-start/custom-basepath/express-server.ts b/e2e/react-start/custom-basepath/express-server.ts new file mode 100644 index 0000000000..6fa802e447 --- /dev/null +++ b/e2e/react-start/custom-basepath/express-server.ts @@ -0,0 +1,44 @@ +import express from 'express' +import { toNodeHandler } from 'srvx/node' + +const DEVELOPMENT = process.env.NODE_ENV === 'development' +const PORT = Number.parseInt(process.env.PORT || '3000') + +const app = express() + +if (DEVELOPMENT) { + const viteDevServer = await import('vite').then((vite) => + vite.createServer({ + server: { middlewareMode: true }, + }), + ) + app.use(viteDevServer.middlewares) + app.use(async (req, res, next) => { + try { + const { default: serverEntry } = + await viteDevServer.ssrLoadModule('./src/server.ts') + const handler = toNodeHandler(serverEntry.fetch) + await handler(req, res) + } catch (error) { + if (typeof error === 'object' && error instanceof Error) { + viteDevServer.ssrFixStacktrace(error) + } + next(error) + } + }) +} else { + const { default: handler } = await import('./dist/server/server.js') + const nodeHandler = toNodeHandler(handler.fetch) + app.use('/custom/basepath', express.static('dist/client')) + app.use(async (req, res, next) => { + try { + await nodeHandler(req, res) + } catch (error) { + next(error) + } + }) +} + +app.listen(PORT, () => { + console.log(`Server is running on http://localhost:${PORT}`) +}) diff --git a/e2e/react-start/custom-basepath/package.json b/e2e/react-start/custom-basepath/package.json index ef1a13b2c6..9a89b00d26 100644 --- a/e2e/react-start/custom-basepath/package.json +++ b/e2e/react-start/custom-basepath/package.json @@ -4,35 +4,36 @@ "sideEffects": false, "type": "module", "scripts": { - "dev": "vite dev --port 3000", - "dev:e2e": "vite dev", + "dev": "cross-env NODE_ENV=development tsx express-server.ts", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "tsx express-server.ts", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/react-start": "workspace:^", + "express": "^4.21.2", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", - "vite": "6.3.5", - "zod": "^3.24.2" + "redaxios": "^0.5.1" }, "devDependencies": { "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", + "@types/express": "^5.0.3", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "autoprefixer": "^10.4.20", - "combinate": "^1.1.11", + "cross-env": "^10.0.0", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", + "tsx": "^4.20.3", "typescript": "^5.7.2", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/react-start/custom-basepath/src/server.ts b/e2e/react-start/custom-basepath/src/server.ts new file mode 100644 index 0000000000..1d97780586 --- /dev/null +++ b/e2e/react-start/custom-basepath/src/server.ts @@ -0,0 +1,14 @@ +import { + createStartHandler, + defaultStreamHandler, +} from '@tanstack/react-start/server' + +import { createRouter } from './router' + +const fetch = createStartHandler({ + createRouter, +})(defaultStreamHandler) + +export default { + fetch, +} diff --git a/e2e/react-start/custom-basepath/vite.config.ts b/e2e/react-start/custom-basepath/vite.config.ts index c304ad647b..7e200dc074 100644 --- a/e2e/react-start/custom-basepath/vite.config.ts +++ b/e2e/react-start/custom-basepath/vite.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ base: '/custom/basepath', @@ -11,6 +12,9 @@ export default defineConfig({ tsConfigPaths({ projects: ['./tsconfig.json'], }), - tanstackStart(), + tanstackStart({ + vite: { installDevServerMiddleware: true }, + }), + viteReact(), ], }) diff --git a/e2e/react-start/query-integration/package.json b/e2e/react-start/query-integration/package.json index 7916c849f6..34080d78bf 100644 --- a/e2e/react-start/query-integration/package.json +++ b/e2e/react-start/query-integration/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { diff --git a/e2e/react-start/query-integration/tests/app.spec.ts b/e2e/react-start/query-integration/tests/app.spec.ts index 5c78722d20..b55f0db801 100644 --- a/e2e/react-start/query-integration/tests/app.spec.ts +++ b/e2e/react-start/query-integration/tests/app.spec.ts @@ -1,5 +1,5 @@ import { expect } from '@playwright/test' -import { test } from './fixture' +import { test } from '@tanstack/router-e2e-utils' // if the query would not be streamed to the client, it would re-execute on the client // and thus cause a hydration mismatch since the query function returns 'client' when executed on the client diff --git a/e2e/react-start/query-integration/tests/fixture.ts b/e2e/react-start/query-integration/tests/fixture.ts deleted file mode 100644 index abb7b1d564..0000000000 --- a/e2e/react-start/query-integration/tests/fixture.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { test as base, expect } from '@playwright/test' - -export interface TestFixtureOptions { - whitelistErrors: Array -} -export const test = base.extend({ - whitelistErrors: [[], { option: true }], - page: async ({ page, whitelistErrors }, use) => { - const errorMessages: Array = [] - page.on('console', (m) => { - if (m.type() === 'error') { - const text = m.text() - for (const whitelistError of whitelistErrors) { - if ( - (typeof whitelistError === 'string' && - text.includes(whitelistError)) || - (whitelistError instanceof RegExp && whitelistError.test(text)) - ) { - return - } - } - errorMessages.push(text) - } - }) - await use(page) - expect(errorMessages).toEqual([]) - }, -}) diff --git a/e2e/react-start/scroll-restoration/package.json b/e2e/react-start/scroll-restoration/package.json index 6f9393c929..f4b18512c1 100644 --- a/e2e/react-start/scroll-restoration/package.json +++ b/e2e/react-start/scroll-restoration/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -19,7 +19,7 @@ "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwind-merge": "^2.6.0", - "vite": "^6.3.5", + "vite": "^7.1.1", "zod": "^3.24.2" }, "devDependencies": { @@ -32,6 +32,7 @@ "autoprefixer": "^10.4.20", "combinate": "^1.1.11", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", "vite-tsconfig-paths": "^5.1.4" diff --git a/e2e/react-start/scroll-restoration/vite.config.ts b/e2e/react-start/scroll-restoration/vite.config.ts index 5b91efb751..33948491fe 100644 --- a/e2e/react-start/scroll-restoration/vite.config.ts +++ b/e2e/react-start/scroll-restoration/vite.config.ts @@ -1,7 +1,12 @@ import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ - plugins: [tsConfigPaths({ projects: ['./tsconfig.json'] }), tanstackStart()], + plugins: [ + tsConfigPaths({ projects: ['./tsconfig.json'] }), + tanstackStart(), + viteReact(), + ], }) diff --git a/e2e/react-start/selective-ssr/package.json b/e2e/react-start/selective-ssr/package.json index 995641c88f..f7f29a329f 100644 --- a/e2e/react-start/selective-ssr/package.json +++ b/e2e/react-start/selective-ssr/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -16,16 +16,18 @@ "@tanstack/react-start": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4", "zod": "^3.24.2" }, "devDependencies": { "@tanstack/router-e2e-utils": "workspace:^", + "@vitejs/plugin-react": "^4.3.4", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", "typescript": "^5.7.2" } diff --git a/e2e/react-start/selective-ssr/tests/app.spec.ts b/e2e/react-start/selective-ssr/tests/app.spec.ts index b013dfb169..aea216d506 100644 --- a/e2e/react-start/selective-ssr/tests/app.spec.ts +++ b/e2e/react-start/selective-ssr/tests/app.spec.ts @@ -1,5 +1,5 @@ import { expect } from '@playwright/test' -import { test } from './fixture' +import { test } from '@tanstack/router-e2e-utils' const testCount = 7 diff --git a/e2e/react-start/selective-ssr/tests/fixture.ts b/e2e/react-start/selective-ssr/tests/fixture.ts deleted file mode 100644 index abb7b1d564..0000000000 --- a/e2e/react-start/selective-ssr/tests/fixture.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { test as base, expect } from '@playwright/test' - -export interface TestFixtureOptions { - whitelistErrors: Array -} -export const test = base.extend({ - whitelistErrors: [[], { option: true }], - page: async ({ page, whitelistErrors }, use) => { - const errorMessages: Array = [] - page.on('console', (m) => { - if (m.type() === 'error') { - const text = m.text() - for (const whitelistError of whitelistErrors) { - if ( - (typeof whitelistError === 'string' && - text.includes(whitelistError)) || - (whitelistError instanceof RegExp && whitelistError.test(text)) - ) { - return - } - } - errorMessages.push(text) - } - }) - await use(page) - expect(errorMessages).toEqual([]) - }, -}) diff --git a/e2e/react-start/selective-ssr/vite.config.ts b/e2e/react-start/selective-ssr/vite.config.ts index c3b722c89b..04033010e8 100644 --- a/e2e/react-start/selective-ssr/vite.config.ts +++ b/e2e/react-start/selective-ssr/vite.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from 'vite' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import tsConfigPaths from 'vite-tsconfig-paths' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/e2e/react-start/serialization-adapters/.gitignore b/e2e/react-start/serialization-adapters/.gitignore new file mode 100644 index 0000000000..08eba9e706 --- /dev/null +++ b/e2e/react-start/serialization-adapters/.gitignore @@ -0,0 +1,20 @@ +node_modules +package-lock.json +yarn.lock + +.DS_Store +.cache +.env +.vercel +.output +/build/ +/api/ +/server/build +/public/build# Sentry Config File +.env.sentry-build-plugin +/test-results/ +/playwright-report/ +/blob-report/ +/playwright/.cache/ + +count.txt diff --git a/e2e/react-start/serialization-adapters/.prettierignore b/e2e/react-start/serialization-adapters/.prettierignore new file mode 100644 index 0000000000..2be5eaa6ec --- /dev/null +++ b/e2e/react-start/serialization-adapters/.prettierignore @@ -0,0 +1,4 @@ +**/build +**/public +pnpm-lock.yaml +routeTree.gen.ts \ No newline at end of file diff --git a/e2e/react-start/serialization-adapters/package.json b/e2e/react-start/serialization-adapters/package.json new file mode 100644 index 0000000000..bb66301e8d --- /dev/null +++ b/e2e/react-start/serialization-adapters/package.json @@ -0,0 +1,34 @@ +{ + "name": "tanstack-react-start-e2e-serialization-adapters", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "dev": "vite dev --port 3000", + "dev:e2e": "vite dev", + "build": "vite build && tsc --noEmit", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "@tanstack/react-router-devtools": "workspace:^", + "@tanstack/react-start": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "vite": "^7.1.1", + "vite-tsconfig-paths": "^5.1.4", + "zod": "^3.24.2" + }, + "devDependencies": { + "@tanstack/router-e2e-utils": "workspace:^", + "@vitejs/plugin-react": "^4.3.4", + "@types/node": "^22.10.2", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "postcss": "^8.5.1", + "srvx": "^0.8.6", + "tailwindcss": "^3.4.17", + "typescript": "^5.7.2" + } +} diff --git a/e2e/react-start/serialization-adapters/playwright.config.ts b/e2e/react-start/serialization-adapters/playwright.config.ts new file mode 100644 index 0000000000..badd6db0eb --- /dev/null +++ b/e2e/react-start/serialization-adapters/playwright.config.ts @@ -0,0 +1,34 @@ +import { defineConfig, devices } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } + +const PORT = await getTestServerPort(packageJson.name) +const baseURL = `http://localhost:${PORT}` +/** + * See https://playwright.dev/docs/test-configuration. + */ +export default defineConfig({ + testDir: './tests', + workers: 1, + + reporter: [['line']], + + use: { + /* Base URL to use in actions like `await page.goto('/')`. */ + baseURL, + }, + + webServer: { + command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, + stdout: 'pipe', + }, + + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-start/serialization-adapters/postcss.config.mjs b/e2e/react-start/serialization-adapters/postcss.config.mjs new file mode 100644 index 0000000000..2e7af2b7f1 --- /dev/null +++ b/e2e/react-start/serialization-adapters/postcss.config.mjs @@ -0,0 +1,6 @@ +export default { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +} diff --git a/e2e/react-start/serialization-adapters/src/CustomError.ts b/e2e/react-start/serialization-adapters/src/CustomError.ts new file mode 100644 index 0000000000..9fcf85b36f --- /dev/null +++ b/e2e/react-start/serialization-adapters/src/CustomError.ts @@ -0,0 +1,31 @@ +import { createSerializationAdapter } from '@tanstack/react-router' + +export class CustomError extends Error { + public foo: string + public bar: bigint + + constructor(message: string, options: { foo: string; bar: bigint }) { + super(message) + + Object.setPrototypeOf(this, new.target.prototype) + + this.name = this.constructor.name + this.foo = options.foo + this.bar = options.bar + } +} + +export const customErrorAdapter = createSerializationAdapter({ + key: 'custom-error', + test: (v) => v instanceof CustomError, + toSerializable: ({ message, foo, bar }) => { + return { + message, + foo, + bar, + } + }, + fromSerializable: ({ message, foo, bar }) => { + return new CustomError(message, { foo, bar }) + }, +}) diff --git a/e2e/react-start/serialization-adapters/src/data.tsx b/e2e/react-start/serialization-adapters/src/data.tsx new file mode 100644 index 0000000000..ea1922fedc --- /dev/null +++ b/e2e/react-start/serialization-adapters/src/data.tsx @@ -0,0 +1,127 @@ +import { createSerializationAdapter } from '@tanstack/react-router' + +export class Foo { + constructor(public value: string) {} +} + +export interface Car { + __type: 'car' + make: string + model: string + year: number + honk: () => { message: string; make: string; model: string; year: number } +} + +export function makeCar(opts: { + make: string + model: string + year: number +}): Car { + return { + ...opts, + __type: 'car', + honk: () => { + return { message: `Honk! Honk!`, ...opts } + }, + } +} + +export const fooAdapter = createSerializationAdapter({ + key: 'foo', + test: (value: any) => value instanceof Foo, + toSerializable: (foo) => foo.value, + fromSerializable: (value) => new Foo(value), +}) + +export const carAdapter = createSerializationAdapter({ + key: 'car', + test: (value: any): value is Car => + '__type' in (value as Car) && value.__type === 'car', + toSerializable: (car) => ({ + make: car.make, + model: car.model, + year: car.year, + }), + fromSerializable: (value: { make: string; model: string; year: number }) => + makeCar(value), +}) + +export function makeData() { + function makeFoo(suffix: string = '') { + return new Foo(typeof window === 'undefined' ? 'server' : 'client' + suffix) + } + return { + foo: { + singleInstance: makeFoo(), + array: [makeFoo('0'), makeFoo('1'), makeFoo('2')], + map: new Map([ + [0, makeFoo('0')], + [1, makeFoo('1')], + [2, makeFoo('2')], + ]), + mapOfArrays: new Map([ + [0, [makeFoo('0-a'), makeFoo('0-b')]], + [1, [makeFoo('1-a'), makeFoo('1-b')]], + [2, [makeFoo('2-a'), makeFoo('2-b')]], + ]), + }, + car: { + singleInstance: makeCar({ + make: 'Toyota', + model: 'Camry', + year: 2020, + }), + array: [ + makeCar({ make: 'Honda', model: 'Accord', year: 2019 }), + makeCar({ make: 'Ford', model: 'Mustang', year: 2021 }), + ], + map: new Map([ + [0, makeCar({ make: 'Chevrolet', model: 'Malibu', year: 2018 })], + [1, makeCar({ make: 'Nissan', model: 'Altima', year: 2020 })], + [2, makeCar({ make: 'Hyundai', model: 'Sonata', year: 2021 })], + ]), + mapOfArrays: new Map([ + [0, [makeCar({ make: 'Kia', model: 'Optima', year: 2019 })]], + [1, [makeCar({ make: 'Subaru', model: 'Legacy', year: 2020 })]], + [2, [makeCar({ make: 'Volkswagen', model: 'Passat', year: 2021 })]], + ]), + }, + } +} + +export function RenderData({ + id, + data, +}: { + id: string + data: ReturnType +}) { + const localData = makeData() + return ( +
+

Car

+

expected

+
+ {JSON.stringify({ + make: localData.car.singleInstance.make, + model: localData.car.singleInstance.model, + year: localData.car.singleInstance.year, + })} +
+

actual

+
+ {JSON.stringify({ + make: data.car.singleInstance.make, + model: data.car.singleInstance.model, + year: data.car.singleInstance.year, + })} +
+ Foo +
+ {JSON.stringify({ + value: data.foo.singleInstance.value, + })} +
+
+ ) +} diff --git a/e2e/react-start/serialization-adapters/src/routeTree.gen.ts b/e2e/react-start/serialization-adapters/src/routeTree.gen.ts new file mode 100644 index 0000000000..872003fb09 --- /dev/null +++ b/e2e/react-start/serialization-adapters/src/routeTree.gen.ts @@ -0,0 +1,123 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as SsrStreamRouteImport } from './routes/ssr/stream' +import { Route as SsrDataOnlyRouteImport } from './routes/ssr/data-only' +import { Route as ServerFunctionCustomErrorRouteImport } from './routes/server-function/custom-error' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const SsrStreamRoute = SsrStreamRouteImport.update({ + id: '/ssr/stream', + path: '/ssr/stream', + getParentRoute: () => rootRouteImport, +} as any) +const SsrDataOnlyRoute = SsrDataOnlyRouteImport.update({ + id: '/ssr/data-only', + path: '/ssr/data-only', + getParentRoute: () => rootRouteImport, +} as any) +const ServerFunctionCustomErrorRoute = + ServerFunctionCustomErrorRouteImport.update({ + id: '/server-function/custom-error', + path: '/server-function/custom-error', + getParentRoute: () => rootRouteImport, + } as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/server-function/custom-error': typeof ServerFunctionCustomErrorRoute + '/ssr/data-only': typeof SsrDataOnlyRoute + '/ssr/stream': typeof SsrStreamRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/server-function/custom-error': typeof ServerFunctionCustomErrorRoute + '/ssr/data-only': typeof SsrDataOnlyRoute + '/ssr/stream': typeof SsrStreamRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/server-function/custom-error': typeof ServerFunctionCustomErrorRoute + '/ssr/data-only': typeof SsrDataOnlyRoute + '/ssr/stream': typeof SsrStreamRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/server-function/custom-error' + | '/ssr/data-only' + | '/ssr/stream' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/server-function/custom-error' | '/ssr/data-only' | '/ssr/stream' + id: + | '__root__' + | '/' + | '/server-function/custom-error' + | '/ssr/data-only' + | '/ssr/stream' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ServerFunctionCustomErrorRoute: typeof ServerFunctionCustomErrorRoute + SsrDataOnlyRoute: typeof SsrDataOnlyRoute + SsrStreamRoute: typeof SsrStreamRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/ssr/stream': { + id: '/ssr/stream' + path: '/ssr/stream' + fullPath: '/ssr/stream' + preLoaderRoute: typeof SsrStreamRouteImport + parentRoute: typeof rootRouteImport + } + '/ssr/data-only': { + id: '/ssr/data-only' + path: '/ssr/data-only' + fullPath: '/ssr/data-only' + preLoaderRoute: typeof SsrDataOnlyRouteImport + parentRoute: typeof rootRouteImport + } + '/server-function/custom-error': { + id: '/server-function/custom-error' + path: '/server-function/custom-error' + fullPath: '/server-function/custom-error' + preLoaderRoute: typeof ServerFunctionCustomErrorRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ServerFunctionCustomErrorRoute: ServerFunctionCustomErrorRoute, + SsrDataOnlyRoute: SsrDataOnlyRoute, + SsrStreamRoute: SsrStreamRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/e2e/react-start/serialization-adapters/src/router.tsx b/e2e/react-start/serialization-adapters/src/router.tsx new file mode 100644 index 0000000000..04154bc28f --- /dev/null +++ b/e2e/react-start/serialization-adapters/src/router.tsx @@ -0,0 +1,28 @@ +import { + createRouterConfig, + createRouter as createTanStackRouter, +} from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +import { carAdapter, fooAdapter } from './data' +import { customErrorAdapter } from './CustomError' + +const config = createRouterConfig({ + serializationAdapters: [fooAdapter, carAdapter, customErrorAdapter], +}) + +export function createRouter() { + const router = createTanStackRouter({ + ...config, + routeTree, + scrollRestoration: true, + }) + + return router +} + +declare module '@tanstack/react-router' { + interface Register { + config: typeof config + router: ReturnType + } +} diff --git a/e2e/react-start/serialization-adapters/src/routes/__root.tsx b/e2e/react-start/serialization-adapters/src/routes/__root.tsx new file mode 100644 index 0000000000..2f30dfa3f1 --- /dev/null +++ b/e2e/react-start/serialization-adapters/src/routes/__root.tsx @@ -0,0 +1,72 @@ +/// +import * as React from 'react' +import { + ClientOnly, + HeadContent, + Link, + Scripts, + createRootRoute, + useRouterState, +} from '@tanstack/react-router' +import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' +import appCss from '~/styles/app.css?url' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { + charSet: 'utf-8', + }, + { + name: 'viewport', + content: 'width=device-width, initial-scale=1', + }, + { + title: 'Serialization Adapters E2E Test', + }, + ], + links: [{ rel: 'stylesheet', href: appCss }], + }), + shellComponent: RootDocument, +}) + +function RootDocument({ children }: { children: React.ReactNode }) { + const { isLoading, status } = useRouterState({ + select: (state) => ({ isLoading: state.isLoading, status: state.status }), + structuralSharing: true, + }) + return ( + + + + + +
+

Serialization Adapters E2E Test

+ + Home + +
+
+ +
+ router isLoading:{' '} + {isLoading ? 'true' : 'false'} +
+
+ router status: {status} +
+
+
+ {children} + + + + + ) +} diff --git a/e2e/react-start/serialization-adapters/src/routes/index.tsx b/e2e/react-start/serialization-adapters/src/routes/index.tsx new file mode 100644 index 0000000000..0c39c4d020 --- /dev/null +++ b/e2e/react-start/serialization-adapters/src/routes/index.tsx @@ -0,0 +1,40 @@ +import { Link, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return ( + <> +
+

SSR

+ + Data Only + +
+ + Stream + +
+
+

Server Functions

+ + Custom Error Serialization + +
+ + ) +} diff --git a/e2e/react-start/serialization-adapters/src/routes/server-function/custom-error.tsx b/e2e/react-start/serialization-adapters/src/routes/server-function/custom-error.tsx new file mode 100644 index 0000000000..784181ee5a --- /dev/null +++ b/e2e/react-start/serialization-adapters/src/routes/server-function/custom-error.tsx @@ -0,0 +1,69 @@ +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { setResponseStatus } from '@tanstack/react-start/server' +import { useState } from 'react' +import { z } from 'zod' +import { CustomError } from '~/CustomError' + +const schema = z.object({ hello: z.string() }) +const serverFnThrowing = createServerFn() + .validator(schema) + .handler(async ({ data }) => { + if (data.hello === 'world') { + return 'Hello, world!' + } + setResponseStatus(499) + throw new CustomError('Invalid input', { foo: 'bar', bar: BigInt(123) }) + }) + +export const Route = createFileRoute('/server-function/custom-error')({ + component: RouteComponent, +}) + +function RouteComponent() { + const [validResponse, setValidResponse] = useState(null) + const [invalidResponse, setInvalidResponse] = useState( + null, + ) + + return ( +
+ +
+ {JSON.stringify(validResponse)} +
+ +
+ +
+ {invalidResponse + ? JSON.stringify({ + message: invalidResponse.message, + foo: invalidResponse.foo, + bar: invalidResponse.bar.toString(), + }) + : JSON.stringify(validResponse)} +
+
+ ) +} diff --git a/e2e/react-start/serialization-adapters/src/routes/ssr/data-only.tsx b/e2e/react-start/serialization-adapters/src/routes/ssr/data-only.tsx new file mode 100644 index 0000000000..c2626f42e2 --- /dev/null +++ b/e2e/react-start/serialization-adapters/src/routes/ssr/data-only.tsx @@ -0,0 +1,51 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { RenderData, makeData } from '~/data' + +export const Route = createFileRoute('/ssr/data-only')({ + ssr: 'data-only', + beforeLoad: () => { + return makeData() + }, + loader: ({ context }) => { + return context + }, + component: () => { + const context = Route.useRouteContext() + const loaderData = Route.useLoaderData() + + const localData = makeData() + const expectedHonkState = localData.car.singleInstance.honk() + + const honkState = loaderData.car.singleInstance.honk() + + return ( +
+

data-only

+
+ context: +
+
+ loader: +
+
+

honk

+
+ expected:{' '} +
+ {JSON.stringify(expectedHonkState)} +
+
+
+ actual:{' '} +
+ {JSON.stringify(honkState)} +
+
+
+
+ +
+ ) + }, + pendingComponent: () =>
posts Loading...
, +}) diff --git a/e2e/react-start/serialization-adapters/src/routes/ssr/stream.tsx b/e2e/react-start/serialization-adapters/src/routes/ssr/stream.tsx new file mode 100644 index 0000000000..75926f8342 --- /dev/null +++ b/e2e/react-start/serialization-adapters/src/routes/ssr/stream.tsx @@ -0,0 +1,31 @@ +import { Await, createFileRoute } from '@tanstack/react-router' +import { Suspense } from 'react' +import { RenderData, makeData } from '~/data' + +export const Route = createFileRoute('/ssr/stream')({ + loader: () => { + const dataPromise = new Promise>((r) => + setTimeout(() => r(makeData()), 1000), + ) + return { + someString: 'hello world', + dataPromise, + } + }, + component: RouteComponent, +}) + +function RouteComponent() { + const loaderData = Route.useLoaderData() + return ( +
+

Stream

+
{loaderData.someString}
+ Loading...
}> + + {(data) => } + + + + ) +} diff --git a/e2e/react-start/serialization-adapters/src/styles/app.css b/e2e/react-start/serialization-adapters/src/styles/app.css new file mode 100644 index 0000000000..c53c870665 --- /dev/null +++ b/e2e/react-start/serialization-adapters/src/styles/app.css @@ -0,0 +1,22 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +@layer base { + html { + color-scheme: light dark; + } + + * { + @apply border-gray-200 dark:border-gray-800; + } + + html, + body { + @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; + } + + .using-mouse * { + outline: none !important; + } +} diff --git a/e2e/react-start/serialization-adapters/tailwind.config.mjs b/e2e/react-start/serialization-adapters/tailwind.config.mjs new file mode 100644 index 0000000000..e49f4eb776 --- /dev/null +++ b/e2e/react-start/serialization-adapters/tailwind.config.mjs @@ -0,0 +1,4 @@ +/** @type {import('tailwindcss').Config} */ +export default { + content: ['./src/**/*.{js,jsx,ts,tsx}'], +} diff --git a/e2e/react-start/serialization-adapters/tests/app.spec.ts b/e2e/react-start/serialization-adapters/tests/app.spec.ts new file mode 100644 index 0000000000..2cfaaf727d --- /dev/null +++ b/e2e/react-start/serialization-adapters/tests/app.spec.ts @@ -0,0 +1,76 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +import type { Page } from '@playwright/test' + +async function awaitPageLoaded(page: Page) { + // wait for page to be loaded by waiting for the ClientOnly component to be rendered + + await expect(page.getByTestId('router-isLoading')).toContainText('false') + await expect(page.getByTestId('router-status')).toContainText('idle') +} +async function checkData(page: Page, id: string) { + const expectedData = await page + .getByTestId(`${id}-car-expected`) + .textContent() + expect(expectedData).not.toBeNull() + await expect(page.getByTestId(`${id}-car-actual`)).toContainText( + expectedData!, + ) + + await expect(page.getByTestId(`${id}-foo`)).toContainText( + '{"value":"server"}', + ) +} +test.use({ + whitelistErrors: [ + /Failed to load resource: the server responded with a status of 499/, + ], +}) +test.describe('SSR serialization adapters', () => { + test(`data-only`, async ({ page }) => { + await page.goto('/ssr/data-only') + await awaitPageLoaded(page) + + await Promise.all( + ['context', 'loader'].map(async (id) => checkData(page, id)), + ) + + const expectedHonkData = await page + .getByTestId('honk-expected-state') + .textContent() + expect(expectedHonkData).not.toBeNull() + await expect(page.getByTestId('honk-actual-state')).toContainText( + expectedHonkData!, + ) + }) + + test('stream', async ({ page }) => { + await page.goto('/ssr/stream') + await awaitPageLoaded(page) + await checkData(page, 'stream') + }) +}) + +test.describe('server functions serialization adapters', () => { + test('custom error', async ({ page }) => { + await page.goto('/server-function/custom-error') + await awaitPageLoaded(page) + + await expect( + page.getByTestId('server-function-valid-response'), + ).toContainText('null') + await expect( + page.getByTestId('server-function-invalid-response'), + ).toContainText('null') + + await page.getByTestId('server-function-valid-input').click() + await expect( + page.getByTestId('server-function-valid-response'), + ).toContainText('Hello, world!') + + await page.getByTestId('server-function-invalid-input').click() + await expect( + page.getByTestId('server-function-invalid-response'), + ).toContainText('{"message":"Invalid input","foo":"bar","bar":"123"}') + }) +}) diff --git a/e2e/react-start/serialization-adapters/tsconfig.json b/e2e/react-start/serialization-adapters/tsconfig.json new file mode 100644 index 0000000000..3a9fb7cd71 --- /dev/null +++ b/e2e/react-start/serialization-adapters/tsconfig.json @@ -0,0 +1,22 @@ +{ + "include": ["**/*.ts", "**/*.tsx"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "isolatedModules": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "target": "ES2022", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "baseUrl": ".", + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true + } +} diff --git a/e2e/react-start/serialization-adapters/vite.config.ts b/e2e/react-start/serialization-adapters/vite.config.ts new file mode 100644 index 0000000000..04033010e8 --- /dev/null +++ b/e2e/react-start/serialization-adapters/vite.config.ts @@ -0,0 +1,17 @@ +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import tsConfigPaths from 'vite-tsconfig-paths' +import viteReact from '@vitejs/plugin-react' + +export default defineConfig({ + server: { + port: 3000, + }, + plugins: [ + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), + tanstackStart(), + viteReact(), + ], +}) diff --git a/e2e/react-start/server-functions/package.json b/e2e/react-start/server-functions/package.json index bf735283d8..2a74346351 100644 --- a/e2e/react-start/server-functions/package.json +++ b/e2e/react-start/server-functions/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -19,7 +19,7 @@ "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwind-merge": "^2.6.0", - "vite": "^6.3.5", + "vite": "^7.1.1", "zod": "^3.24.2" }, "devDependencies": { @@ -33,6 +33,7 @@ "autoprefixer": "^10.4.20", "combinate": "^1.1.11", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", "vite-tsconfig-paths": "^5.1.4" diff --git a/e2e/react-start/server-functions/src/routeTree.gen.ts b/e2e/react-start/server-functions/src/routeTree.gen.ts index 39bdf99d2d..249607c47d 100644 --- a/e2e/react-start/server-functions/src/routeTree.gen.ts +++ b/e2e/react-start/server-functions/src/routeTree.gen.ts @@ -24,6 +24,7 @@ import { Route as AbortSignalRouteImport } from './routes/abort-signal' import { Route as IndexRouteImport } from './routes/index' import { Route as MiddlewareIndexRouteImport } from './routes/middleware/index' import { Route as FormdataRedirectIndexRouteImport } from './routes/formdata-redirect/index' +import { Route as FactoryIndexRouteImport } from './routes/factory/index' import { Route as CookiesIndexRouteImport } from './routes/cookies/index' import { Route as MiddlewareSendServerFnRouteImport } from './routes/middleware/send-serverFn' import { Route as MiddlewareClientMiddlewareRouterRouteImport } from './routes/middleware/client-middleware-router' @@ -105,6 +106,11 @@ const FormdataRedirectIndexRoute = FormdataRedirectIndexRouteImport.update({ path: '/formdata-redirect/', getParentRoute: () => rootRouteImport, } as any) +const FactoryIndexRoute = FactoryIndexRouteImport.update({ + id: '/factory/', + path: '/factory/', + getParentRoute: () => rootRouteImport, +} as any) const CookiesIndexRoute = CookiesIndexRouteImport.update({ id: '/cookies/', path: '/cookies/', @@ -151,6 +157,7 @@ export interface FileRoutesByFullPath { '/middleware/client-middleware-router': typeof MiddlewareClientMiddlewareRouterRoute '/middleware/send-serverFn': typeof MiddlewareSendServerFnRoute '/cookies': typeof CookiesIndexRoute + '/factory': typeof FactoryIndexRoute '/formdata-redirect': typeof FormdataRedirectIndexRoute '/middleware': typeof MiddlewareIndexRoute '/formdata-redirect/target/$name': typeof FormdataRedirectTargetNameRoute @@ -173,6 +180,7 @@ export interface FileRoutesByTo { '/middleware/client-middleware-router': typeof MiddlewareClientMiddlewareRouterRoute '/middleware/send-serverFn': typeof MiddlewareSendServerFnRoute '/cookies': typeof CookiesIndexRoute + '/factory': typeof FactoryIndexRoute '/formdata-redirect': typeof FormdataRedirectIndexRoute '/middleware': typeof MiddlewareIndexRoute '/formdata-redirect/target/$name': typeof FormdataRedirectTargetNameRoute @@ -196,6 +204,7 @@ export interface FileRoutesById { '/middleware/client-middleware-router': typeof MiddlewareClientMiddlewareRouterRoute '/middleware/send-serverFn': typeof MiddlewareSendServerFnRoute '/cookies/': typeof CookiesIndexRoute + '/factory/': typeof FactoryIndexRoute '/formdata-redirect/': typeof FormdataRedirectIndexRoute '/middleware/': typeof MiddlewareIndexRoute '/formdata-redirect/target/$name': typeof FormdataRedirectTargetNameRoute @@ -220,6 +229,7 @@ export interface FileRouteTypes { | '/middleware/client-middleware-router' | '/middleware/send-serverFn' | '/cookies' + | '/factory' | '/formdata-redirect' | '/middleware' | '/formdata-redirect/target/$name' @@ -242,6 +252,7 @@ export interface FileRouteTypes { | '/middleware/client-middleware-router' | '/middleware/send-serverFn' | '/cookies' + | '/factory' | '/formdata-redirect' | '/middleware' | '/formdata-redirect/target/$name' @@ -264,6 +275,7 @@ export interface FileRouteTypes { | '/middleware/client-middleware-router' | '/middleware/send-serverFn' | '/cookies/' + | '/factory/' | '/formdata-redirect/' | '/middleware/' | '/formdata-redirect/target/$name' @@ -287,6 +299,7 @@ export interface RootRouteChildren { MiddlewareClientMiddlewareRouterRoute: typeof MiddlewareClientMiddlewareRouterRoute MiddlewareSendServerFnRoute: typeof MiddlewareSendServerFnRoute CookiesIndexRoute: typeof CookiesIndexRoute + FactoryIndexRoute: typeof FactoryIndexRoute FormdataRedirectIndexRoute: typeof FormdataRedirectIndexRoute MiddlewareIndexRoute: typeof MiddlewareIndexRoute FormdataRedirectTargetNameRoute: typeof FormdataRedirectTargetNameRoute @@ -399,6 +412,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof FormdataRedirectIndexRouteImport parentRoute: typeof rootRouteImport } + '/factory/': { + id: '/factory/' + path: '/factory' + fullPath: '/factory' + preLoaderRoute: typeof FactoryIndexRouteImport + parentRoute: typeof rootRouteImport + } '/cookies/': { id: '/cookies/' path: '/cookies' @@ -455,6 +475,7 @@ const rootRouteChildren: RootRouteChildren = { MiddlewareClientMiddlewareRouterRoute: MiddlewareClientMiddlewareRouterRoute, MiddlewareSendServerFnRoute: MiddlewareSendServerFnRoute, CookiesIndexRoute: CookiesIndexRoute, + FactoryIndexRoute: FactoryIndexRoute, FormdataRedirectIndexRoute: FormdataRedirectIndexRoute, MiddlewareIndexRoute: MiddlewareIndexRoute, FormdataRedirectTargetNameRoute: FormdataRedirectTargetNameRoute, diff --git a/e2e/react-start/server-functions/src/routes/env-only.tsx b/e2e/react-start/server-functions/src/routes/env-only.tsx index fe5ae8c1e8..2a938d692e 100644 --- a/e2e/react-start/server-functions/src/routes/env-only.tsx +++ b/e2e/react-start/server-functions/src/routes/env-only.tsx @@ -1,9 +1,13 @@ import { createFileRoute } from '@tanstack/react-router' -import { clientOnly, createServerFn, serverOnly } from '@tanstack/react-start' +import { + createClientOnlyFn, + createServerFn, + createServerOnlyFn, +} from '@tanstack/react-start' import { useState } from 'react' -const serverEcho = serverOnly((input: string) => 'server got: ' + input) -const clientEcho = clientOnly((input: string) => 'client got: ' + input) +const serverEcho = createServerOnlyFn((input: string) => 'server got: ' + input) +const clientEcho = createClientOnlyFn((input: string) => 'client got: ' + input) const testOnServer = createServerFn().handler(() => { const serverOnServer = serverEcho('hello') diff --git a/e2e/react-start/server-functions/src/routes/factory/-functions/createBarServerFn.ts b/e2e/react-start/server-functions/src/routes/factory/-functions/createBarServerFn.ts new file mode 100644 index 0000000000..4d622fcf9b --- /dev/null +++ b/e2e/react-start/server-functions/src/routes/factory/-functions/createBarServerFn.ts @@ -0,0 +1,22 @@ +import { createMiddleware } from '@tanstack/react-start' +import { createFooServerFn } from './createFooServerFn' + +const barMiddleware = createMiddleware({ type: 'function' }).server( + ({ next }) => { + console.log('Bar middleware triggered') + return next({ + context: { bar: 'bar' } as const, + }) + }, +) + +export const createBarServerFn = createFooServerFn().middleware([barMiddleware]) + +export const barFnInsideFactoryFile = createBarServerFn().handler( + ({ context }) => { + return { + name: 'barFnInsideFactoryFile', + context, + } + }, +) diff --git a/e2e/react-start/server-functions/src/routes/factory/-functions/createFakeFn.ts b/e2e/react-start/server-functions/src/routes/factory/-functions/createFakeFn.ts new file mode 100644 index 0000000000..1c72733885 --- /dev/null +++ b/e2e/react-start/server-functions/src/routes/factory/-functions/createFakeFn.ts @@ -0,0 +1,5 @@ +export function createFakeFn() { + return { + handler: (cb: () => Promise) => cb, + } +} diff --git a/e2e/react-start/server-functions/src/routes/factory/-functions/createFooServerFn.ts b/e2e/react-start/server-functions/src/routes/factory/-functions/createFooServerFn.ts new file mode 100644 index 0000000000..af13270b62 --- /dev/null +++ b/e2e/react-start/server-functions/src/routes/factory/-functions/createFooServerFn.ts @@ -0,0 +1,22 @@ +import { createMiddleware, createServerFn } from '@tanstack/react-start' + +const fooMiddleware = createMiddleware({ type: 'function' }).server( + ({ next }) => { + console.log('Foo middleware triggered') + return next({ + context: { foo: 'foo' } as const, + }) + }, +) + +export const createFooServerFn = createServerFn().middleware([fooMiddleware]) + +export const fooFnInsideFactoryFile = createFooServerFn().handler( + async ({ context, method }) => { + console.log('fooFnInsideFactoryFile handler triggered', method) + return { + name: 'fooFnInsideFactoryFile', + context, + } + }, +) diff --git a/e2e/react-start/server-functions/src/routes/factory/-functions/functions.ts b/e2e/react-start/server-functions/src/routes/factory/-functions/functions.ts new file mode 100644 index 0000000000..35be5f91f7 --- /dev/null +++ b/e2e/react-start/server-functions/src/routes/factory/-functions/functions.ts @@ -0,0 +1,93 @@ +import { createMiddleware, createServerFn } from '@tanstack/react-start' +import { createBarServerFn } from './createBarServerFn' +import { createFooServerFn } from './createFooServerFn' +import { createFakeFn } from './createFakeFn' + +export const fooFn = createFooServerFn().handler(({ context }) => { + return { + name: 'fooFn', + context, + } +}) + +export const fooFnPOST = createFooServerFn({ method: 'POST' }).handler( + ({ context }) => { + return { + name: 'fooFnPOST', + context, + } + }, +) + +export const barFn = createBarServerFn().handler(({ context }) => { + return { + name: 'barFn', + context, + } +}) + +export const barFnPOST = createBarServerFn({ method: 'POST' }).handler( + ({ context }) => { + return { + name: 'barFnPOST', + context, + } + }, +) + +const localMiddleware = createMiddleware({ type: 'function' }).server( + ({ next }) => { + console.log('local middleware triggered') + return next({ + context: { local: 'local' } as const, + }) + }, +) + +const localFnFactory = createBarServerFn.middleware([localMiddleware]) + +const anotherMiddleware = createMiddleware({ type: 'function' }).server( + ({ next }) => { + console.log('another middleware triggered') + return next({ + context: { another: 'another' } as const, + }) + }, +) + +export const localFn = localFnFactory() + .middleware([anotherMiddleware]) + .handler(({ context }) => { + return { + name: 'localFn', + context, + } + }) + +export const localFnPOST = localFnFactory({ method: 'POST' }) + .middleware([anotherMiddleware]) + .handler(({ context }) => { + return { + name: 'localFnPOST', + context, + } + }) + +export const fakeFn = createFakeFn().handler(async () => { + return { + name: 'fakeFn', + window, + } +}) + +export const composeFactory = createServerFn({ method: 'GET' }).middleware([ + createBarServerFn, +]) +export const composedFn = composeFactory() + .middleware([anotherMiddleware, localFnFactory]) + .handler(({ context }) => { + return { + name: 'composedFn', + context, + } + }) diff --git a/e2e/react-start/server-functions/src/routes/factory/index.tsx b/e2e/react-start/server-functions/src/routes/factory/index.tsx new file mode 100644 index 0000000000..cf16c362b1 --- /dev/null +++ b/e2e/react-start/server-functions/src/routes/factory/index.tsx @@ -0,0 +1,184 @@ +import { createFileRoute, deepEqual } from '@tanstack/react-router' + +import React from 'react' +import { createServerFn } from '@tanstack/react-start' +import { fooFnInsideFactoryFile } from './-functions/createFooServerFn' +import { + barFn, + barFnPOST, + composedFn, + fakeFn, + fooFn, + fooFnPOST, + localFn, + localFnPOST, +} from './-functions/functions' + +export const Route = createFileRoute('/factory/')({ + ssr: false, + component: RouteComponent, +}) + +const fnInsideRoute = createServerFn({ method: 'GET' }).handler(() => { + return { + name: 'fnInsideRoute', + } +}) + +const functions = { + fnInsideRoute: { + fn: fnInsideRoute, + type: 'serverFn', + expected: { + name: 'fnInsideRoute', + }, + }, + fooFnInsideFactoryFile: { + fn: fooFnInsideFactoryFile, + type: 'serverFn', + + expected: { + name: 'fooFnInsideFactoryFile', + context: { foo: 'foo' }, + }, + }, + fooFn: { + fn: fooFn, + type: 'serverFn', + + expected: { + name: 'fooFn', + context: { foo: 'foo' }, + }, + }, + fooFnPOST: { + fn: fooFnPOST, + type: 'serverFn', + + expected: { + name: 'fooFnPOST', + context: { foo: 'foo' }, + }, + }, + barFn: { + fn: barFn, + type: 'serverFn', + + expected: { + name: 'barFn', + context: { foo: 'foo', bar: 'bar' }, + }, + }, + barFnPOST: { + fn: barFnPOST, + type: 'serverFn', + + expected: { + name: 'barFnPOST', + context: { foo: 'foo', bar: 'bar' }, + }, + }, + localFn: { + fn: localFn, + type: 'serverFn', + + expected: { + name: 'localFn', + context: { foo: 'foo', bar: 'bar', local: 'local', another: 'another' }, + }, + }, + localFnPOST: { + fn: localFnPOST, + type: 'serverFn', + + expected: { + name: 'localFnPOST', + context: { foo: 'foo', bar: 'bar', local: 'local', another: 'another' }, + }, + }, + composedFn: { + fn: composedFn, + type: 'serverFn', + expected: { + name: 'composedFn', + context: { foo: 'foo', bar: 'bar', another: 'another', local: 'local' }, + }, + }, + fakeFn: { + fn: fakeFn, + type: 'localFn', + expected: { + name: 'fakeFn', + window, + }, + }, +} satisfies Record + +interface TestCase { + fn: () => Promise + expected: any + type: 'serverFn' | 'localFn' +} +function Test({ fn, type, expected }: TestCase) { + const [result, setResult] = React.useState(null) + function comparison() { + if (result) { + const isEqual = deepEqual(result, expected) + return isEqual ? 'equal' : 'not equal' + } + return 'Loading...' + } + + return ( +
+

+
+ It should return{' '} + +
+            {type === 'serverFn' ? JSON.stringify(expected) : 'localFn'}
+          
+
+
+

+ fn returns: +
+ + {result + ? type === 'serverFn' + ? JSON.stringify(result) + : 'localFn' + : 'Loading...'} + {' '} + + {comparison()} + +

+ +
+ ) +} +function RouteComponent() { + return ( +
+

+ Server functions middleware E2E tests +

+ {Object.entries(functions).map(([name, testCase]) => ( + + ))} +
+ ) +} diff --git a/e2e/react-start/server-functions/src/routes/headers.tsx b/e2e/react-start/server-functions/src/routes/headers.tsx index 77c576e40b..79b05c0fcb 100644 --- a/e2e/react-start/server-functions/src/routes/headers.tsx +++ b/e2e/react-start/server-functions/src/routes/headers.tsx @@ -1,8 +1,11 @@ import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' import { createServerFn } from '@tanstack/react-start' -import { getHeaders, setHeader } from '@tanstack/react-start/server' -import type { HTTPHeaderName } from '@tanstack/react-start/server' +import { + getRequestHeaders, + setResponseHeader, +} from '@tanstack/react-start/server' +import type { RequestHeaderName } from '@tanstack/react-start/server' export const Route = createFileRoute('/headers')({ loader: async () => { @@ -17,17 +20,18 @@ export const Route = createFileRoute('/headers')({ }) export const getTestHeaders = createServerFn().handler(() => { - setHeader('x-test-header', 'test-value') + setResponseHeader('x-test-header', 'test-value') + const reqHeaders = Object.fromEntries(getRequestHeaders().entries()) return { - serverHeaders: getHeaders(), - headers: getHeaders(), + serverHeaders: reqHeaders, + headers: reqHeaders, } }) type TestHeadersResult = { - headers?: Partial> - serverHeaders?: Partial> + headers?: Partial> + serverHeaders?: Partial> } function ResponseHeaders({ diff --git a/e2e/react-start/server-functions/src/routes/index.tsx b/e2e/react-start/server-functions/src/routes/index.tsx index 949cc08f58..6251940689 100644 --- a/e2e/react-start/server-functions/src/routes/index.tsx +++ b/e2e/react-start/server-functions/src/routes/index.tsx @@ -85,6 +85,9 @@ function Home() {
  • Server Functions Middlware E2E tests
  • +
  • + Server Functions Factory E2E tests +
  • ) diff --git a/e2e/react-start/server-functions/src/routes/raw-response.tsx b/e2e/react-start/server-functions/src/routes/raw-response.tsx index 8da5f8af7d..f30ff6660e 100644 --- a/e2e/react-start/server-functions/src/routes/raw-response.tsx +++ b/e2e/react-start/server-functions/src/routes/raw-response.tsx @@ -8,7 +8,7 @@ export const Route = createFileRoute('/raw-response')({ }) const expectedValue = 'Hello from a server function!' -export const rawResponseFn = createServerFn({ response: 'raw' }).handler(() => { +export const rawResponseFn = createServerFn().handler(() => { return new Response(expectedValue) }) diff --git a/e2e/react-start/server-functions/src/routes/serialize-form-data.tsx b/e2e/react-start/server-functions/src/routes/serialize-form-data.tsx index b1b9dc777a..5429df98c8 100644 --- a/e2e/react-start/server-functions/src/routes/serialize-form-data.tsx +++ b/e2e/react-start/server-functions/src/routes/serialize-form-data.tsx @@ -15,7 +15,7 @@ const testValues = { __adder: 1, } -export const greetUser = createServerFn() +export const greetUser = createServerFn({ method: 'POST' }) .validator((data: FormData) => { if (!(data instanceof FormData)) { throw new Error('Invalid! FormData is required') diff --git a/e2e/react-start/server-functions/src/routes/submit-post-formdata.tsx b/e2e/react-start/server-functions/src/routes/submit-post-formdata.tsx index 05df922817..4369239a05 100644 --- a/e2e/react-start/server-functions/src/routes/submit-post-formdata.tsx +++ b/e2e/react-start/server-functions/src/routes/submit-post-formdata.tsx @@ -9,7 +9,7 @@ const testValues = { name: 'Sean', } -export const greetUser = createServerFn({ method: 'POST', response: 'raw' }) +export const greetUser = createServerFn({ method: 'POST' }) .validator((data: FormData) => { if (!(data instanceof FormData)) { throw new Error('Invalid! FormData is required') diff --git a/e2e/react-start/server-functions/tests/fixture.ts b/e2e/react-start/server-functions/tests/fixture.ts deleted file mode 100644 index abb7b1d564..0000000000 --- a/e2e/react-start/server-functions/tests/fixture.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { test as base, expect } from '@playwright/test' - -export interface TestFixtureOptions { - whitelistErrors: Array -} -export const test = base.extend({ - whitelistErrors: [[], { option: true }], - page: async ({ page, whitelistErrors }, use) => { - const errorMessages: Array = [] - page.on('console', (m) => { - if (m.type() === 'error') { - const text = m.text() - for (const whitelistError of whitelistErrors) { - if ( - (typeof whitelistError === 'string' && - text.includes(whitelistError)) || - (whitelistError instanceof RegExp && whitelistError.test(text)) - ) { - return - } - } - errorMessages.push(text) - } - }) - await use(page) - expect(errorMessages).toEqual([]) - }, -}) diff --git a/e2e/react-start/server-functions/tests/server-functions.spec.ts b/e2e/react-start/server-functions/tests/server-functions.spec.ts index 86332e7491..990487289f 100644 --- a/e2e/react-start/server-functions/tests/server-functions.spec.ts +++ b/e2e/react-start/server-functions/tests/server-functions.spec.ts @@ -1,8 +1,11 @@ import * as fs from 'node:fs' -import { expect, test } from '@playwright/test' -import { PORT } from '../playwright.config' +import { expect } from '@playwright/test' +import { getTestServerPort, test } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } import type { Page } from '@playwright/test' +const PORT = await getTestServerPort(packageJson.name) + test('invoking a server function with custom response status code', async ({ page, }) => { @@ -11,16 +14,10 @@ test('invoking a server function with custom response status code', async ({ await page.waitForLoadState('networkidle') const requestPromise = new Promise((resolve) => { - page.on('response', async (response) => { + page.on('response', (response) => { expect(response.status()).toBe(225) expect(response.statusText()).toBe('hello') - expect(response.headers()['content-type']).toBe('application/json') - expect(await response.json()).toEqual( - expect.objectContaining({ - result: { hello: 'world' }, - context: {}, - }), - ) + expect(response.headers()['content-type']).toContain('application/json') resolve() }) }) @@ -122,11 +119,11 @@ test('env-only functions can only be called on the server or client respectively 'server got: hello', ) await expect(page.getByTestId('server-on-client')).toContainText( - 'serverEcho threw an error: serverOnly() functions can only be called on the server!', + 'serverEcho threw an error: createServerOnlyFn() functions can only be called on the server!', ) await expect(page.getByTestId('client-on-server')).toContainText( - 'clientEcho threw an error: clientOnly() functions can only be called on the client!', + 'clientEcho threw an error: createClientOnlyFn() functions can only be called on the client!', ) await expect(page.getByTestId('client-on-client')).toContainText( 'client got: hello', @@ -372,3 +369,37 @@ test.describe('middleware', () => { }) }) }) + +test('factory', async ({ page }) => { + await page.goto('/factory') + + await expect(page.getByTestId('factory-route-component')).toBeInViewport() + + const buttons = await page + .locator('[data-testid^="btn-fn-"]') + .elementHandles() + for (const button of buttons) { + const testId = await button.getAttribute('data-testid') + + if (!testId) { + throw new Error('Button is missing data-testid') + } + + const suffix = testId.replace('btn-fn-', '') + + const expected = + (await page.getByTestId(`expected-fn-result-${suffix}`).textContent()) || + '' + expect(expected).not.toBe('') + + await button.click() + + await expect(page.getByTestId(`fn-result-${suffix}`)).toContainText( + expected, + ) + + await expect(page.getByTestId(`fn-comparison-${suffix}`)).toContainText( + 'equal', + ) + } +}) diff --git a/e2e/react-start/server-functions/vite.config.ts b/e2e/react-start/server-functions/vite.config.ts index 1df337cd40..dc57f144e4 100644 --- a/e2e/react-start/server-functions/vite.config.ts +++ b/e2e/react-start/server-functions/vite.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ plugins: [ @@ -8,5 +9,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/e2e/react-start/server-routes/package.json b/e2e/react-start/server-routes/package.json index e7352c35ce..614c5d1552 100644 --- a/e2e/react-start/server-routes/package.json +++ b/e2e/react-start/server-routes/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "playwright test --project=chromium" }, "dependencies": { @@ -19,7 +19,7 @@ "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwind-merge": "^2.6.0", - "vite": "^6.3.5", + "vite": "^7.1.1", "zod": "^3.24.2" }, "devDependencies": { @@ -33,6 +33,7 @@ "autoprefixer": "^10.4.20", "combinate": "^1.1.11", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", "vite-tsconfig-paths": "^5.1.4" diff --git a/e2e/react-start/server-routes/tests/fixture.ts b/e2e/react-start/server-routes/tests/fixture.ts deleted file mode 100644 index abb7b1d564..0000000000 --- a/e2e/react-start/server-routes/tests/fixture.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { test as base, expect } from '@playwright/test' - -export interface TestFixtureOptions { - whitelistErrors: Array -} -export const test = base.extend({ - whitelistErrors: [[], { option: true }], - page: async ({ page, whitelistErrors }, use) => { - const errorMessages: Array = [] - page.on('console', (m) => { - if (m.type() === 'error') { - const text = m.text() - for (const whitelistError of whitelistErrors) { - if ( - (typeof whitelistError === 'string' && - text.includes(whitelistError)) || - (whitelistError instanceof RegExp && whitelistError.test(text)) - ) { - return - } - } - errorMessages.push(text) - } - }) - await use(page) - expect(errorMessages).toEqual([]) - }, -}) diff --git a/e2e/react-start/server-routes/tests/server-routes.spec.ts b/e2e/react-start/server-routes/tests/server-routes.spec.ts index 098a40b2ef..33176a23fd 100644 --- a/e2e/react-start/server-routes/tests/server-routes.spec.ts +++ b/e2e/react-start/server-routes/tests/server-routes.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' test('merge-server-fn-middleware-context', async ({ page }) => { await page.goto('/merge-server-fn-middleware-context') diff --git a/e2e/react-start/server-routes/vite.config.ts b/e2e/react-start/server-routes/vite.config.ts index 1df337cd40..dc57f144e4 100644 --- a/e2e/react-start/server-routes/vite.config.ts +++ b/e2e/react-start/server-routes/vite.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ plugins: [ @@ -8,5 +9,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/e2e/react-start/spa-mode/package.json b/e2e/react-start/spa-mode/package.json index ec5aaa4d5d..ae48f46c88 100644 --- a/e2e/react-start/spa-mode/package.json +++ b/e2e/react-start/spa-mode/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "npx serve .output/public", + "start": "npx serve dist/client", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -25,7 +25,7 @@ "postcss": "^8.5.1", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/react-start/spa-mode/tests/app.spec.ts b/e2e/react-start/spa-mode/tests/app.spec.ts index 8970ec333c..c18a0ff65d 100644 --- a/e2e/react-start/spa-mode/tests/app.spec.ts +++ b/e2e/react-start/spa-mode/tests/app.spec.ts @@ -1,5 +1,5 @@ import { expect } from '@playwright/test' -import { test } from './fixture' +import { test } from '@tanstack/router-e2e-utils' import type { Page } from '@playwright/test' async function runTest( diff --git a/e2e/react-start/spa-mode/tests/fixture.ts b/e2e/react-start/spa-mode/tests/fixture.ts deleted file mode 100644 index abb7b1d564..0000000000 --- a/e2e/react-start/spa-mode/tests/fixture.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { test as base, expect } from '@playwright/test' - -export interface TestFixtureOptions { - whitelistErrors: Array -} -export const test = base.extend({ - whitelistErrors: [[], { option: true }], - page: async ({ page, whitelistErrors }, use) => { - const errorMessages: Array = [] - page.on('console', (m) => { - if (m.type() === 'error') { - const text = m.text() - for (const whitelistError of whitelistErrors) { - if ( - (typeof whitelistError === 'string' && - text.includes(whitelistError)) || - (whitelistError instanceof RegExp && whitelistError.test(text)) - ) { - return - } - } - errorMessages.push(text) - } - }) - await use(page) - expect(errorMessages).toEqual([]) - }, -}) diff --git a/e2e/react-start/virtual-routes/package.json b/e2e/react-start/virtual-routes/package.json index 3347f1e995..b4f3b6b6ed 100644 --- a/e2e/react-start/virtual-routes/package.json +++ b/e2e/react-start/virtual-routes/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -19,7 +19,7 @@ "react-dom": "^19.0.0", "redaxios": "^0.5.1", "tailwind-merge": "^2.6.0", - "vite": "^6.3.5", + "vite": "^7.1.1", "zod": "^3.24.2" }, "devDependencies": { @@ -32,6 +32,7 @@ "autoprefixer": "^10.4.20", "combinate": "^1.1.11", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", "vite-tsconfig-paths": "^5.1.4" diff --git a/e2e/react-start/virtual-routes/vite.config.ts b/e2e/react-start/virtual-routes/vite.config.ts index 21ff4c2940..110811e198 100644 --- a/e2e/react-start/virtual-routes/vite.config.ts +++ b/e2e/react-start/virtual-routes/vite.config.ts @@ -11,7 +11,7 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart({ - tsr: { + router: { virtualRouteConfig: './routes.ts', }, }), diff --git a/e2e/react-start/website/package.json b/e2e/react-start/website/package.json index 2990a23c08..5d54afc056 100644 --- a/e2e/react-start/website/package.json +++ b/e2e/react-start/website/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -29,9 +29,10 @@ "@vitejs/plugin-react": "^4.3.4", "autoprefixer": "^10.4.20", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/react-start/website/vite.config.ts b/e2e/react-start/website/vite.config.ts index a1b3d840f5..c2c28ae93b 100644 --- a/e2e/react-start/website/vite.config.ts +++ b/e2e/react-start/website/vite.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/e2e/solid-router/basic-file-based-code-splitting/package.json b/e2e/solid-router/basic-file-based-code-splitting/package.json index 6a929a45bc..05739aa9c5 100644 --- a/e2e/solid-router/basic-file-based-code-splitting/package.json +++ b/e2e/solid-router/basic-file-based-code-splitting/package.json @@ -25,7 +25,7 @@ "devDependencies": { "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "vite": "^6.3.5", - "vite-plugin-solid": "^2.11.2" + "vite": "^7.1.1", + "vite-plugin-solid": "^2.11.8" } } diff --git a/e2e/solid-router/basic-file-based/package.json b/e2e/solid-router/basic-file-based/package.json index 50b911f89a..f3a3019b46 100644 --- a/e2e/solid-router/basic-file-based/package.json +++ b/e2e/solid-router/basic-file-based/package.json @@ -25,8 +25,8 @@ "devDependencies": { "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "vite-plugin-solid": "^2.11.2", + "vite-plugin-solid": "^2.11.8", "combinate": "^1.1.11", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/e2e/solid-router/basic-file-based/src/routeTree.gen.ts b/e2e/solid-router/basic-file-based/src/routeTree.gen.ts index 08d8fb4978..b81fbe69d5 100644 --- a/e2e/solid-router/basic-file-based/src/routeTree.gen.ts +++ b/e2e/solid-router/basic-file-based/src/routeTree.gen.ts @@ -22,6 +22,7 @@ import { Route as LayoutRouteImport } from './routes/_layout' import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' import { Route as IndexRouteImport } from './routes/index' import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' +import { Route as RelativeIndexRouteImport } from './routes/relative/index' import { Route as RedirectIndexRouteImport } from './routes/redirect/index' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' @@ -32,7 +33,13 @@ import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside import { Route as groupInsideRouteImport } from './routes/(group)/inside' import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' +import { Route as RelativeUseNavigateRouteRouteImport } from './routes/relative/useNavigate/route' +import { Route as RelativeLinkRouteRouteImport } from './routes/relative/link/route' import { Route as RedirectTargetIndexRouteImport } from './routes/redirect/$target/index' +import { Route as RelativeUseNavigateRelativeUseNavigateBRouteImport } from './routes/relative/useNavigate/relative-useNavigate-b' +import { Route as RelativeUseNavigateRelativeUseNavigateARouteImport } from './routes/relative/useNavigate/relative-useNavigate-a' +import { Route as RelativeLinkRelativeLinkBRouteImport } from './routes/relative/link/relative-link-b' +import { Route as RelativeLinkRelativeLinkARouteImport } from './routes/relative/link/relative-link-a' import { Route as RedirectPreloadThirdRouteImport } from './routes/redirect/preload/third' import { Route as RedirectPreloadSecondRouteImport } from './routes/redirect/preload/second' import { Route as RedirectPreloadFirstRouteImport } from './routes/redirect/preload/first' @@ -44,6 +51,16 @@ import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layo import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' import { Route as groupLayoutInsidelayoutRouteImport } from './routes/(group)/_layout.insidelayout' +import { Route as RelativeUseNavigateWithSearchIndexRouteImport } from './routes/relative/useNavigate/with-search/index' +import { Route as RelativeUseNavigatePathIndexRouteImport } from './routes/relative/useNavigate/path/index' +import { Route as RelativeUseNavigateNestedIndexRouteImport } from './routes/relative/useNavigate/nested/index' +import { Route as RelativeLinkWithSearchIndexRouteImport } from './routes/relative/link/with-search/index' +import { Route as RelativeLinkPathIndexRouteImport } from './routes/relative/link/path/index' +import { Route as RelativeLinkNestedIndexRouteImport } from './routes/relative/link/nested/index' +import { Route as RelativeUseNavigatePathPathIndexRouteImport } from './routes/relative/useNavigate/path/$path/index' +import { Route as RelativeUseNavigateNestedDeepIndexRouteImport } from './routes/relative/useNavigate/nested/deep/index' +import { Route as RelativeLinkPathPathIndexRouteImport } from './routes/relative/link/path/$path/index' +import { Route as RelativeLinkNestedDeepIndexRouteImport } from './routes/relative/link/nested/deep/index' const groupRouteImport = createFileRoute('/(group)')() @@ -105,6 +122,11 @@ const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ path: '/', getParentRoute: () => SearchParamsRouteRoute, } as any) +const RelativeIndexRoute = RelativeIndexRouteImport.update({ + id: '/relative/', + path: '/relative/', + getParentRoute: () => rootRouteImport, +} as any) const RedirectIndexRoute = RedirectIndexRouteImport.update({ id: '/redirect/', path: '/redirect/', @@ -156,11 +178,46 @@ const anotherGroupOnlyrouteinsideRoute = path: '/onlyrouteinside', getParentRoute: () => rootRouteImport, } as any) +const RelativeUseNavigateRouteRoute = + RelativeUseNavigateRouteRouteImport.update({ + id: '/relative/useNavigate', + path: '/relative/useNavigate', + getParentRoute: () => rootRouteImport, + } as any) +const RelativeLinkRouteRoute = RelativeLinkRouteRouteImport.update({ + id: '/relative/link', + path: '/relative/link', + getParentRoute: () => rootRouteImport, +} as any) const RedirectTargetIndexRoute = RedirectTargetIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => RedirectTargetRoute, } as any) +const RelativeUseNavigateRelativeUseNavigateBRoute = + RelativeUseNavigateRelativeUseNavigateBRouteImport.update({ + id: '/relative-useNavigate-b', + path: '/relative-useNavigate-b', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeUseNavigateRelativeUseNavigateARoute = + RelativeUseNavigateRelativeUseNavigateARouteImport.update({ + id: '/relative-useNavigate-a', + path: '/relative-useNavigate-a', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeLinkRelativeLinkBRoute = + RelativeLinkRelativeLinkBRouteImport.update({ + id: '/relative-link-b', + path: '/relative-link-b', + getParentRoute: () => RelativeLinkRouteRoute, + } as any) +const RelativeLinkRelativeLinkARoute = + RelativeLinkRelativeLinkARouteImport.update({ + id: '/relative-link-a', + path: '/relative-link-a', + getParentRoute: () => RelativeLinkRouteRoute, + } as any) const RedirectPreloadThirdRoute = RedirectPreloadThirdRouteImport.update({ id: '/redirect/preload/third', path: '/redirect/preload/third', @@ -217,6 +274,64 @@ const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({ path: '/insidelayout', getParentRoute: () => groupLayoutRoute, } as any) +const RelativeUseNavigateWithSearchIndexRoute = + RelativeUseNavigateWithSearchIndexRouteImport.update({ + id: '/with-search/', + path: '/with-search/', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeUseNavigatePathIndexRoute = + RelativeUseNavigatePathIndexRouteImport.update({ + id: '/path/', + path: '/path/', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeUseNavigateNestedIndexRoute = + RelativeUseNavigateNestedIndexRouteImport.update({ + id: '/nested/', + path: '/nested/', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeLinkWithSearchIndexRoute = + RelativeLinkWithSearchIndexRouteImport.update({ + id: '/with-search/', + path: '/with-search/', + getParentRoute: () => RelativeLinkRouteRoute, + } as any) +const RelativeLinkPathIndexRoute = RelativeLinkPathIndexRouteImport.update({ + id: '/path/', + path: '/path/', + getParentRoute: () => RelativeLinkRouteRoute, +} as any) +const RelativeLinkNestedIndexRoute = RelativeLinkNestedIndexRouteImport.update({ + id: '/nested/', + path: '/nested/', + getParentRoute: () => RelativeLinkRouteRoute, +} as any) +const RelativeUseNavigatePathPathIndexRoute = + RelativeUseNavigatePathPathIndexRouteImport.update({ + id: '/path/$path/', + path: '/path/$path/', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeUseNavigateNestedDeepIndexRoute = + RelativeUseNavigateNestedDeepIndexRouteImport.update({ + id: '/nested/deep/', + path: '/nested/deep/', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeLinkPathPathIndexRoute = + RelativeLinkPathPathIndexRouteImport.update({ + id: '/path/$path/', + path: '/path/$path/', + getParentRoute: () => RelativeLinkRouteRoute, + } as any) +const RelativeLinkNestedDeepIndexRoute = + RelativeLinkNestedDeepIndexRouteImport.update({ + id: '/nested/deep/', + path: '/nested/deep/', + getParentRoute: () => RelativeLinkRouteRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof groupLayoutRouteWithChildren @@ -228,6 +343,8 @@ export interface FileRoutesByFullPath { '/notRemountDeps': typeof NotRemountDepsRoute '/posts': typeof PostsRouteWithChildren '/remountDeps': typeof RemountDepsRoute + '/relative/link': typeof RelativeLinkRouteRouteWithChildren + '/relative/useNavigate': typeof RelativeUseNavigateRouteRouteWithChildren '/onlyrouteinside': typeof anotherGroupOnlyrouteinsideRoute '/inside': typeof groupInsideRoute '/lazyinside': typeof groupLazyinsideRoute @@ -236,6 +353,7 @@ export interface FileRoutesByFullPath { '/search-params/default': typeof SearchParamsDefaultRoute '/posts/': typeof PostsIndexRoute '/redirect': typeof RedirectIndexRoute + '/relative': typeof RelativeIndexRoute '/search-params/': typeof SearchParamsIndexRoute '/insidelayout': typeof groupLayoutInsidelayoutRoute '/subfolder/inside': typeof groupSubfolderInsideRoute @@ -248,7 +366,21 @@ export interface FileRoutesByFullPath { '/redirect/preload/first': typeof RedirectPreloadFirstRoute '/redirect/preload/second': typeof RedirectPreloadSecondRoute '/redirect/preload/third': typeof RedirectPreloadThirdRoute + '/relative/link/relative-link-a': typeof RelativeLinkRelativeLinkARoute + '/relative/link/relative-link-b': typeof RelativeLinkRelativeLinkBRoute + '/relative/useNavigate/relative-useNavigate-a': typeof RelativeUseNavigateRelativeUseNavigateARoute + '/relative/useNavigate/relative-useNavigate-b': typeof RelativeUseNavigateRelativeUseNavigateBRoute '/redirect/$target/': typeof RedirectTargetIndexRoute + '/relative/link/nested': typeof RelativeLinkNestedIndexRoute + '/relative/link/path': typeof RelativeLinkPathIndexRoute + '/relative/link/with-search': typeof RelativeLinkWithSearchIndexRoute + '/relative/useNavigate/nested': typeof RelativeUseNavigateNestedIndexRoute + '/relative/useNavigate/path': typeof RelativeUseNavigatePathIndexRoute + '/relative/useNavigate/with-search': typeof RelativeUseNavigateWithSearchIndexRoute + '/relative/link/nested/deep': typeof RelativeLinkNestedDeepIndexRoute + '/relative/link/path/$path': typeof RelativeLinkPathPathIndexRoute + '/relative/useNavigate/nested/deep': typeof RelativeUseNavigateNestedDeepIndexRoute + '/relative/useNavigate/path/$path': typeof RelativeUseNavigatePathPathIndexRoute } export interface FileRoutesByTo { '/': typeof groupLayoutRouteWithChildren @@ -258,6 +390,8 @@ export interface FileRoutesByTo { '/editing-b': typeof EditingBRoute '/notRemountDeps': typeof NotRemountDepsRoute '/remountDeps': typeof RemountDepsRoute + '/relative/link': typeof RelativeLinkRouteRouteWithChildren + '/relative/useNavigate': typeof RelativeUseNavigateRouteRouteWithChildren '/onlyrouteinside': typeof anotherGroupOnlyrouteinsideRoute '/inside': typeof groupInsideRoute '/lazyinside': typeof groupLazyinsideRoute @@ -265,6 +399,7 @@ export interface FileRoutesByTo { '/search-params/default': typeof SearchParamsDefaultRoute '/posts': typeof PostsIndexRoute '/redirect': typeof RedirectIndexRoute + '/relative': typeof RelativeIndexRoute '/search-params': typeof SearchParamsIndexRoute '/insidelayout': typeof groupLayoutInsidelayoutRoute '/subfolder/inside': typeof groupSubfolderInsideRoute @@ -277,7 +412,21 @@ export interface FileRoutesByTo { '/redirect/preload/first': typeof RedirectPreloadFirstRoute '/redirect/preload/second': typeof RedirectPreloadSecondRoute '/redirect/preload/third': typeof RedirectPreloadThirdRoute + '/relative/link/relative-link-a': typeof RelativeLinkRelativeLinkARoute + '/relative/link/relative-link-b': typeof RelativeLinkRelativeLinkBRoute + '/relative/useNavigate/relative-useNavigate-a': typeof RelativeUseNavigateRelativeUseNavigateARoute + '/relative/useNavigate/relative-useNavigate-b': typeof RelativeUseNavigateRelativeUseNavigateBRoute '/redirect/$target': typeof RedirectTargetIndexRoute + '/relative/link/nested': typeof RelativeLinkNestedIndexRoute + '/relative/link/path': typeof RelativeLinkPathIndexRoute + '/relative/link/with-search': typeof RelativeLinkWithSearchIndexRoute + '/relative/useNavigate/nested': typeof RelativeUseNavigateNestedIndexRoute + '/relative/useNavigate/path': typeof RelativeUseNavigatePathIndexRoute + '/relative/useNavigate/with-search': typeof RelativeUseNavigateWithSearchIndexRoute + '/relative/link/nested/deep': typeof RelativeLinkNestedDeepIndexRoute + '/relative/link/path/$path': typeof RelativeLinkPathPathIndexRoute + '/relative/useNavigate/nested/deep': typeof RelativeUseNavigateNestedDeepIndexRoute + '/relative/useNavigate/path/$path': typeof RelativeUseNavigatePathPathIndexRoute } export interface FileRoutesById { __root__: typeof rootRouteImport @@ -291,6 +440,8 @@ export interface FileRoutesById { '/notRemountDeps': typeof NotRemountDepsRoute '/posts': typeof PostsRouteWithChildren '/remountDeps': typeof RemountDepsRoute + '/relative/link': typeof RelativeLinkRouteRouteWithChildren + '/relative/useNavigate': typeof RelativeUseNavigateRouteRouteWithChildren '/(another-group)/onlyrouteinside': typeof anotherGroupOnlyrouteinsideRoute '/(group)': typeof groupRouteWithChildren '/(group)/_layout': typeof groupLayoutRouteWithChildren @@ -302,6 +453,7 @@ export interface FileRoutesById { '/search-params/default': typeof SearchParamsDefaultRoute '/posts/': typeof PostsIndexRoute '/redirect/': typeof RedirectIndexRoute + '/relative/': typeof RelativeIndexRoute '/search-params/': typeof SearchParamsIndexRoute '/(group)/_layout/insidelayout': typeof groupLayoutInsidelayoutRoute '/(group)/subfolder/inside': typeof groupSubfolderInsideRoute @@ -314,7 +466,21 @@ export interface FileRoutesById { '/redirect/preload/first': typeof RedirectPreloadFirstRoute '/redirect/preload/second': typeof RedirectPreloadSecondRoute '/redirect/preload/third': typeof RedirectPreloadThirdRoute + '/relative/link/relative-link-a': typeof RelativeLinkRelativeLinkARoute + '/relative/link/relative-link-b': typeof RelativeLinkRelativeLinkBRoute + '/relative/useNavigate/relative-useNavigate-a': typeof RelativeUseNavigateRelativeUseNavigateARoute + '/relative/useNavigate/relative-useNavigate-b': typeof RelativeUseNavigateRelativeUseNavigateBRoute '/redirect/$target/': typeof RedirectTargetIndexRoute + '/relative/link/nested/': typeof RelativeLinkNestedIndexRoute + '/relative/link/path/': typeof RelativeLinkPathIndexRoute + '/relative/link/with-search/': typeof RelativeLinkWithSearchIndexRoute + '/relative/useNavigate/nested/': typeof RelativeUseNavigateNestedIndexRoute + '/relative/useNavigate/path/': typeof RelativeUseNavigatePathIndexRoute + '/relative/useNavigate/with-search/': typeof RelativeUseNavigateWithSearchIndexRoute + '/relative/link/nested/deep/': typeof RelativeLinkNestedDeepIndexRoute + '/relative/link/path/$path/': typeof RelativeLinkPathPathIndexRoute + '/relative/useNavigate/nested/deep/': typeof RelativeUseNavigateNestedDeepIndexRoute + '/relative/useNavigate/path/$path/': typeof RelativeUseNavigatePathPathIndexRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath @@ -328,6 +494,8 @@ export interface FileRouteTypes { | '/notRemountDeps' | '/posts' | '/remountDeps' + | '/relative/link' + | '/relative/useNavigate' | '/onlyrouteinside' | '/inside' | '/lazyinside' @@ -336,6 +504,7 @@ export interface FileRouteTypes { | '/search-params/default' | '/posts/' | '/redirect' + | '/relative' | '/search-params/' | '/insidelayout' | '/subfolder/inside' @@ -348,7 +517,21 @@ export interface FileRouteTypes { | '/redirect/preload/first' | '/redirect/preload/second' | '/redirect/preload/third' + | '/relative/link/relative-link-a' + | '/relative/link/relative-link-b' + | '/relative/useNavigate/relative-useNavigate-a' + | '/relative/useNavigate/relative-useNavigate-b' | '/redirect/$target/' + | '/relative/link/nested' + | '/relative/link/path' + | '/relative/link/with-search' + | '/relative/useNavigate/nested' + | '/relative/useNavigate/path' + | '/relative/useNavigate/with-search' + | '/relative/link/nested/deep' + | '/relative/link/path/$path' + | '/relative/useNavigate/nested/deep' + | '/relative/useNavigate/path/$path' fileRoutesByTo: FileRoutesByTo to: | '/' @@ -358,6 +541,8 @@ export interface FileRouteTypes { | '/editing-b' | '/notRemountDeps' | '/remountDeps' + | '/relative/link' + | '/relative/useNavigate' | '/onlyrouteinside' | '/inside' | '/lazyinside' @@ -365,6 +550,7 @@ export interface FileRouteTypes { | '/search-params/default' | '/posts' | '/redirect' + | '/relative' | '/search-params' | '/insidelayout' | '/subfolder/inside' @@ -377,7 +563,21 @@ export interface FileRouteTypes { | '/redirect/preload/first' | '/redirect/preload/second' | '/redirect/preload/third' + | '/relative/link/relative-link-a' + | '/relative/link/relative-link-b' + | '/relative/useNavigate/relative-useNavigate-a' + | '/relative/useNavigate/relative-useNavigate-b' | '/redirect/$target' + | '/relative/link/nested' + | '/relative/link/path' + | '/relative/link/with-search' + | '/relative/useNavigate/nested' + | '/relative/useNavigate/path' + | '/relative/useNavigate/with-search' + | '/relative/link/nested/deep' + | '/relative/link/path/$path' + | '/relative/useNavigate/nested/deep' + | '/relative/useNavigate/path/$path' id: | '__root__' | '/' @@ -390,6 +590,8 @@ export interface FileRouteTypes { | '/notRemountDeps' | '/posts' | '/remountDeps' + | '/relative/link' + | '/relative/useNavigate' | '/(another-group)/onlyrouteinside' | '/(group)' | '/(group)/_layout' @@ -401,6 +603,7 @@ export interface FileRouteTypes { | '/search-params/default' | '/posts/' | '/redirect/' + | '/relative/' | '/search-params/' | '/(group)/_layout/insidelayout' | '/(group)/subfolder/inside' @@ -413,7 +616,21 @@ export interface FileRouteTypes { | '/redirect/preload/first' | '/redirect/preload/second' | '/redirect/preload/third' + | '/relative/link/relative-link-a' + | '/relative/link/relative-link-b' + | '/relative/useNavigate/relative-useNavigate-a' + | '/relative/useNavigate/relative-useNavigate-b' | '/redirect/$target/' + | '/relative/link/nested/' + | '/relative/link/path/' + | '/relative/link/with-search/' + | '/relative/useNavigate/nested/' + | '/relative/useNavigate/path/' + | '/relative/useNavigate/with-search/' + | '/relative/link/nested/deep/' + | '/relative/link/path/$path/' + | '/relative/useNavigate/nested/deep/' + | '/relative/useNavigate/path/$path/' fileRoutesById: FileRoutesById } export interface RootRouteChildren { @@ -427,10 +644,13 @@ export interface RootRouteChildren { NotRemountDepsRoute: typeof NotRemountDepsRoute PostsRoute: typeof PostsRouteWithChildren RemountDepsRoute: typeof RemountDepsRoute + RelativeLinkRouteRoute: typeof RelativeLinkRouteRouteWithChildren + RelativeUseNavigateRouteRoute: typeof RelativeUseNavigateRouteRouteWithChildren anotherGroupOnlyrouteinsideRoute: typeof anotherGroupOnlyrouteinsideRoute groupRoute: typeof groupRouteWithChildren RedirectTargetRoute: typeof RedirectTargetRouteWithChildren RedirectIndexRoute: typeof RedirectIndexRoute + RelativeIndexRoute: typeof RelativeIndexRoute ParamsSingleValueRoute: typeof ParamsSingleValueRoute PostsPostIdEditRoute: typeof PostsPostIdEditRoute RedirectPreloadFirstRoute: typeof RedirectPreloadFirstRoute @@ -524,6 +744,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SearchParamsIndexRouteImport parentRoute: typeof SearchParamsRouteRoute } + '/relative/': { + id: '/relative/' + path: '/relative' + fullPath: '/relative' + preLoaderRoute: typeof RelativeIndexRouteImport + parentRoute: typeof rootRouteImport + } '/redirect/': { id: '/redirect/' path: '/redirect' @@ -594,6 +821,20 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport parentRoute: typeof rootRouteImport } + '/relative/useNavigate': { + id: '/relative/useNavigate' + path: '/relative/useNavigate' + fullPath: '/relative/useNavigate' + preLoaderRoute: typeof RelativeUseNavigateRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/relative/link': { + id: '/relative/link' + path: '/relative/link' + fullPath: '/relative/link' + preLoaderRoute: typeof RelativeLinkRouteRouteImport + parentRoute: typeof rootRouteImport + } '/redirect/$target/': { id: '/redirect/$target/' path: '/' @@ -601,6 +842,34 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof RedirectTargetIndexRouteImport parentRoute: typeof RedirectTargetRoute } + '/relative/useNavigate/relative-useNavigate-b': { + id: '/relative/useNavigate/relative-useNavigate-b' + path: '/relative-useNavigate-b' + fullPath: '/relative/useNavigate/relative-useNavigate-b' + preLoaderRoute: typeof RelativeUseNavigateRelativeUseNavigateBRouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute + } + '/relative/useNavigate/relative-useNavigate-a': { + id: '/relative/useNavigate/relative-useNavigate-a' + path: '/relative-useNavigate-a' + fullPath: '/relative/useNavigate/relative-useNavigate-a' + preLoaderRoute: typeof RelativeUseNavigateRelativeUseNavigateARouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute + } + '/relative/link/relative-link-b': { + id: '/relative/link/relative-link-b' + path: '/relative-link-b' + fullPath: '/relative/link/relative-link-b' + preLoaderRoute: typeof RelativeLinkRelativeLinkBRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } + '/relative/link/relative-link-a': { + id: '/relative/link/relative-link-a' + path: '/relative-link-a' + fullPath: '/relative/link/relative-link-a' + preLoaderRoute: typeof RelativeLinkRelativeLinkARouteImport + parentRoute: typeof RelativeLinkRouteRoute + } '/redirect/preload/third': { id: '/redirect/preload/third' path: '/redirect/preload/third' @@ -678,6 +947,76 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport parentRoute: typeof groupLayoutRoute } + '/relative/useNavigate/with-search/': { + id: '/relative/useNavigate/with-search/' + path: '/with-search' + fullPath: '/relative/useNavigate/with-search' + preLoaderRoute: typeof RelativeUseNavigateWithSearchIndexRouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute + } + '/relative/useNavigate/path/': { + id: '/relative/useNavigate/path/' + path: '/path' + fullPath: '/relative/useNavigate/path' + preLoaderRoute: typeof RelativeUseNavigatePathIndexRouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute + } + '/relative/useNavigate/nested/': { + id: '/relative/useNavigate/nested/' + path: '/nested' + fullPath: '/relative/useNavigate/nested' + preLoaderRoute: typeof RelativeUseNavigateNestedIndexRouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute + } + '/relative/link/with-search/': { + id: '/relative/link/with-search/' + path: '/with-search' + fullPath: '/relative/link/with-search' + preLoaderRoute: typeof RelativeLinkWithSearchIndexRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } + '/relative/link/path/': { + id: '/relative/link/path/' + path: '/path' + fullPath: '/relative/link/path' + preLoaderRoute: typeof RelativeLinkPathIndexRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } + '/relative/link/nested/': { + id: '/relative/link/nested/' + path: '/nested' + fullPath: '/relative/link/nested' + preLoaderRoute: typeof RelativeLinkNestedIndexRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } + '/relative/useNavigate/path/$path/': { + id: '/relative/useNavigate/path/$path/' + path: '/path/$path' + fullPath: '/relative/useNavigate/path/$path' + preLoaderRoute: typeof RelativeUseNavigatePathPathIndexRouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute + } + '/relative/useNavigate/nested/deep/': { + id: '/relative/useNavigate/nested/deep/' + path: '/nested/deep' + fullPath: '/relative/useNavigate/nested/deep' + preLoaderRoute: typeof RelativeUseNavigateNestedDeepIndexRouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute + } + '/relative/link/path/$path/': { + id: '/relative/link/path/$path/' + path: '/path/$path' + fullPath: '/relative/link/path/$path' + preLoaderRoute: typeof RelativeLinkPathPathIndexRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } + '/relative/link/nested/deep/': { + id: '/relative/link/nested/deep/' + path: '/nested/deep' + fullPath: '/relative/link/nested/deep' + preLoaderRoute: typeof RelativeLinkNestedDeepIndexRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } } } @@ -731,6 +1070,60 @@ const PostsRouteChildren: PostsRouteChildren = { const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) +interface RelativeLinkRouteRouteChildren { + RelativeLinkRelativeLinkARoute: typeof RelativeLinkRelativeLinkARoute + RelativeLinkRelativeLinkBRoute: typeof RelativeLinkRelativeLinkBRoute + RelativeLinkNestedIndexRoute: typeof RelativeLinkNestedIndexRoute + RelativeLinkPathIndexRoute: typeof RelativeLinkPathIndexRoute + RelativeLinkWithSearchIndexRoute: typeof RelativeLinkWithSearchIndexRoute + RelativeLinkNestedDeepIndexRoute: typeof RelativeLinkNestedDeepIndexRoute + RelativeLinkPathPathIndexRoute: typeof RelativeLinkPathPathIndexRoute +} + +const RelativeLinkRouteRouteChildren: RelativeLinkRouteRouteChildren = { + RelativeLinkRelativeLinkARoute: RelativeLinkRelativeLinkARoute, + RelativeLinkRelativeLinkBRoute: RelativeLinkRelativeLinkBRoute, + RelativeLinkNestedIndexRoute: RelativeLinkNestedIndexRoute, + RelativeLinkPathIndexRoute: RelativeLinkPathIndexRoute, + RelativeLinkWithSearchIndexRoute: RelativeLinkWithSearchIndexRoute, + RelativeLinkNestedDeepIndexRoute: RelativeLinkNestedDeepIndexRoute, + RelativeLinkPathPathIndexRoute: RelativeLinkPathPathIndexRoute, +} + +const RelativeLinkRouteRouteWithChildren = + RelativeLinkRouteRoute._addFileChildren(RelativeLinkRouteRouteChildren) + +interface RelativeUseNavigateRouteRouteChildren { + RelativeUseNavigateRelativeUseNavigateARoute: typeof RelativeUseNavigateRelativeUseNavigateARoute + RelativeUseNavigateRelativeUseNavigateBRoute: typeof RelativeUseNavigateRelativeUseNavigateBRoute + RelativeUseNavigateNestedIndexRoute: typeof RelativeUseNavigateNestedIndexRoute + RelativeUseNavigatePathIndexRoute: typeof RelativeUseNavigatePathIndexRoute + RelativeUseNavigateWithSearchIndexRoute: typeof RelativeUseNavigateWithSearchIndexRoute + RelativeUseNavigateNestedDeepIndexRoute: typeof RelativeUseNavigateNestedDeepIndexRoute + RelativeUseNavigatePathPathIndexRoute: typeof RelativeUseNavigatePathPathIndexRoute +} + +const RelativeUseNavigateRouteRouteChildren: RelativeUseNavigateRouteRouteChildren = + { + RelativeUseNavigateRelativeUseNavigateARoute: + RelativeUseNavigateRelativeUseNavigateARoute, + RelativeUseNavigateRelativeUseNavigateBRoute: + RelativeUseNavigateRelativeUseNavigateBRoute, + RelativeUseNavigateNestedIndexRoute: RelativeUseNavigateNestedIndexRoute, + RelativeUseNavigatePathIndexRoute: RelativeUseNavigatePathIndexRoute, + RelativeUseNavigateWithSearchIndexRoute: + RelativeUseNavigateWithSearchIndexRoute, + RelativeUseNavigateNestedDeepIndexRoute: + RelativeUseNavigateNestedDeepIndexRoute, + RelativeUseNavigatePathPathIndexRoute: + RelativeUseNavigatePathPathIndexRoute, + } + +const RelativeUseNavigateRouteRouteWithChildren = + RelativeUseNavigateRouteRoute._addFileChildren( + RelativeUseNavigateRouteRouteChildren, + ) + interface groupLayoutRouteChildren { groupLayoutInsidelayoutRoute: typeof groupLayoutInsidelayoutRoute } @@ -786,10 +1179,13 @@ const rootRouteChildren: RootRouteChildren = { NotRemountDepsRoute: NotRemountDepsRoute, PostsRoute: PostsRouteWithChildren, RemountDepsRoute: RemountDepsRoute, + RelativeLinkRouteRoute: RelativeLinkRouteRouteWithChildren, + RelativeUseNavigateRouteRoute: RelativeUseNavigateRouteRouteWithChildren, anotherGroupOnlyrouteinsideRoute: anotherGroupOnlyrouteinsideRoute, groupRoute: groupRouteWithChildren, RedirectTargetRoute: RedirectTargetRouteWithChildren, RedirectIndexRoute: RedirectIndexRoute, + RelativeIndexRoute: RelativeIndexRoute, ParamsSingleValueRoute: ParamsSingleValueRoute, PostsPostIdEditRoute: PostsPostIdEditRoute, RedirectPreloadFirstRoute: RedirectPreloadFirstRoute, diff --git a/e2e/solid-router/basic-file-based/src/routes/__root.tsx b/e2e/solid-router/basic-file-based/src/routes/__root.tsx index c9ff803463..0997c45b37 100644 --- a/e2e/solid-router/basic-file-based/src/routes/__root.tsx +++ b/e2e/solid-router/basic-file-based/src/routes/__root.tsx @@ -122,6 +122,14 @@ function RootComponent() { > redirect {' '} + + relative routing + {' '} +
    + Relative Routing Tests - Home +
    +
    + Using Links + Using useNavigate +
    +
    + +
    + + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/link/nested/deep/index.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/link/nested/deep/index.tsx new file mode 100644 index 0000000000..d92d2b5e7c --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/link/nested/deep/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/relative/link/nested/deep/')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
    + Hello "/relative/link/nested/deep/"! +
    + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/link/nested/index.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/link/nested/index.tsx new file mode 100644 index 0000000000..5ddaa68d75 --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/link/nested/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/relative/link/nested/')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
    + Hello "/relative/link/nested/"! +
    + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/link/path/$path/index.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/link/path/$path/index.tsx new file mode 100644 index 0000000000..1cf079d4b8 --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/link/path/$path/index.tsx @@ -0,0 +1,31 @@ +import { Link, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/relative/link/path/$path/')({ + component: RouteComponent, + loader: ({ params }) => { + return params + }, +}) + +function RouteComponent() { + const params = Route.useParams() + + return ( +
    +
    + Hello from "/relative/links/path/{params().path}"! +
    +
    + + To {params().path === 'a' ? 'b' : 'a'} + +
    +
    + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/link/path/index.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/link/path/index.tsx new file mode 100644 index 0000000000..36bf3f5cde --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/link/path/index.tsx @@ -0,0 +1,18 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/relative/link/path/')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
    +
    + Relative Routing Tests - Path Params +
    +
    + +
    +
    + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/link/relative-link-a.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/link/relative-link-a.tsx new file mode 100644 index 0000000000..daa2cea064 --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/link/relative-link-a.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/relative/link/relative-link-a')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
    + Hello "/relative/link/relative-link-a"! +
    + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/link/relative-link-b.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/link/relative-link-b.tsx new file mode 100644 index 0000000000..9f80899b73 --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/link/relative-link-b.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/relative/link/relative-link-b')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
    + Hello "/relative/link/relative-link-b"! +
    + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/link/route.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/link/route.tsx new file mode 100644 index 0000000000..5d6934442b --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/link/route.tsx @@ -0,0 +1,93 @@ +import { + Link, + Outlet, + createFileRoute, + useNavigate, +} from '@tanstack/solid-router' +import { createEffect } from 'solid-js' + +export const Route = createFileRoute('/relative/link')({ + component: RouteComponent, +}) + +function RouteComponent() { + createEffect(() => { + console.log('navigate') + }) + + return ( +
    +
    + Relative Routing - Links - Index +
    +
    + + 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 + +
    +
    + +
    +
    + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/link/with-search/index.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/link/with-search/index.tsx new file mode 100644 index 0000000000..f571340a56 --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/link/with-search/index.tsx @@ -0,0 +1,29 @@ +import { Link, createFileRoute } from '@tanstack/solid-router' +import { z } from 'zod' + +export const Route = createFileRoute('/relative/link/with-search/')({ + component: RouteComponent, + validateSearch: z.object({ + searchParam: z.string().default('1'), + }), +}) + +function RouteComponent() { + const searchParams = Route.useSearch() + return ( + <> +
    + Hello "/relative/link/with-search/" searchParam:{' '} + {searchParams().searchParam}! +
    +
    + + Update Search + + + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/nested/deep/index.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/nested/deep/index.tsx new file mode 100644 index 0000000000..a373967b11 --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/nested/deep/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/relative/useNavigate/nested/deep/')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
    + Hello "/relative/useNavigate/nested/deep/"! +
    + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/nested/index.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/nested/index.tsx new file mode 100644 index 0000000000..5e41c4c6db --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/nested/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/relative/useNavigate/nested/')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
    + Hello "/relative/useNavigate/nested/"! +
    + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/path/$path/index.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/path/$path/index.tsx new file mode 100644 index 0000000000..167aca58d7 --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/path/$path/index.tsx @@ -0,0 +1,40 @@ +import { createFileRoute, useNavigate } from '@tanstack/solid-router' + +export const Route = createFileRoute('/relative/useNavigate/path/$path/')({ + component: RouteComponent, + loader: ({ params }) => { + return params + }, +}) + +function RouteComponent() { + const navigate = useNavigate() + + const params = Route.useParams() + + return ( +
    +
    + Hello from "/relative/useNavigate/path/{params().path}"! +
    +
    + +
    +
    + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/path/index.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/path/index.tsx new file mode 100644 index 0000000000..6734648ae5 --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/path/index.tsx @@ -0,0 +1,18 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/relative/useNavigate/path/')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
    +
    + Relative Routing Tests - Path Params +
    +
    + +
    +
    + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/relative-useNavigate-a.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/relative-useNavigate-a.tsx new file mode 100644 index 0000000000..bbe5625a62 --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/relative-useNavigate-a.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute( + '/relative/useNavigate/relative-useNavigate-a', +)({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
    + Hello "/relative/useNavigate/relative-useNavigate-a"! +
    + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/relative-useNavigate-b.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/relative-useNavigate-b.tsx new file mode 100644 index 0000000000..9be49cfcdc --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/relative-useNavigate-b.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute( + '/relative/useNavigate/relative-useNavigate-b', +)({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
    + Hello "/relative/useNavigate/relative-useNavigate-b"! +
    + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/route.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/route.tsx new file mode 100644 index 0000000000..7bdaeaecb5 --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/route.tsx @@ -0,0 +1,134 @@ +import { Outlet, createFileRoute, useNavigate } from '@tanstack/solid-router' +import { createEffect } from 'solid-js' + +export const Route = createFileRoute('/relative/useNavigate')({ + component: RouteComponent, +}) + +function RouteComponent() { + const navigate = useNavigate() + + createEffect(() => { + console.log('navigate') + }) + + return ( +
    +
    + Relative Routing - Links - Index +
    +
    + + + + + + + + + +
    +
    + +
    +
    + ) +} diff --git a/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/with-search/index.tsx b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/with-search/index.tsx new file mode 100644 index 0000000000..524eae04a7 --- /dev/null +++ b/e2e/solid-router/basic-file-based/src/routes/relative/useNavigate/with-search/index.tsx @@ -0,0 +1,35 @@ +import { createFileRoute, useNavigate } from '@tanstack/solid-router' +import { z } from 'zod' + +export const Route = createFileRoute('/relative/useNavigate/with-search/')({ + component: RouteComponent, + validateSearch: z.object({ + searchParam: z.string().default('1'), + }), +}) + +function RouteComponent() { + const navigate = useNavigate() + const searchParams = Route.useSearch() + + return ( + <> +
    + Hello "/relative/useNavigate/with-search/" searchParam:{' '} + {searchParams().searchParam}! +
    +
    + + + ) +} diff --git a/e2e/solid-router/basic-file-based/tests/relative.spec.ts b/e2e/solid-router/basic-file-based/tests/relative.spec.ts new file mode 100644 index 0000000000..4850d3630d --- /dev/null +++ b/e2e/solid-router/basic-file-based/tests/relative.spec.ts @@ -0,0 +1,273 @@ +import { expect, test } from '@playwright/test' +import combinateImport from 'combinate' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } + +// somehow playwright does not correctly import default exports +const combinate = (combinateImport as any).default as typeof combinateImport + +const PORT = await getTestServerPort(packageJson.name) + +test.describe('relative_routing', () => { + const internalNavigationTestMatrix = combinate({ + navigation: ['link', 'useNavigate'] as const, + }) + + internalNavigationTestMatrix.forEach(({ navigation }) => { + test(`simple relative navigation. navigation: ${navigation}`, async ({ + page, + }) => { + await page.waitForLoadState('networkidle') + await page.goto(`/relative/${navigation}`) + await page.waitForURL(`http://localhost:${PORT}/relative/${navigation}`) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + const indexLink = page.getByTestId(`relative-${navigation}-index`) + const backLink = page.getByTestId(`relative-${navigation}-back`) + const relativeRouteA = page.getByTestId(`relative-${navigation}-a`) + const relativeRouteB = page.getByTestId(`relative-${navigation}-b`) + + await relativeRouteA.click() + + await page.waitForURL( + `http://localhost:${PORT}/relative/${navigation}/relative-${navigation}-a`, + ) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + await expect( + page.getByTestId(`relative-${navigation}-a-header`), + ).toBeInViewport() + + await relativeRouteB.click() + + await page.waitForURL( + `http://localhost:${PORT}/relative/${navigation}/relative-${navigation}-b`, + ) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + await expect( + page.getByTestId(`relative-${navigation}-b-header`), + ).toBeInViewport() + + await indexLink.click() + + await page.waitForURL(`http://localhost:${PORT}/relative/${navigation}`) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + await expect( + page.getByTestId(`relative-${navigation}-b-header`), + ).not.toBeInViewport() + + await backLink.click() + + await page.waitForURL(`http://localhost:${PORT}/relative`) + + await expect(page.getByTestId(`relative-routing-home`)).toBeInViewport() + }) + + test(`nested chilren. navigation: ${navigation}`, async ({ page }) => { + await page.waitForLoadState('networkidle') + await page.goto(`/relative/${navigation}`) + await page.waitForURL(`http://localhost:${PORT}/relative/${navigation}`) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + const backLink = page.getByTestId(`relative-${navigation}-back`) + + const deeplyNestedChildRoute = page.getByTestId( + `relative-${navigation}-deeply-nested`, + ) + + await deeplyNestedChildRoute.click() + + await page.waitForURL( + `http://localhost:${PORT}/relative/${navigation}/nested/deep`, + ) + + await expect( + page.getByTestId(`relative-${navigation}-nested-deep-header`), + ).toBeInViewport() + + await backLink.click() + + await page.waitForURL( + `http://localhost:${PORT}/relative/${navigation}/nested`, + ) + + await expect( + page.getByTestId(`relative-${navigation}-nested-header`), + ).toBeInViewport() + }) + + test(`with path params. navigation: ${navigation}`, async ({ page }) => { + await page.waitForLoadState('networkidle') + await page.goto(`/relative/${navigation}`) + await page.waitForURL(`http://localhost:${PORT}/relative/${navigation}`) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + const pathParamRoute = page.getByTestId(`relative-${navigation}-path`) + + await pathParamRoute.click() + + await page.waitForURL( + `http://localhost:${PORT}/relative/${navigation}/path/a`, + ) + + expect(page.url().endsWith('/path/a')).toBe(true) + + await expect( + page.getByTestId(`relative-${navigation}-path-param-header`), + ).toBeInViewport() + + const switchParamLink = page.getByTestId( + `relative-${navigation}-path-param-switchAB`, + ) + + await switchParamLink.click() + + await page.waitForURL( + `http://localhost:${PORT}/relative/${navigation}/path/b`, + ) + + expect(page.url().endsWith('/path/b')).toBe(true) + + await expect( + page.getByTestId(`relative-${navigation}-path-param-header`), + ).toBeInViewport() + }) + + test(`with search params. navigation: ${navigation}`, async ({ page }) => { + await page.waitForLoadState('networkidle') + await page.goto(`/relative/${navigation}`) + await page.waitForURL(`http://localhost:${PORT}/relative/${navigation}`) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + const searchParamRoute = page.getByTestId( + `relative-${navigation}-withSearch`, + ) + + await searchParamRoute.click() + + let expectedUrl = new URL( + `http://localhost:${PORT}/relative/${navigation}/with-search?searchParam="1"`, + ) + + await page.waitForLoadState('domcontentloaded') + + expect(page.url().toString()).toBe(expectedUrl.toString()) + + await expect( + page.getByTestId(`relative-${navigation}-withSearch-header`), + ).toBeInViewport() + + await expect( + page.getByTestId(`relative-${navigation}-withSearch-header`), + ).toContainText('searchParam: 1') + + const updateSearchLink = page.getByTestId( + `relative-${navigation}-withSearch-update-param`, + ) + + await updateSearchLink.click() + + await page.waitForLoadState('domcontentloaded') + + expectedUrl = new URL( + `http://localhost:${PORT}/relative/${navigation}/with-search?searchParam="2"`, + ) + + expect(page.url().toString()).toBe(expectedUrl.toString()) + + await expect( + page.getByTestId(`relative-${navigation}-withSearch-header`), + ).toContainText('searchParam: 2') + + await expect( + page.getByTestId(`relative-${navigation}-withSearch-header`), + ).toBeInViewport() + }) + + test(`shouldn't cause excessive rendering. navigation: ${navigation}`, async ({ + page, + }) => { + let navigateMsgs = 0 + + page.on('console', (msg) => { + if (msg.text() === 'navigate') { + navigateMsgs++ + } + }) + + await page.waitForLoadState('networkidle') + await page.goto(`/relative/${navigation}`) + await page.waitForURL(`http://localhost:${PORT}/relative/${navigation}`) + + await expect( + page.getByTestId(`relative-${navigation}-header`), + ).toBeInViewport() + + expect(navigateMsgs).toBe(1) + const indexLink = page.getByTestId(`relative-${navigation}-index`) + const backLink = page.getByTestId(`relative-${navigation}-back`) + const relativeRouteA = page.getByTestId(`relative-${navigation}-a`) + const relativeRouteB = page.getByTestId(`relative-${navigation}-b`) + const deeplyNestedChildRoute = page.getByTestId( + `relative-${navigation}-deeply-nested`, + ) + const pathParamRoute = page.getByTestId(`relative-${navigation}-path`) + const searchParamRoute = page.getByTestId( + `relative-${navigation}-withSearch`, + ) + + await relativeRouteA.click() + await page.waitForLoadState('domcontentloaded') + await relativeRouteB.click() + await page.waitForLoadState('domcontentloaded') + await deeplyNestedChildRoute.click() + await page.waitForLoadState('domcontentloaded') + await backLink.click() + await page.waitForLoadState('domcontentloaded') + await pathParamRoute.click() + await page.waitForLoadState('domcontentloaded') + const switchParamLink = page.getByTestId( + `relative-${navigation}-path-param-switchAB`, + ) + await switchParamLink.click() + await page.waitForLoadState('domcontentloaded') + await searchParamRoute.click() + await page.waitForLoadState('domcontentloaded') + + const updateSearchLink = page.getByTestId( + `relative-${navigation}-withSearch-update-param`, + ) + + await updateSearchLink.click() + await page.waitForLoadState('domcontentloaded') + + await indexLink.click() + await page.waitForLoadState('domcontentloaded') + + expect(navigateMsgs).toBe(1) + }) + }) +}) diff --git a/e2e/solid-router/basic-scroll-restoration/package.json b/e2e/solid-router/basic-scroll-restoration/package.json index 99eadce4ed..b1eef16702 100644 --- a/e2e/solid-router/basic-scroll-restoration/package.json +++ b/e2e/solid-router/basic-scroll-restoration/package.json @@ -23,7 +23,7 @@ "devDependencies": { "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "vite-plugin-solid": "^2.11.2", - "vite": "^6.3.5" + "vite-plugin-solid": "^2.11.8", + "vite": "^7.1.1" } } diff --git a/e2e/solid-router/basic-solid-query-file-based/package.json b/e2e/solid-router/basic-solid-query-file-based/package.json index cff6d8c71c..2d9ccafe20 100644 --- a/e2e/solid-router/basic-solid-query-file-based/package.json +++ b/e2e/solid-router/basic-solid-query-file-based/package.json @@ -26,7 +26,7 @@ "devDependencies": { "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "vite-plugin-solid": "^2.11.2", - "vite": "^6.3.5" + "vite-plugin-solid": "^2.11.8", + "vite": "^7.1.1" } } diff --git a/e2e/solid-router/basic-solid-query/package.json b/e2e/solid-router/basic-solid-query/package.json index 61c7fa9fd3..4a1346f52e 100644 --- a/e2e/solid-router/basic-solid-query/package.json +++ b/e2e/solid-router/basic-solid-query/package.json @@ -24,7 +24,7 @@ "devDependencies": { "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "vite-plugin-solid": "^2.11.2", - "vite": "^6.3.5" + "vite-plugin-solid": "^2.11.8", + "vite": "^7.1.1" } } diff --git a/e2e/solid-router/basic-virtual-file-based/package.json b/e2e/solid-router/basic-virtual-file-based/package.json index 7e6f8ec3cd..3a19c7f602 100644 --- a/e2e/solid-router/basic-virtual-file-based/package.json +++ b/e2e/solid-router/basic-virtual-file-based/package.json @@ -25,7 +25,7 @@ "devDependencies": { "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "vite-plugin-solid": "^2.11.2", - "vite": "^6.3.5" + "vite-plugin-solid": "^2.11.8", + "vite": "^7.1.1" } } diff --git a/e2e/solid-router/basic-virtual-named-export-config-file-based/package.json b/e2e/solid-router/basic-virtual-named-export-config-file-based/package.json index 212cb73be7..6f57ade84c 100644 --- a/e2e/solid-router/basic-virtual-named-export-config-file-based/package.json +++ b/e2e/solid-router/basic-virtual-named-export-config-file-based/package.json @@ -25,7 +25,7 @@ "devDependencies": { "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "vite-plugin-solid": "^2.11.2", - "vite": "^6.3.5" + "vite-plugin-solid": "^2.11.8", + "vite": "^7.1.1" } } diff --git a/e2e/solid-router/basic/package.json b/e2e/solid-router/basic/package.json index 9634148185..930f065ce8 100644 --- a/e2e/solid-router/basic/package.json +++ b/e2e/solid-router/basic/package.json @@ -22,7 +22,7 @@ "devDependencies": { "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "vite-plugin-solid": "^2.11.2", - "vite": "^6.3.5" + "vite-plugin-solid": "^2.11.8", + "vite": "^7.1.1" } } diff --git a/e2e/solid-router/scroll-restoration-sandbox-vite/package.json b/e2e/solid-router/scroll-restoration-sandbox-vite/package.json index 8d41ebe795..c39283cc58 100644 --- a/e2e/solid-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/solid-router/scroll-restoration-sandbox-vite/package.json @@ -28,7 +28,7 @@ "devDependencies": { "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "vite-plugin-solid": "^2.11.2", - "vite": "^6.3.5" + "vite-plugin-solid": "^2.11.8", + "vite": "^7.1.1" } } diff --git a/e2e/solid-start/basic-tsr-config/package.json b/e2e/solid-start/basic-tsr-config/package.json index 97d12fa5ba..e94beef5ee 100644 --- a/e2e/solid-start/basic-tsr-config/package.json +++ b/e2e/solid-start/basic-tsr-config/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "rimraf ./count.txt && vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -15,12 +15,14 @@ "@tanstack/solid-router-devtools": "workspace:^", "@tanstack/solid-start": "workspace:^", "solid-js": "^1.9.5", - "vite": "6.3.5" + "vite": "^7.1.1" }, "devDependencies": { "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", + "srvx": "^0.8.6", "typescript": "^5.7.2", + "vite-plugin-solid": "^2.11.8", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/solid-start/basic-tsr-config/tests/app.spec.ts b/e2e/solid-start/basic-tsr-config/tests/app.spec.ts index e3488df952..782007684a 100644 --- a/e2e/solid-start/basic-tsr-config/tests/app.spec.ts +++ b/e2e/solid-start/basic-tsr-config/tests/app.spec.ts @@ -3,6 +3,7 @@ import { expect, test } from '@playwright/test' test('opening the app', async ({ page }) => { await page.goto('/') + await page.waitForLoadState('networkidle') await expect(page.getByTestId('add-button')).toContainText('Add 1 to 0?') await page.getByTestId('add-button').click() await page.waitForLoadState('networkidle') diff --git a/e2e/solid-start/basic-tsr-config/vite.config.ts b/e2e/solid-start/basic-tsr-config/vite.config.ts index 347962b83d..fa5673a503 100644 --- a/e2e/solid-start/basic-tsr-config/vite.config.ts +++ b/e2e/solid-start/basic-tsr-config/vite.config.ts @@ -1,6 +1,7 @@ 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: { @@ -11,9 +12,8 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart({ - tsr: { - srcDirectory: './src/app', - }, + srcDirectory: './src/app', }), + viteSolid({ ssr: true }), ], }) diff --git a/e2e/solid-start/basic/package.json b/e2e/solid-start/basic/package.json index c7b631c1d6..d3515f9eaf 100644 --- a/e2e/solid-start/basic/package.json +++ b/e2e/solid-start/basic/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -17,7 +17,7 @@ "redaxios": "^0.5.1", "solid-js": "^1.9.5", "tailwind-merge": "^2.6.0", - "vite": "6.3.5", + "vite": "^7.1.1", "zod": "^3.24.2" }, "devDependencies": { @@ -27,9 +27,10 @@ "autoprefixer": "^10.4.20", "combinate": "^1.1.11", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite-plugin-solid": "^2.11.2", + "vite-plugin-solid": "^2.11.8", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/solid-start/basic/src/server.ts b/e2e/solid-start/basic/src/server.ts index f9fbb3a2d5..dc9f547478 100644 --- a/e2e/solid-start/basic/src/server.ts +++ b/e2e/solid-start/basic/src/server.ts @@ -8,6 +8,10 @@ import { createRouter } from './router' console.log("[server-entry]: using custom server entry in 'src/server.ts'") -export default createStartHandler({ +const fetch = createStartHandler({ createRouter, })(defaultStreamHandler) + +export default { + fetch, +} diff --git a/e2e/solid-start/basic/tests/fixture.ts b/e2e/solid-start/basic/tests/fixture.ts deleted file mode 100644 index abb7b1d564..0000000000 --- a/e2e/solid-start/basic/tests/fixture.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { test as base, expect } from '@playwright/test' - -export interface TestFixtureOptions { - whitelistErrors: Array -} -export const test = base.extend({ - whitelistErrors: [[], { option: true }], - page: async ({ page, whitelistErrors }, use) => { - const errorMessages: Array = [] - page.on('console', (m) => { - if (m.type() === 'error') { - const text = m.text() - for (const whitelistError of whitelistErrors) { - if ( - (typeof whitelistError === 'string' && - text.includes(whitelistError)) || - (whitelistError instanceof RegExp && whitelistError.test(text)) - ) { - return - } - } - errorMessages.push(text) - } - }) - await use(page) - expect(errorMessages).toEqual([]) - }, -}) diff --git a/e2e/solid-start/basic/tests/navigation.spec.ts b/e2e/solid-start/basic/tests/navigation.spec.ts index 5d21f2adbe..b73d4ddf09 100644 --- a/e2e/solid-start/basic/tests/navigation.spec.ts +++ b/e2e/solid-start/basic/tests/navigation.spec.ts @@ -1,5 +1,11 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +test.use({ + whitelistErrors: [ + /Failed to load resource: the server responded with a status of 404/, + ], +}) test('Navigating to post', async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-start/basic/tests/not-found.spec.ts b/e2e/solid-start/basic/tests/not-found.spec.ts index 0d83ab5280..ab1c94eee9 100644 --- a/e2e/solid-start/basic/tests/not-found.spec.ts +++ b/e2e/solid-start/basic/tests/not-found.spec.ts @@ -1,6 +1,6 @@ import { expect } from '@playwright/test' import combinateImport from 'combinate' -import { test } from './fixture' +import { test } from '@tanstack/router-e2e-utils' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport diff --git a/e2e/solid-start/basic/tests/redirect.spec.ts b/e2e/solid-start/basic/tests/redirect.spec.ts index 87e93a42e6..78c57d6a00 100644 --- a/e2e/solid-start/basic/tests/redirect.spec.ts +++ b/e2e/solid-start/basic/tests/redirect.spec.ts @@ -4,9 +4,9 @@ import combinateImport from 'combinate' import { getDummyServerPort, getTestServerPort, + test, } from '@tanstack/router-e2e-utils' import packageJson from '../package.json' with { type: 'json' } -import { test } from './fixture' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport @@ -184,6 +184,8 @@ test.describe('redirects', () => { await page.goto(`/redirect/${target}/serverFn/via-useServerFn?${q}`) + await page.waitForLoadState('networkidle') + const button = page.getByTestId('redirect-on-click') let fullPageLoad = false diff --git a/e2e/solid-start/basic/tests/search-params.spec.ts b/e2e/solid-start/basic/tests/search-params.spec.ts index 23cd97517d..d7ce617890 100644 --- a/e2e/solid-start/basic/tests/search-params.spec.ts +++ b/e2e/solid-start/basic/tests/search-params.spec.ts @@ -1,5 +1,5 @@ import { expect } from '@playwright/test' -import { test } from './fixture' +import { test } from '@tanstack/router-e2e-utils' import type { Response } from '@playwright/test' function expectRedirect(response: Response | null, endsWith: string) { diff --git a/e2e/solid-start/basic/tests/streaming.spec.ts b/e2e/solid-start/basic/tests/streaming.spec.ts index 252bb192aa..15f60b7deb 100644 --- a/e2e/solid-start/basic/tests/streaming.spec.ts +++ b/e2e/solid-start/basic/tests/streaming.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' test('Navigating to deferred route', async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-start/basic/vite.config.ts b/e2e/solid-start/basic/vite.config.ts index 3af67d62ad..1a2219f443 100644 --- a/e2e/solid-start/basic/vite.config.ts +++ b/e2e/solid-start/basic/vite.config.ts @@ -1,6 +1,7 @@ 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: { @@ -10,6 +11,7 @@ export default defineConfig({ tsConfigPaths({ projects: ['./tsconfig.json'], }), - tanstackStart({}), + tanstackStart(), + viteSolid({ ssr: true }), ], }) diff --git a/e2e/solid-start/custom-basepath/express-server.ts b/e2e/solid-start/custom-basepath/express-server.ts new file mode 100644 index 0000000000..6fa802e447 --- /dev/null +++ b/e2e/solid-start/custom-basepath/express-server.ts @@ -0,0 +1,44 @@ +import express from 'express' +import { toNodeHandler } from 'srvx/node' + +const DEVELOPMENT = process.env.NODE_ENV === 'development' +const PORT = Number.parseInt(process.env.PORT || '3000') + +const app = express() + +if (DEVELOPMENT) { + const viteDevServer = await import('vite').then((vite) => + vite.createServer({ + server: { middlewareMode: true }, + }), + ) + app.use(viteDevServer.middlewares) + app.use(async (req, res, next) => { + try { + const { default: serverEntry } = + await viteDevServer.ssrLoadModule('./src/server.ts') + const handler = toNodeHandler(serverEntry.fetch) + await handler(req, res) + } catch (error) { + if (typeof error === 'object' && error instanceof Error) { + viteDevServer.ssrFixStacktrace(error) + } + next(error) + } + }) +} else { + const { default: handler } = await import('./dist/server/server.js') + const nodeHandler = toNodeHandler(handler.fetch) + app.use('/custom/basepath', express.static('dist/client')) + app.use(async (req, res, next) => { + try { + await nodeHandler(req, res) + } catch (error) { + next(error) + } + }) +} + +app.listen(PORT, () => { + console.log(`Server is running on http://localhost:${PORT}`) +}) diff --git a/e2e/solid-start/custom-basepath/package.json b/e2e/solid-start/custom-basepath/package.json index 1f668703a3..1b0755af31 100644 --- a/e2e/solid-start/custom-basepath/package.json +++ b/e2e/solid-start/custom-basepath/package.json @@ -4,32 +4,33 @@ "sideEffects": false, "type": "module", "scripts": { - "dev": "vite dev --port 3000", - "dev:e2e": "vite dev", + "dev": "cross-env NODE_ENV=development tsx express-server.ts", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "tsx express-server.ts", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-router": "workspace:^", "@tanstack/solid-router-devtools": "workspace:^", "@tanstack/solid-start": "workspace:^", + "express": "^4.21.2", "redaxios": "^0.5.1", - "solid-js": "^1.9.5", - "tailwind-merge": "^2.6.0", - "vite": "6.3.5", - "zod": "^3.24.2" + "solid-js": "^1.9.5" }, "devDependencies": { "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", + "@types/express": "^5.0.3", "@types/node": "^22.10.2", "autoprefixer": "^10.4.20", - "combinate": "^1.1.11", + "cross-env": "^10.0.0", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", + "tsx": "^4.20.3", "typescript": "^5.7.2", - "vite-plugin-solid": "^2.11.2", + "vite": "^7.1.1", + "vite-plugin-solid": "^2.11.8", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/solid-start/custom-basepath/src/server.ts b/e2e/solid-start/custom-basepath/src/server.ts new file mode 100644 index 0000000000..d54db7edf0 --- /dev/null +++ b/e2e/solid-start/custom-basepath/src/server.ts @@ -0,0 +1,14 @@ +import { + createStartHandler, + defaultStreamHandler, +} from '@tanstack/solid-start/server' + +import { createRouter } from './router' + +const fetch = createStartHandler({ + createRouter, +})(defaultStreamHandler) + +export default { + fetch, +} diff --git a/e2e/solid-start/custom-basepath/vite.config.ts b/e2e/solid-start/custom-basepath/vite.config.ts index d6784f657c..4f0310eddf 100644 --- a/e2e/solid-start/custom-basepath/vite.config.ts +++ b/e2e/solid-start/custom-basepath/vite.config.ts @@ -1,6 +1,7 @@ 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({ base: '/custom/basepath', @@ -11,6 +12,7 @@ export default defineConfig({ tsConfigPaths({ projects: ['./tsconfig.json'], }), - tanstackStart({}), + tanstackStart(), + viteSolid({ ssr: true }), ], }) diff --git a/e2e/solid-start/scroll-restoration/package.json b/e2e/solid-start/scroll-restoration/package.json index 60f64e7d04..8527fa97e4 100644 --- a/e2e/solid-start/scroll-restoration/package.json +++ b/e2e/solid-start/scroll-restoration/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -18,7 +18,7 @@ "redaxios": "^0.5.1", "solid-js": "^1.9.5", "tailwind-merge": "^2.6.0", - "vite": "6.3.5", + "vite": "^7.1.1", "zod": "^3.24.2" }, "devDependencies": { @@ -28,9 +28,10 @@ "autoprefixer": "^10.4.20", "combinate": "^1.1.11", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite-plugin-solid": "^2.11.6", + "vite-plugin-solid": "^2.11.8", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/solid-start/scroll-restoration/vite.config.ts b/e2e/solid-start/scroll-restoration/vite.config.ts index 3af67d62ad..1a2219f443 100644 --- a/e2e/solid-start/scroll-restoration/vite.config.ts +++ b/e2e/solid-start/scroll-restoration/vite.config.ts @@ -1,6 +1,7 @@ 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: { @@ -10,6 +11,7 @@ export default defineConfig({ tsConfigPaths({ projects: ['./tsconfig.json'], }), - tanstackStart({}), + tanstackStart(), + viteSolid({ ssr: true }), ], }) diff --git a/e2e/solid-start/selective-ssr/package.json b/e2e/solid-start/selective-ssr/package.json index 3be0fee142..67a902cfe2 100644 --- a/e2e/solid-start/selective-ssr/package.json +++ b/e2e/solid-start/selective-ssr/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -19,9 +19,11 @@ "devDependencies": { "@tanstack/router-e2e-utils": "workspace:^", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", + "vite-plugin-solid": "^2.11.8", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/solid-start/selective-ssr/tests/app.spec.ts b/e2e/solid-start/selective-ssr/tests/app.spec.ts index b013dfb169..aea216d506 100644 --- a/e2e/solid-start/selective-ssr/tests/app.spec.ts +++ b/e2e/solid-start/selective-ssr/tests/app.spec.ts @@ -1,5 +1,5 @@ import { expect } from '@playwright/test' -import { test } from './fixture' +import { test } from '@tanstack/router-e2e-utils' const testCount = 7 diff --git a/e2e/solid-start/selective-ssr/tests/fixture.ts b/e2e/solid-start/selective-ssr/tests/fixture.ts deleted file mode 100644 index abb7b1d564..0000000000 --- a/e2e/solid-start/selective-ssr/tests/fixture.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { test as base, expect } from '@playwright/test' - -export interface TestFixtureOptions { - whitelistErrors: Array -} -export const test = base.extend({ - whitelistErrors: [[], { option: true }], - page: async ({ page, whitelistErrors }, use) => { - const errorMessages: Array = [] - page.on('console', (m) => { - if (m.type() === 'error') { - const text = m.text() - for (const whitelistError of whitelistErrors) { - if ( - (typeof whitelistError === 'string' && - text.includes(whitelistError)) || - (whitelistError instanceof RegExp && whitelistError.test(text)) - ) { - return - } - } - errorMessages.push(text) - } - }) - await use(page) - expect(errorMessages).toEqual([]) - }, -}) diff --git a/e2e/solid-start/selective-ssr/vite.config.ts b/e2e/solid-start/selective-ssr/vite.config.ts index 151f2248f8..20ffdb3d6e 100644 --- a/e2e/solid-start/selective-ssr/vite.config.ts +++ b/e2e/solid-start/selective-ssr/vite.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from 'vite' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import tsConfigPaths from 'vite-tsconfig-paths' +import viteSolid from 'vite-plugin-solid' export default defineConfig({ server: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteSolid({ ssr: true }), ], }) diff --git a/e2e/solid-start/server-functions/package.json b/e2e/solid-start/server-functions/package.json index 7a02e8266e..fb3d649934 100644 --- a/e2e/solid-start/server-functions/package.json +++ b/e2e/solid-start/server-functions/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -18,7 +18,7 @@ "redaxios": "^0.5.1", "solid-js": "^1.9.5", "tailwind-merge": "^2.6.0", - "vite": "6.3.5", + "vite": "^7.1.1", "zod": "^3.24.2" }, "devDependencies": { @@ -29,9 +29,10 @@ "autoprefixer": "^10.4.20", "combinate": "^1.1.11", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite-plugin-solid": "^2.11.6", + "vite-plugin-solid": "^2.11.8", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/solid-start/server-functions/src/routes/env-only.tsx b/e2e/solid-start/server-functions/src/routes/env-only.tsx index df8f08eed2..85bcae0f60 100644 --- a/e2e/solid-start/server-functions/src/routes/env-only.tsx +++ b/e2e/solid-start/server-functions/src/routes/env-only.tsx @@ -1,9 +1,13 @@ import { createFileRoute } from '@tanstack/solid-router' -import { clientOnly, createServerFn, serverOnly } from '@tanstack/solid-start' +import { + createClientOnlyFn, + createServerFn, + createServerOnlyFn, +} from '@tanstack/solid-start' import { createSignal } from 'solid-js' -const serverEcho = serverOnly((input: string) => 'server got: ' + input) -const clientEcho = clientOnly((input: string) => 'client got: ' + input) +const serverEcho = createServerOnlyFn((input: string) => 'server got: ' + input) +const clientEcho = createClientOnlyFn((input: string) => 'client got: ' + input) const testOnServer = createServerFn().handler(() => { const serverOnServer = serverEcho('hello') diff --git a/e2e/solid-start/server-functions/src/routes/headers.tsx b/e2e/solid-start/server-functions/src/routes/headers.tsx index 3b1ce8d499..132f304fbe 100644 --- a/e2e/solid-start/server-functions/src/routes/headers.tsx +++ b/e2e/solid-start/server-functions/src/routes/headers.tsx @@ -1,8 +1,11 @@ import { createFileRoute } from '@tanstack/solid-router' import * as Solid from 'solid-js' import { createServerFn } from '@tanstack/solid-start' -import { getHeaders, setHeader } from '@tanstack/solid-start/server' -import type { HTTPHeaderName } from '@tanstack/solid-start/server' +import { + getRequestHeaders, + setResponseHeader, +} from '@tanstack/solid-start/server' +import type { RequestHeaderName } from '@tanstack/solid-start/server' export const Route = createFileRoute('/headers')({ loader: async () => { @@ -17,17 +20,18 @@ export const Route = createFileRoute('/headers')({ }) export const getTestHeaders = createServerFn().handler(() => { - setHeader('x-test-header', 'test-value') + setResponseHeader('x-test-header', 'test-value') + const reqHeaders = Object.fromEntries(getRequestHeaders().entries()) return { - serverHeaders: getHeaders(), - headers: getHeaders(), + serverHeaders: reqHeaders, + headers: reqHeaders, } }) type TestHeadersResult = { - headers?: Partial> - serverHeaders?: Partial> + headers?: Partial> + serverHeaders?: Partial> } function ResponseHeaders({ diff --git a/e2e/solid-start/server-functions/src/routes/raw-response.tsx b/e2e/solid-start/server-functions/src/routes/raw-response.tsx index 24f95e2cd1..ad3cfdc419 100644 --- a/e2e/solid-start/server-functions/src/routes/raw-response.tsx +++ b/e2e/solid-start/server-functions/src/routes/raw-response.tsx @@ -8,7 +8,7 @@ export const Route = createFileRoute('/raw-response')({ }) const expectedValue = 'Hello from a server function!' -export const rawResponseFn = createServerFn({ response: 'raw' }).handler(() => { +export const rawResponseFn = createServerFn().handler(() => { return new Response(expectedValue) }) diff --git a/e2e/solid-start/server-functions/src/routes/serialize-form-data.tsx b/e2e/solid-start/server-functions/src/routes/serialize-form-data.tsx index 1973e9f7b9..aeaf80576c 100644 --- a/e2e/solid-start/server-functions/src/routes/serialize-form-data.tsx +++ b/e2e/solid-start/server-functions/src/routes/serialize-form-data.tsx @@ -11,7 +11,7 @@ const testValues = { __adder: 1, } -export const greetUser = createServerFn() +export const greetUser = createServerFn({ method: 'POST' }) .validator((data: FormData) => { if (!(data instanceof FormData)) { throw new Error('Invalid! FormData is required') diff --git a/e2e/solid-start/server-functions/src/routes/submit-post-formdata.tsx b/e2e/solid-start/server-functions/src/routes/submit-post-formdata.tsx index 3fb6ea356f..d9b8ed5588 100644 --- a/e2e/solid-start/server-functions/src/routes/submit-post-formdata.tsx +++ b/e2e/solid-start/server-functions/src/routes/submit-post-formdata.tsx @@ -9,7 +9,7 @@ const testValues = { name: 'Sean', } -export const greetUser = createServerFn({ method: 'POST', response: 'raw' }) +export const greetUser = createServerFn({ method: 'POST' }) .validator((data: FormData) => { if (!(data instanceof FormData)) { throw new Error('Invalid! FormData is required') diff --git a/e2e/solid-start/server-functions/tests/fixture.ts b/e2e/solid-start/server-functions/tests/fixture.ts deleted file mode 100644 index abb7b1d564..0000000000 --- a/e2e/solid-start/server-functions/tests/fixture.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { test as base, expect } from '@playwright/test' - -export interface TestFixtureOptions { - whitelistErrors: Array -} -export const test = base.extend({ - whitelistErrors: [[], { option: true }], - page: async ({ page, whitelistErrors }, use) => { - const errorMessages: Array = [] - page.on('console', (m) => { - if (m.type() === 'error') { - const text = m.text() - for (const whitelistError of whitelistErrors) { - if ( - (typeof whitelistError === 'string' && - text.includes(whitelistError)) || - (whitelistError instanceof RegExp && whitelistError.test(text)) - ) { - return - } - } - errorMessages.push(text) - } - }) - await use(page) - expect(errorMessages).toEqual([]) - }, -}) diff --git a/e2e/solid-start/server-functions/tests/server-functions.spec.ts b/e2e/solid-start/server-functions/tests/server-functions.spec.ts index 80c89004c5..2af3201cf4 100644 --- a/e2e/solid-start/server-functions/tests/server-functions.spec.ts +++ b/e2e/solid-start/server-functions/tests/server-functions.spec.ts @@ -1,5 +1,6 @@ import * as fs from 'node:fs' -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' import { PORT } from '../playwright.config' import type { Page } from '@playwright/test' @@ -11,16 +12,10 @@ test('invoking a server function with custom response status code', async ({ await page.waitForLoadState('networkidle') const requestPromise = new Promise((resolve) => { - page.on('response', async (response) => { + page.on('response', (response) => { expect(response.status()).toBe(225) expect(response.statusText()).toBe('hello') - expect(response.headers()['content-type']).toBe('application/json') - expect(await response.json()).toEqual( - expect.objectContaining({ - result: { hello: 'world' }, - context: {}, - }), - ) + expect(response.headers()['content-type']).toContain('application/json') resolve() }) }) @@ -122,11 +117,11 @@ test('env-only functions can only be called on the server or client respectively 'server got: hello', ) await expect(page.getByTestId('server-on-client')).toContainText( - 'serverEcho threw an error: serverOnly() functions can only be called on the server!', + 'serverEcho threw an error: createServerOnlyFn() functions can only be called on the server!', ) await expect(page.getByTestId('client-on-server')).toContainText( - 'clientEcho threw an error: clientOnly() functions can only be called on the client!', + 'clientEcho threw an error: createClientOnlyFn() functions can only be called on the client!', ) await expect(page.getByTestId('client-on-client')).toContainText( 'client got: hello', diff --git a/e2e/solid-start/server-functions/vite.config.ts b/e2e/solid-start/server-functions/vite.config.ts index bae1bfaad6..1a2219f443 100644 --- a/e2e/solid-start/server-functions/vite.config.ts +++ b/e2e/solid-start/server-functions/vite.config.ts @@ -1,6 +1,7 @@ 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: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteSolid({ ssr: true }), ], }) diff --git a/e2e/solid-start/server-routes/package.json b/e2e/solid-start/server-routes/package.json index c2bec1aa27..96a395f286 100644 --- a/e2e/solid-start/server-routes/package.json +++ b/e2e/solid-start/server-routes/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "playwright test --project=chromium" }, "dependencies": { @@ -18,7 +18,7 @@ "redaxios": "^0.5.1", "solid-js": "^1.9.5", "tailwind-merge": "^2.6.0", - "vite": "6.3.5", + "vite": "^7.1.1", "zod": "^3.24.2" }, "devDependencies": { @@ -29,9 +29,10 @@ "autoprefixer": "^10.4.20", "combinate": "^1.1.11", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite-plugin-solid": "^2.11.6", + "vite-plugin-solid": "^2.11.8", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/solid-start/server-routes/tests/fixture.ts b/e2e/solid-start/server-routes/tests/fixture.ts deleted file mode 100644 index abb7b1d564..0000000000 --- a/e2e/solid-start/server-routes/tests/fixture.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { test as base, expect } from '@playwright/test' - -export interface TestFixtureOptions { - whitelistErrors: Array -} -export const test = base.extend({ - whitelistErrors: [[], { option: true }], - page: async ({ page, whitelistErrors }, use) => { - const errorMessages: Array = [] - page.on('console', (m) => { - if (m.type() === 'error') { - const text = m.text() - for (const whitelistError of whitelistErrors) { - if ( - (typeof whitelistError === 'string' && - text.includes(whitelistError)) || - (whitelistError instanceof RegExp && whitelistError.test(text)) - ) { - return - } - } - errorMessages.push(text) - } - }) - await use(page) - expect(errorMessages).toEqual([]) - }, -}) diff --git a/e2e/solid-start/server-routes/tests/server-routes.spec.ts b/e2e/solid-start/server-routes/tests/server-routes.spec.ts index 098a40b2ef..33176a23fd 100644 --- a/e2e/solid-start/server-routes/tests/server-routes.spec.ts +++ b/e2e/solid-start/server-routes/tests/server-routes.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' test('merge-server-fn-middleware-context', async ({ page }) => { await page.goto('/merge-server-fn-middleware-context') diff --git a/e2e/solid-start/server-routes/vite.config.ts b/e2e/solid-start/server-routes/vite.config.ts index bae1bfaad6..1a2219f443 100644 --- a/e2e/solid-start/server-routes/vite.config.ts +++ b/e2e/solid-start/server-routes/vite.config.ts @@ -1,6 +1,7 @@ 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: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteSolid({ ssr: true }), ], }) diff --git a/e2e/solid-start/spa-mode/package.json b/e2e/solid-start/spa-mode/package.json index 74f862abcb..a0ffac57a5 100644 --- a/e2e/solid-start/spa-mode/package.json +++ b/e2e/solid-start/spa-mode/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "npx serve .output/public", + "start": "npx serve dist/client", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -22,7 +22,8 @@ "postcss": "^8.5.1", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite": "^6.3.5", - "vite-tsconfig-paths": "^5.1.4" + "vite": "^7.1.1", + "vite-tsconfig-paths": "^5.1.4", + "vite-plugin-solid": "^2.11.8" } } diff --git a/e2e/solid-start/spa-mode/tests/app.spec.ts b/e2e/solid-start/spa-mode/tests/app.spec.ts index 8970ec333c..c18a0ff65d 100644 --- a/e2e/solid-start/spa-mode/tests/app.spec.ts +++ b/e2e/solid-start/spa-mode/tests/app.spec.ts @@ -1,5 +1,5 @@ import { expect } from '@playwright/test' -import { test } from './fixture' +import { test } from '@tanstack/router-e2e-utils' import type { Page } from '@playwright/test' async function runTest( diff --git a/e2e/solid-start/spa-mode/tests/fixture.ts b/e2e/solid-start/spa-mode/tests/fixture.ts deleted file mode 100644 index abb7b1d564..0000000000 --- a/e2e/solid-start/spa-mode/tests/fixture.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { test as base, expect } from '@playwright/test' - -export interface TestFixtureOptions { - whitelistErrors: Array -} -export const test = base.extend({ - whitelistErrors: [[], { option: true }], - page: async ({ page, whitelistErrors }, use) => { - const errorMessages: Array = [] - page.on('console', (m) => { - if (m.type() === 'error') { - const text = m.text() - for (const whitelistError of whitelistErrors) { - if ( - (typeof whitelistError === 'string' && - text.includes(whitelistError)) || - (whitelistError instanceof RegExp && whitelistError.test(text)) - ) { - return - } - } - errorMessages.push(text) - } - }) - await use(page) - expect(errorMessages).toEqual([]) - }, -}) diff --git a/e2e/solid-start/spa-mode/vite.config.ts b/e2e/solid-start/spa-mode/vite.config.ts index f14e499525..3bad2df77e 100644 --- a/e2e/solid-start/spa-mode/vite.config.ts +++ b/e2e/solid-start/spa-mode/vite.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from 'vite' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import tsConfigPaths from 'vite-tsconfig-paths' +import viteSolid from 'vite-plugin-solid' export default defineConfig({ server: { @@ -25,5 +26,6 @@ export default defineConfig({ }, ], }), + viteSolid({ ssr: true }), ], }) diff --git a/e2e/solid-start/website/package.json b/e2e/solid-start/website/package.json index 383f3305db..0a60d4e5f6 100644 --- a/e2e/solid-start/website/package.json +++ b/e2e/solid-start/website/package.json @@ -7,7 +7,7 @@ "dev": "vite dev --port 3000", "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", - "start": "node .output/server/index.mjs", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { @@ -17,7 +17,7 @@ "redaxios": "^0.5.1", "solid-js": "^1.9.5", "tailwind-merge": "^2.6.0", - "vite": "6.3.5", + "vite": "^7.1.1", "zod": "^3.24.2" }, "devDependencies": { @@ -26,9 +26,10 @@ "@types/node": "^22.10.2", "autoprefixer": "^10.4.20", "postcss": "^8.5.1", + "srvx": "^0.8.6", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite-plugin-solid": "^2.11.6", + "vite-plugin-solid": "^2.11.8", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/solid-start/website/vite.config.ts b/e2e/solid-start/website/vite.config.ts index 3af67d62ad..1a2219f443 100644 --- a/e2e/solid-start/website/vite.config.ts +++ b/e2e/solid-start/website/vite.config.ts @@ -1,6 +1,7 @@ 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: { @@ -10,6 +11,7 @@ export default defineConfig({ tsConfigPaths({ projects: ['./tsconfig.json'], }), - tanstackStart({}), + tanstackStart(), + viteSolid({ ssr: true }), ], }) diff --git a/examples/react/authenticated-routes-firebase/package.json b/examples/react/authenticated-routes-firebase/package.json index c188e691b0..cca364824c 100644 --- a/examples/react/authenticated-routes-firebase/package.json +++ b/examples/react/authenticated-routes-firebase/package.json @@ -9,9 +9,9 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "autoprefixer": "^10.4.20", "firebase": "^11.4.0", "postcss": "^8.5.1", @@ -27,6 +27,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/authenticated-routes/package.json b/examples/react/authenticated-routes/package.json index df45f36d77..5c0b1691fa 100644 --- a/examples/react/authenticated-routes/package.json +++ b/examples/react/authenticated-routes/package.json @@ -9,9 +9,9 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -25,6 +25,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/basic-default-search-params/package.json b/examples/react/basic-default-search-params/package.json index 9995fbcfc8..c22dc6fa37 100644 --- a/examples/react/basic-default-search-params/package.json +++ b/examples/react/basic-default-search-params/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tanstack/react-query": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -25,6 +25,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/basic-devtools-panel/package.json b/examples/react/basic-devtools-panel/package.json index 0c7c7fafa6..5e064b3caa 100644 --- a/examples/react/basic-devtools-panel/package.json +++ b/examples/react/basic-devtools-panel/package.json @@ -9,8 +9,8 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "@tanstack/react-query-devtools": "^5.67.2", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -24,6 +24,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/basic-file-based/package.json b/examples/react/basic-file-based/package.json index fd25b3760d..9277927bca 100644 --- a/examples/react/basic-file-based/package.json +++ b/examples/react/basic-file-based/package.json @@ -9,9 +9,9 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -25,6 +25,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/basic-non-nested-devtools/package.json b/examples/react/basic-non-nested-devtools/package.json index db1696e610..9a75fdaf3d 100644 --- a/examples/react/basic-non-nested-devtools/package.json +++ b/examples/react/basic-non-nested-devtools/package.json @@ -9,8 +9,8 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -23,6 +23,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/basic-react-query-file-based/package.json b/examples/react/basic-react-query-file-based/package.json index 09048ede0e..1280ad7401 100644 --- a/examples/react/basic-react-query-file-based/package.json +++ b/examples/react/basic-react-query-file-based/package.json @@ -11,9 +11,9 @@ "dependencies": { "@tanstack/react-query": "^5.66.0", "@tanstack/react-query-devtools": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -27,6 +27,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/basic-react-query/package.json b/examples/react/basic-react-query/package.json index 013a903228..9c09531281 100644 --- a/examples/react/basic-react-query/package.json +++ b/examples/react/basic-react-query/package.json @@ -11,8 +11,8 @@ "dependencies": { "@tanstack/react-query": "^5.66.0", "@tanstack/react-query-devtools": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -25,6 +25,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/basic-ssr-file-based/package.json b/examples/react/basic-ssr-file-based/package.json index f3e413566b..0ec7a2312d 100644 --- a/examples/react/basic-ssr-file-based/package.json +++ b/examples/react/basic-ssr-file-based/package.json @@ -11,23 +11,22 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "compression": "^1.8.0", "express": "^4.21.2", "get-port": "^7.1.0", - "isbot": "^5.1.28", "node-fetch": "^3.3.2", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "@types/express": "^4.17.23", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.1", "@vitejs/plugin-react": "^4.5.2", "typescript": "^5.8.3", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/basic-ssr-streaming-file-based/package.json b/examples/react/basic-ssr-streaming-file-based/package.json index fc2d5dd213..2265755ae9 100644 --- a/examples/react/basic-ssr-streaming-file-based/package.json +++ b/examples/react/basic-ssr-streaming-file-based/package.json @@ -11,23 +11,22 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "compression": "^1.7.5", "express": "^4.21.2", "get-port": "^7.1.0", - "isbot": "^5.1.22", "node-fetch": "^3.3.2", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "@types/express": "^4.17.21", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.1", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/basic-virtual-file-based/package.json b/examples/react/basic-virtual-file-based/package.json index ca3aa4d328..c416011889 100644 --- a/examples/react/basic-virtual-file-based/package.json +++ b/examples/react/basic-virtual-file-based/package.json @@ -9,10 +9,10 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", - "@tanstack/virtual-file-routes": "^1.131.2", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", + "@tanstack/virtual-file-routes": "^1.132.0-alpha.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -26,6 +26,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/basic-virtual-inside-file-based/package.json b/examples/react/basic-virtual-inside-file-based/package.json index 2bea5afad5..67ef89992d 100644 --- a/examples/react/basic-virtual-inside-file-based/package.json +++ b/examples/react/basic-virtual-inside-file-based/package.json @@ -9,10 +9,10 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", - "@tanstack/virtual-file-routes": "^1.131.2", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", + "@tanstack/virtual-file-routes": "^1.132.0-alpha.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -26,6 +26,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/basic/package.json b/examples/react/basic/package.json index 17e33d6a3b..c0694bea00 100644 --- a/examples/react/basic/package.json +++ b/examples/react/basic/package.json @@ -9,8 +9,8 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -23,6 +23,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/deferred-data/package.json b/examples/react/deferred-data/package.json index d82b45ebcc..f676e6a04b 100644 --- a/examples/react/deferred-data/package.json +++ b/examples/react/deferred-data/package.json @@ -9,8 +9,8 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -24,6 +24,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/kitchen-sink-file-based/package.json b/examples/react/kitchen-sink-file-based/package.json index 115a136d0d..561162308c 100644 --- a/examples/react/kitchen-sink-file-based/package.json +++ b/examples/react/kitchen-sink-file-based/package.json @@ -9,9 +9,9 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -26,6 +26,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/kitchen-sink-react-query-file-based/package.json b/examples/react/kitchen-sink-react-query-file-based/package.json index 0ace315b74..d008d3974d 100644 --- a/examples/react/kitchen-sink-react-query-file-based/package.json +++ b/examples/react/kitchen-sink-react-query-file-based/package.json @@ -11,9 +11,9 @@ "dependencies": { "@tanstack/react-query": "^5.66.0", "@tanstack/react-query-devtools": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -28,6 +28,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/kitchen-sink-react-query/package.json b/examples/react/kitchen-sink-react-query/package.json index 6ccbefd8fc..15f9688e9e 100644 --- a/examples/react/kitchen-sink-react-query/package.json +++ b/examples/react/kitchen-sink-react-query/package.json @@ -11,8 +11,8 @@ "dependencies": { "@tanstack/react-query": "^5.66.0", "@tanstack/react-query-devtools": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -27,6 +27,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/kitchen-sink/package.json b/examples/react/kitchen-sink/package.json index 5ca9eac8a0..796b22d57e 100644 --- a/examples/react/kitchen-sink/package.json +++ b/examples/react/kitchen-sink/package.json @@ -9,8 +9,8 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -25,6 +25,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/large-file-based/package.json b/examples/react/large-file-based/package.json index a3d89e3cb5..c1e71e4510 100644 --- a/examples/react/large-file-based/package.json +++ b/examples/react/large-file-based/package.json @@ -12,9 +12,9 @@ }, "dependencies": { "@tanstack/react-query": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -28,6 +28,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/location-masking/package.json b/examples/react/location-masking/package.json index 51e609b293..1193092774 100644 --- a/examples/react/location-masking/package.json +++ b/examples/react/location-masking/package.json @@ -11,8 +11,8 @@ "dependencies": { "@radix-ui/react-dialog": "^1.1.6", "@tanstack/react-query": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -25,6 +25,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/navigation-blocking/package.json b/examples/react/navigation-blocking/package.json index add1b8a550..790ceda0a5 100644 --- a/examples/react/navigation-blocking/package.json +++ b/examples/react/navigation-blocking/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tanstack/react-query": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -24,6 +24,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/quickstart-esbuild-file-based/package.json b/examples/react/quickstart-esbuild-file-based/package.json index cdfcf5fb29..9edd98b7d6 100644 --- a/examples/react/quickstart-esbuild-file-based/package.json +++ b/examples/react/quickstart-esbuild-file-based/package.json @@ -9,9 +9,9 @@ "start": "dev" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/quickstart-file-based/package.json b/examples/react/quickstart-file-based/package.json index 299e78c6a1..143049b62f 100644 --- a/examples/react/quickstart-file-based/package.json +++ b/examples/react/quickstart-file-based/package.json @@ -9,9 +9,9 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -25,6 +25,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/quickstart-rspack-file-based/package.json b/examples/react/quickstart-rspack-file-based/package.json index 99cddefd26..31ef142e76 100644 --- a/examples/react/quickstart-rspack-file-based/package.json +++ b/examples/react/quickstart-rspack-file-based/package.json @@ -8,8 +8,8 @@ "preview": "rsbuild preview" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "postcss": "^8.5.1", @@ -19,7 +19,7 @@ "devDependencies": { "@rsbuild/core": "1.2.4", "@rsbuild/plugin-react": "1.1.0", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "typescript": "^5.6.2" diff --git a/examples/react/quickstart-webpack-file-based/package.json b/examples/react/quickstart-webpack-file-based/package.json index 765aecc25a..9e31afc36a 100644 --- a/examples/react/quickstart-webpack-file-based/package.json +++ b/examples/react/quickstart-webpack-file-based/package.json @@ -7,14 +7,14 @@ "build": "webpack build && tsc --noEmit" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { "@swc/core": "^1.10.15", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "html-webpack-plugin": "^5.6.3", diff --git a/examples/react/quickstart/package.json b/examples/react/quickstart/package.json index aaa3d9d055..5a1b753e8e 100644 --- a/examples/react/quickstart/package.json +++ b/examples/react/quickstart/package.json @@ -9,8 +9,8 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "postcss": "^8.5.1", @@ -22,6 +22,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/router-monorepo-react-query/package.json b/examples/react/router-monorepo-react-query/package.json index ca54061e3b..b7ef5299ed 100644 --- a/examples/react/router-monorepo-react-query/package.json +++ b/examples/react/router-monorepo-react-query/package.json @@ -12,9 +12,9 @@ "dependencies": { "@tanstack/react-query": "^5.66.0", "@tanstack/react-query-devtools": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -25,7 +25,7 @@ "@types/react-dom": "^19.0.3", "typescript": "^5.7.2", "@vitejs/plugin-react": "^4.3.4", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-plugin-dts": "^4.5.0" }, "keywords": [], diff --git a/examples/react/router-monorepo-react-query/packages/app/package.json b/examples/react/router-monorepo-react-query/packages/app/package.json index 3d0d06369f..05c292bb52 100644 --- a/examples/react/router-monorepo-react-query/packages/app/package.json +++ b/examples/react/router-monorepo-react-query/packages/app/package.json @@ -20,11 +20,11 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "postcss": "^8.5.1", "autoprefixer": "^10.4.20", "tailwindcss": "^3.4.17", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-plugin-dts": "^4.5.0" }, "nx": { diff --git a/examples/react/router-monorepo-react-query/packages/post-feature/package.json b/examples/react/router-monorepo-react-query/packages/post-feature/package.json index ef4700d04f..fc6532deeb 100644 --- a/examples/react/router-monorepo-react-query/packages/post-feature/package.json +++ b/examples/react/router-monorepo-react-query/packages/post-feature/package.json @@ -19,7 +19,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-plugin-dts": "^4.5.0" } } diff --git a/examples/react/router-monorepo-react-query/packages/post-query/package.json b/examples/react/router-monorepo-react-query/packages/post-query/package.json index 6f856efc89..89c813fc70 100644 --- a/examples/react/router-monorepo-react-query/packages/post-query/package.json +++ b/examples/react/router-monorepo-react-query/packages/post-query/package.json @@ -15,6 +15,6 @@ "devDependencies": { "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/router-monorepo-react-query/packages/router/package.json b/examples/react/router-monorepo-react-query/packages/router/package.json index 4186aec9ed..439d7ffd5c 100644 --- a/examples/react/router-monorepo-react-query/packages/router/package.json +++ b/examples/react/router-monorepo-react-query/packages/router/package.json @@ -8,10 +8,10 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.131.2", + "@tanstack/history": "^1.132.0-alpha.1", "@tanstack/react-query": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "@router-mono-react-query/post-query": "workspace:*", "redaxios": "^0.5.1", "zod": "^3.24.2", @@ -23,7 +23,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-plugin-dts": "^4.5.0" } } diff --git a/examples/react/router-monorepo-simple-lazy/package.json b/examples/react/router-monorepo-simple-lazy/package.json index d4a3029590..bc4f28ea3e 100644 --- a/examples/react/router-monorepo-simple-lazy/package.json +++ b/examples/react/router-monorepo-simple-lazy/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -21,7 +21,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-plugin-dts": "^4.5.0" }, "keywords": [], diff --git a/examples/react/router-monorepo-simple-lazy/packages/app/package.json b/examples/react/router-monorepo-simple-lazy/packages/app/package.json index 83b440dbfa..0bd7168af1 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/app/package.json @@ -19,11 +19,11 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "postcss": "^8.5.1", "autoprefixer": "^10.4.20", "tailwindcss": "^3.4.17", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-plugin-dts": "^4.5.0" }, "nx": { diff --git a/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json b/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json index 324c49737a..b241c9403e 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json @@ -26,7 +26,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-plugin-dts": "^4.5.0" } } diff --git a/examples/react/router-monorepo-simple-lazy/packages/router/package.json b/examples/react/router-monorepo-simple-lazy/packages/router/package.json index 6e117762ff..dd220b64bf 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/router/package.json @@ -8,9 +8,9 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.131.2", - "@tanstack/react-router": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/history": "^1.132.0-alpha.1", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "redaxios": "^0.5.1", "zod": "^3.24.2", "react": "^19.0.0", @@ -21,7 +21,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-plugin-dts": "^4.5.0" } } diff --git a/examples/react/router-monorepo-simple/package.json b/examples/react/router-monorepo-simple/package.json index 014b10473e..24c72be5c6 100644 --- a/examples/react/router-monorepo-simple/package.json +++ b/examples/react/router-monorepo-simple/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -21,7 +21,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-plugin-dts": "^4.5.0" }, "keywords": [], diff --git a/examples/react/router-monorepo-simple/packages/app/package.json b/examples/react/router-monorepo-simple/packages/app/package.json index f810d00600..5f9fdce472 100644 --- a/examples/react/router-monorepo-simple/packages/app/package.json +++ b/examples/react/router-monorepo-simple/packages/app/package.json @@ -19,8 +19,8 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "@tanstack/react-router-devtools": "^1.131.27", - "vite": "^6.3.5", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "vite": "^7.1.1", "postcss": "^8.5.1", "autoprefixer": "^10.4.20", "tailwindcss": "^3.4.17", diff --git a/examples/react/router-monorepo-simple/packages/post-feature/package.json b/examples/react/router-monorepo-simple/packages/post-feature/package.json index 2a5ff9288e..eaeb4539ff 100644 --- a/examples/react/router-monorepo-simple/packages/post-feature/package.json +++ b/examples/react/router-monorepo-simple/packages/post-feature/package.json @@ -17,7 +17,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-plugin-dts": "^4.5.0" } } diff --git a/examples/react/router-monorepo-simple/packages/router/package.json b/examples/react/router-monorepo-simple/packages/router/package.json index 3ed9caf884..06b4e659b0 100644 --- a/examples/react/router-monorepo-simple/packages/router/package.json +++ b/examples/react/router-monorepo-simple/packages/router/package.json @@ -8,9 +8,9 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.131.2", - "@tanstack/react-router": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/history": "^1.132.0-alpha.1", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "redaxios": "^0.5.1", "zod": "^3.24.2", "react": "^19.0.0", @@ -21,7 +21,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-plugin-dts": "^4.5.0" } } diff --git a/examples/react/scroll-restoration/package.json b/examples/react/scroll-restoration/package.json index fe1be853f1..730fcfbdbf 100644 --- a/examples/react/scroll-restoration/package.json +++ b/examples/react/scroll-restoration/package.json @@ -9,9 +9,9 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", "@tanstack/react-virtual": "^3.13.0", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "postcss": "^8.5.1", @@ -23,6 +23,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/search-validator-adapters/package.json b/examples/react/search-validator-adapters/package.json index e6bd20f7e2..d87bb0e321 100644 --- a/examples/react/search-validator-adapters/package.json +++ b/examples/react/search-validator-adapters/package.json @@ -10,13 +10,13 @@ "test:unit": "vitest" }, "dependencies": { - "@tanstack/arktype-adapter": "^1.131.27", + "@tanstack/arktype-adapter": "^1.132.0-alpha.16", "@tanstack/react-query": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", - "@tanstack/valibot-adapter": "^1.131.27", - "@tanstack/zod-adapter": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", + "@tanstack/valibot-adapter": "^1.132.0-alpha.16", + "@tanstack/zod-adapter": "^1.132.0-alpha.16", "arktype": "^2.1.7", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -33,6 +33,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/start-bare/package.json b/examples/react/start-bare/package.json index 08e46031e5..8c7cf0292b 100644 --- a/examples/react/start-bare/package.json +++ b/examples/react/start-bare/package.json @@ -9,9 +9,9 @@ "start": "vite start" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/react-start": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/react-start": "^1.132.0-alpha.17", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^3.24.2" @@ -20,8 +20,9 @@ "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/react/start-bare/vite.config.ts b/examples/react/start-bare/vite.config.ts index 1f5fd1961a..f10c86e79f 100644 --- a/examples/react/start-bare/vite.config.ts +++ b/examples/react/start-bare/vite.config.ts @@ -1,6 +1,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/examples/react/start-basic-auth/package.json b/examples/react/start-basic-auth/package.json index 427828eee7..af5d59ff95 100644 --- a/examples/react/start-basic-auth/package.json +++ b/examples/react/start-basic-auth/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@prisma/client": "5.22.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/react-start": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/react-start": "^1.132.0-alpha.17", "prisma": "^5.22.0", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -21,6 +21,7 @@ "tailwind-merge": "^2.6.0" }, "devDependencies": { + "@vitejs/plugin-react": "^4.3.4", "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", @@ -28,7 +29,7 @@ "autoprefixer": "^10.4.20", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/react/start-basic-auth/vite.config.ts b/examples/react/start-basic-auth/vite.config.ts index 1f5fd1961a..f10c86e79f 100644 --- a/examples/react/start-basic-auth/vite.config.ts +++ b/examples/react/start-basic-auth/vite.config.ts @@ -1,6 +1,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/examples/react/start-basic-react-query/package.json b/examples/react/start-basic-react-query/package.json index 262d1e9aa0..248ff3b79e 100644 --- a/examples/react/start-basic-react-query/package.json +++ b/examples/react/start-basic-react-query/package.json @@ -11,10 +11,10 @@ "dependencies": { "@tanstack/react-query": "^5.66.0", "@tanstack/react-query-devtools": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-ssr-query": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/react-start": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-ssr-query": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/react-start": "^1.132.0-alpha.17", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -24,11 +24,12 @@ "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^4.3.4", "postcss": "^8.5.1", "autoprefixer": "^10.4.20", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/react/start-basic-react-query/vite.config.ts b/examples/react/start-basic-react-query/vite.config.ts index 1f5fd1961a..f10c86e79f 100644 --- a/examples/react/start-basic-react-query/vite.config.ts +++ b/examples/react/start-basic-react-query/vite.config.ts @@ -1,6 +1,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/examples/react/start-basic-rsc/package.json b/examples/react/start-basic-rsc/package.json index 754091755d..9449a8d4f2 100644 --- a/examples/react/start-basic-rsc/package.json +++ b/examples/react/start-basic-rsc/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@babel/plugin-syntax-typescript": "^7.25.9", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/react-start": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/react-start": "^1.132.0-alpha.17", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -21,11 +21,12 @@ "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^4.3.4", "postcss": "^8.5.1", "autoprefixer": "^10.4.20", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" }, "overrides": { diff --git a/examples/react/start-basic-rsc/vite.config.ts b/examples/react/start-basic-rsc/vite.config.ts index 1f5fd1961a..f10c86e79f 100644 --- a/examples/react/start-basic-rsc/vite.config.ts +++ b/examples/react/start-basic-rsc/vite.config.ts @@ -1,6 +1,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/examples/react/start-basic-static/package.json b/examples/react/start-basic-static/package.json index 129c87e330..d484f74420 100644 --- a/examples/react/start-basic-static/package.json +++ b/examples/react/start-basic-static/package.json @@ -9,9 +9,10 @@ "start": "vite start" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/react-start": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/react-start": "^1.132.0-alpha.17", + "@tanstack/start-static-server-functions": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -25,7 +26,7 @@ "postcss": "^8.4.49", "tailwindcss": "^3.4.15", "typescript": "^5.6.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.3" } } diff --git a/examples/react/start-basic-static/src/routes/deferred.tsx b/examples/react/start-basic-static/src/routes/deferred.tsx index e59a871e7b..07810ddc39 100644 --- a/examples/react/start-basic-static/src/routes/deferred.tsx +++ b/examples/react/start-basic-static/src/routes/deferred.tsx @@ -1,14 +1,17 @@ import { Await, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' import { Suspense, useState } from 'react' +import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' -const personServerFn = createServerFn({ method: 'GET', type: 'static' }) +const personServerFn = createServerFn({ method: 'GET' }) + .middleware([staticFunctionMiddleware]) .validator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) -const slowServerFn = createServerFn({ method: 'GET', type: 'static' }) +const slowServerFn = createServerFn({ method: 'GET' }) + .middleware([staticFunctionMiddleware]) .validator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) diff --git a/examples/react/start-basic-static/src/routes/users.$userId.tsx b/examples/react/start-basic-static/src/routes/users.$userId.tsx index d166885e29..2d2d32279d 100644 --- a/examples/react/start-basic-static/src/routes/users.$userId.tsx +++ b/examples/react/start-basic-static/src/routes/users.$userId.tsx @@ -4,8 +4,10 @@ import { createServerFn } from '@tanstack/react-start' import type { ErrorComponentProps } from '@tanstack/react-router' import type { User } from '~/utils/users' import { NotFound } from '~/components/NotFound' +import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' -const fetchUser = createServerFn({ method: 'GET', type: 'static' }) +const fetchUser = createServerFn({ method: 'GET' }) + .middleware([staticFunctionMiddleware]) .validator((d: string) => d) .handler(async ({ data: userId }) => { return axios diff --git a/examples/react/start-basic-static/src/routes/users.tsx b/examples/react/start-basic-static/src/routes/users.tsx index 95eeacaf63..98fb79518b 100644 --- a/examples/react/start-basic-static/src/routes/users.tsx +++ b/examples/react/start-basic-static/src/routes/users.tsx @@ -2,9 +2,11 @@ import { Link, Outlet, createFileRoute } from '@tanstack/react-router' import axios from 'redaxios' import { createServerFn } from '@tanstack/react-start' import type { User } from '../utils/users' +import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' -const fetchUsers = createServerFn({ method: 'GET', type: 'static' }).handler( - async () => { +const fetchUsers = createServerFn({ method: 'GET' }) + .middleware([staticFunctionMiddleware]) + .handler(async () => { console.info('Fetching users...') const res = await axios.get>( 'https://jsonplaceholder.typicode.com/users', @@ -13,8 +15,7 @@ const fetchUsers = createServerFn({ method: 'GET', type: 'static' }).handler( return res.data .slice(0, 10) .map((u) => ({ id: u.id, name: u.name, email: u.email })) - }, -) + }) export const Route = createFileRoute('/users')({ loader: async () => fetchUsers(), diff --git a/examples/react/start-basic-static/src/utils/posts.tsx b/examples/react/start-basic-static/src/utils/posts.tsx index 79f52eea47..82e568ceef 100644 --- a/examples/react/start-basic-static/src/utils/posts.tsx +++ b/examples/react/start-basic-static/src/utils/posts.tsx @@ -2,6 +2,7 @@ import { createServerFn } from '@tanstack/react-start' import axios from 'redaxios' import { notFound } from '@tanstack/react-router' import { logMiddleware } from './loggingMiddleware' +import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' export type PostType = { id: string @@ -9,8 +10,8 @@ export type PostType = { body: string } -export const fetchPost = createServerFn({ method: 'GET', type: 'static' }) - .middleware([logMiddleware]) +export const fetchPost = createServerFn({ method: 'GET' }) + .middleware([logMiddleware, staticFunctionMiddleware]) .validator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) @@ -27,8 +28,8 @@ export const fetchPost = createServerFn({ method: 'GET', type: 'static' }) return post }) -export const fetchPosts = createServerFn({ method: 'GET', type: 'static' }) - .middleware([logMiddleware]) +export const fetchPosts = createServerFn({ method: 'GET' }) + .middleware([logMiddleware, staticFunctionMiddleware]) .handler(async () => { console.info('Fetching posts...') return axios diff --git a/examples/react/start-basic-static/vite.config.ts b/examples/react/start-basic-static/vite.config.ts index 303ac171c9..07451c7d66 100644 --- a/examples/react/start-basic-static/vite.config.ts +++ b/examples/react/start-basic-static/vite.config.ts @@ -20,6 +20,9 @@ export default defineConfig({ sitemap: { host: 'https://localhost:3000', }, + prerender: { + failOnError: false, + }, }), ], }) diff --git a/examples/react/start-basic/package.json b/examples/react/start-basic/package.json index 819bc12fe5..aacbbd48c3 100644 --- a/examples/react/start-basic/package.json +++ b/examples/react/start-basic/package.json @@ -9,9 +9,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/react-start": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/react-start": "^1.132.0-alpha.17", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwind-merge": "^2.6.0", @@ -26,7 +26,7 @@ "postcss": "^8.5.1", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/react/start-basic/src/routes/index.tsx b/examples/react/start-basic/src/routes/index.tsx index 37c8d237bd..9be4870863 100644 --- a/examples/react/start-basic/src/routes/index.tsx +++ b/examples/react/start-basic/src/routes/index.tsx @@ -1,5 +1,44 @@ import { createFileRoute } from '@tanstack/react-router' + export const Route = createFileRoute('/')({ + server: { + // handlers: ({ createHandlers }) => + // createHandlers({ + // GET: ({ next }) => { + // return next({ + // context: { + // test: true, + // }, + // }) + // }, + // POST: ({ next }) => { + // return next({ + // context: { + // wrong: true, + // }, + // }) + // }, + // }), + handlers: { + GET: ({ next }) => { + return next({ + context: { + test: true, + }, + }) + }, + POST: ({ next }) => { + return next({ + context: { + wrong: true, + }, + }) + }, + }, + }, + beforeLoad: (ctx) => { + ctx.serverContext + }, component: Home, }) diff --git a/examples/react/start-basic/vite.config.ts b/examples/react/start-basic/vite.config.ts index 70067dfa49..f10c86e79f 100644 --- a/examples/react/start-basic/vite.config.ts +++ b/examples/react/start-basic/vite.config.ts @@ -11,7 +11,7 @@ export default defineConfig({ tsConfigPaths({ projects: ['./tsconfig.json'], }), - tanstackStart({ customViteReactPlugin: true }), + tanstackStart(), viteReact(), ], }) diff --git a/examples/react/start-clerk-basic/package.json b/examples/react/start-clerk-basic/package.json index 8a0e5a1262..4c663752a0 100644 --- a/examples/react/start-clerk-basic/package.json +++ b/examples/react/start-clerk-basic/package.json @@ -10,9 +10,10 @@ }, "dependencies": { "@clerk/tanstack-react-start": "^0.19.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/react-start": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/react-start": "^1.132.0-alpha.17", + "@vitejs/plugin-react": "^4.3.4", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -26,7 +27,7 @@ "autoprefixer": "^10.4.20", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/react/start-clerk-basic/src/routes/__root.tsx b/examples/react/start-clerk-basic/src/routes/__root.tsx index 1842003cea..80ce274116 100644 --- a/examples/react/start-clerk-basic/src/routes/__root.tsx +++ b/examples/react/start-clerk-basic/src/routes/__root.tsx @@ -17,13 +17,13 @@ import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' import { createServerFn } from '@tanstack/react-start' import * as React from 'react' import { getAuth } from '@clerk/tanstack-react-start/server' -import { getWebRequest } from '@tanstack/react-start/server' +import { getRequest } from '@tanstack/react-start/server' import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' const fetchClerkAuth = createServerFn({ method: 'GET' }).handler(async () => { - const { userId } = await getAuth(getWebRequest()!) + const { userId } = await getAuth(getRequest()) return { userId, diff --git a/examples/react/start-clerk-basic/src/server.ts b/examples/react/start-clerk-basic/src/server.ts index 7fb77bd8cb..116dda52ff 100644 --- a/examples/react/start-clerk-basic/src/server.ts +++ b/examples/react/start-clerk-basic/src/server.ts @@ -11,4 +11,6 @@ const handler = createStartHandler({ const clerkHandler = createClerkHandler(handler) -export default clerkHandler(defaultStreamHandler) +export default { + fetch: clerkHandler(defaultStreamHandler), +} diff --git a/examples/react/start-clerk-basic/vite.config.ts b/examples/react/start-clerk-basic/vite.config.ts index 1f5fd1961a..f10c86e79f 100644 --- a/examples/react/start-clerk-basic/vite.config.ts +++ b/examples/react/start-clerk-basic/vite.config.ts @@ -1,6 +1,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/examples/react/start-convex-trellaux/package.json b/examples/react/start-convex-trellaux/package.json index 0791371413..c94ea2c130 100644 --- a/examples/react/start-convex-trellaux/package.json +++ b/examples/react/start-convex-trellaux/package.json @@ -14,10 +14,10 @@ "@convex-dev/react-query": "0.0.0-alpha.8", "@tanstack/react-query": "^5.66.0", "@tanstack/react-query-devtools": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-ssr-query": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/react-start": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-ssr-query": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/react-start": "^1.132.0-alpha.17", "concurrently": "^8.2.2", "convex": "^1.19.0", "ky": "^1.7.4", @@ -33,11 +33,12 @@ "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^4.3.4", "postcss": "^8.5.1", "autoprefixer": "^10.4.20", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/react/start-convex-trellaux/vite.config.ts b/examples/react/start-convex-trellaux/vite.config.ts index 1f5fd1961a..f10c86e79f 100644 --- a/examples/react/start-convex-trellaux/vite.config.ts +++ b/examples/react/start-convex-trellaux/vite.config.ts @@ -1,6 +1,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/examples/react/start-counter/package.json b/examples/react/start-counter/package.json index acbea16c31..4576b8b61b 100644 --- a/examples/react/start-counter/package.json +++ b/examples/react/start-counter/package.json @@ -9,9 +9,9 @@ "start": "vite start" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/react-start": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/react-start": "^1.132.0-alpha.17", "react": "^19.0.0", "react-dom": "^19.0.0" }, @@ -19,7 +19,8 @@ "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/start-counter/vite.config.ts b/examples/react/start-counter/vite.config.ts index 86790438cf..bae3acaefe 100644 --- a/examples/react/start-counter/vite.config.ts +++ b/examples/react/start-counter/vite.config.ts @@ -1,9 +1,10 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { port: 3000, }, - plugins: [tanstackStart()], + plugins: [tanstackStart(), viteReact()], }) diff --git a/examples/react/start-large/package.json b/examples/react/start-large/package.json index 5cc9131bcc..ad9ab6dbd4 100644 --- a/examples/react/start-large/package.json +++ b/examples/react/start-large/package.json @@ -12,9 +12,9 @@ }, "dependencies": { "@tanstack/react-query": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/react-start": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/react-start": "^1.132.0-alpha.17", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -25,11 +25,12 @@ "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^4.3.4", "postcss": "^8.5.1", "autoprefixer": "^10.4.20", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" }, "keywords": [], diff --git a/examples/react/start-large/src/routes/search/searchPlaceholder.tsx b/examples/react/start-large/src/routes/search/searchPlaceholder.tsx index eb7f95c39a..f16813520f 100644 --- a/examples/react/start-large/src/routes/search/searchPlaceholder.tsx +++ b/examples/react/start-large/src/routes/search/searchPlaceholder.tsx @@ -68,7 +68,6 @@ export const Route = createFileRoute('/search/searchPlaceholder')({ return { search, - external, } }, }) diff --git a/examples/react/start-large/vite.config.ts b/examples/react/start-large/vite.config.ts index 1f5fd1961a..f10c86e79f 100644 --- a/examples/react/start-large/vite.config.ts +++ b/examples/react/start-large/vite.config.ts @@ -1,6 +1,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/examples/react/start-material-ui/package.json b/examples/react/start-material-ui/package.json index a83f3644ee..406f6a2a2a 100644 --- a/examples/react/start-material-ui/package.json +++ b/examples/react/start-material-ui/package.json @@ -14,9 +14,9 @@ "@emotion/styled": "11.14.0", "@fontsource-variable/roboto": "5.2.5", "@mui/material": "6.4.7", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-start": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-start": "^1.132.0-alpha.17", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^3.24.2" @@ -25,8 +25,9 @@ "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/react/start-material-ui/vite.config.ts b/examples/react/start-material-ui/vite.config.ts index 1c59bcc8f9..5bd46872f1 100644 --- a/examples/react/start-material-ui/vite.config.ts +++ b/examples/react/start-material-ui/vite.config.ts @@ -1,6 +1,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { @@ -14,5 +15,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/examples/react/start-supabase-basic/package.json b/examples/react/start-supabase-basic/package.json index 91cccdd0a8..e43eabe6ad 100644 --- a/examples/react/start-supabase-basic/package.json +++ b/examples/react/start-supabase-basic/package.json @@ -15,9 +15,9 @@ "dependencies": { "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.48.1", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/react-start": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/react-start": "^1.132.0-alpha.17", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -25,11 +25,12 @@ "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^4.3.4", "autoprefixer": "^10.4.20", "postcss": "^8.5.1", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/react/start-supabase-basic/src/utils/supabase.ts b/examples/react/start-supabase-basic/src/utils/supabase.ts index 39ad47a8fa..b06ffb81cd 100644 --- a/examples/react/start-supabase-basic/src/utils/supabase.ts +++ b/examples/react/start-supabase-basic/src/utils/supabase.ts @@ -1,4 +1,4 @@ -import { parseCookies, setCookie } from '@tanstack/react-start/server' +import { getCookies, setCookie } from '@tanstack/react-start/server' import { createServerClient } from '@supabase/ssr' export function getSupabaseServerClient() { @@ -8,7 +8,7 @@ export function getSupabaseServerClient() { { cookies: { getAll() { - return Object.entries(parseCookies()).map(([name, value]) => ({ + return Object.entries(getCookies()).map(([name, value]) => ({ name, value, })) diff --git a/examples/react/start-supabase-basic/vite.config.ts b/examples/react/start-supabase-basic/vite.config.ts index 1f5fd1961a..f10c86e79f 100644 --- a/examples/react/start-supabase-basic/vite.config.ts +++ b/examples/react/start-supabase-basic/vite.config.ts @@ -1,6 +1,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/examples/react/start-tailwind-v4/package.json b/examples/react/start-tailwind-v4/package.json index ae924e84a5..152ecb8dfb 100644 --- a/examples/react/start-tailwind-v4/package.json +++ b/examples/react/start-tailwind-v4/package.json @@ -9,9 +9,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/react-start": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/react-start": "^1.132.0-alpha.17", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwind-merge": "^2.6.0", @@ -22,9 +22,10 @@ "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^4.3.4", "tailwindcss": "^4.1.6", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/react/start-tailwind-v4/vite.config.ts b/examples/react/start-tailwind-v4/vite.config.ts index 6a8f14e7c0..360b4f7dda 100644 --- a/examples/react/start-tailwind-v4/vite.config.ts +++ b/examples/react/start-tailwind-v4/vite.config.ts @@ -2,6 +2,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' import tailwindcss from '@tailwindcss/vite' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { @@ -12,6 +13,7 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), tailwindcss(), ], }) diff --git a/examples/react/start-trellaux/package.json b/examples/react/start-trellaux/package.json index 58ae9ca86f..21ef9ce804 100644 --- a/examples/react/start-trellaux/package.json +++ b/examples/react/start-trellaux/package.json @@ -11,10 +11,10 @@ "dependencies": { "@tanstack/react-query": "^5.66.0", "@tanstack/react-query-devtools": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-ssr-query": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/react-start": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-ssr-query": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/react-start": "^1.132.0-alpha.17", "ky": "^1.7.4", "msw": "^2.7.0", "react": "^19.0.0", @@ -28,11 +28,12 @@ "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^4.3.4", "postcss": "^8.5.1", "autoprefixer": "^10.4.20", "tailwindcss": "^3.4.17", "typescript": "^5.6.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/react/start-trellaux/vite.config.ts b/examples/react/start-trellaux/vite.config.ts index 1f5fd1961a..f10c86e79f 100644 --- a/examples/react/start-trellaux/vite.config.ts +++ b/examples/react/start-trellaux/vite.config.ts @@ -1,6 +1,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }) diff --git a/examples/react/start-workos/package.json b/examples/react/start-workos/package.json index 7cda059ff2..5b4647ddaf 100644 --- a/examples/react/start-workos/package.json +++ b/examples/react/start-workos/package.json @@ -14,9 +14,9 @@ "license": "MIT", "dependencies": { "@radix-ui/themes": "^3.2.1", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/react-start": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/react-start": "^1.132.0-alpha.17", "@workos-inc/node": "^7.45.0", "iron-session": "^8.0.4", "jose": "^6.0.10", @@ -26,11 +26,12 @@ "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^4.3.4", "postcss": "^8.5.1", "autoprefixer": "^10.4.20", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/react/start-workos/src/authkit/serverFunctions.ts b/examples/react/start-workos/src/authkit/serverFunctions.ts index 8ce62c746b..f41ddb9dd0 100644 --- a/examples/react/start-workos/src/authkit/serverFunctions.ts +++ b/examples/react/start-workos/src/authkit/serverFunctions.ts @@ -31,7 +31,7 @@ export const getSignUpUrl = createServerFn({ method: 'GET' }) return getAuthorizationUrl({ data: { returnPathname, screenHint: 'sign-up' } }); }); -export const signOut = createServerFn({ method: 'POST', response: 'full' }) +export const signOut = createServerFn({ method: 'POST' }) .validator((data?: string) => data) .handler(async ({ data: returnTo }) => { const cookieName = getConfig('cookieName') || 'wos_session'; diff --git a/examples/react/start-workos/src/routes/logout.tsx b/examples/react/start-workos/src/routes/logout.tsx index 41e8bc0b88..401d6cbc99 100644 --- a/examples/react/start-workos/src/routes/logout.tsx +++ b/examples/react/start-workos/src/routes/logout.tsx @@ -3,5 +3,7 @@ import { signOut } from '../authkit/serverFunctions'; export const Route = createFileRoute('/logout')({ preload: false, - loader: () => signOut(), + loader: async () => { + await signOut(); + }, }); diff --git a/examples/react/start-workos/vite.config.ts b/examples/react/start-workos/vite.config.ts index cd888de96e..fce3baa54d 100644 --- a/examples/react/start-workos/vite.config.ts +++ b/examples/react/start-workos/vite.config.ts @@ -1,6 +1,7 @@ import { defineConfig } from 'vite'; import tsConfigPaths from 'vite-tsconfig-paths'; import { tanstackStart } from '@tanstack/react-start/plugin/vite'; +import viteReact from '@vitejs/plugin-react'; export default defineConfig({ server: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteReact(), ], }); diff --git a/examples/react/view-transitions/package.json b/examples/react/view-transitions/package.json index f5b7a3e8be..0b61ed45f7 100644 --- a/examples/react/view-transitions/package.json +++ b/examples/react/view-transitions/package.json @@ -9,9 +9,9 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -25,6 +25,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/with-framer-motion/package.json b/examples/react/with-framer-motion/package.json index 125088bd0b..aab23af817 100644 --- a/examples/react/with-framer-motion/package.json +++ b/examples/react/with-framer-motion/package.json @@ -9,8 +9,8 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", "framer-motion": "^11.18.2", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -25,6 +25,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/with-trpc-react-query/package.json b/examples/react/with-trpc-react-query/package.json index 7bdc7a81d1..58fcd45b08 100644 --- a/examples/react/with-trpc-react-query/package.json +++ b/examples/react/with-trpc-react-query/package.json @@ -12,9 +12,9 @@ "dependencies": { "@tanstack/react-query": "^5.66.0", "@tanstack/react-query-devtools": "^5.66.0", - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", "@trpc/tanstack-react-query": "^11.4.3", @@ -33,6 +33,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "tsx": "^4.20.3", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/with-trpc-react-query/src/server/server.ts b/examples/react/with-trpc-react-query/src/server/server.ts index 1f8b4a3c47..b2b3fd2485 100644 --- a/examples/react/with-trpc-react-query/src/server/server.ts +++ b/examples/react/with-trpc-react-query/src/server/server.ts @@ -24,7 +24,7 @@ export const createServer = async ( ) => { const app = express() - app.use('/trpc', trpcMiddleWare) + app.use('/trpc', trpcMiddleWare as any) if (!isProd) { const vite = await import('vite') diff --git a/examples/react/with-trpc/package.json b/examples/react/with-trpc/package.json index c70d3a3d99..c089fa2a76 100644 --- a/examples/react/with-trpc/package.json +++ b/examples/react/with-trpc/package.json @@ -10,9 +10,9 @@ "start": "NODE_ENV=production node dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.131.27", - "@tanstack/react-router-devtools": "^1.131.27", - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/react-router": "^1.132.0-alpha.16", + "@tanstack/react-router-devtools": "^1.132.0-alpha.16", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", "autoprefixer": "^10.4.20", @@ -30,6 +30,6 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "tsx": "^4.20.3", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/react/with-trpc/src/server/server.ts b/examples/react/with-trpc/src/server/server.ts index 1f8b4a3c47..b2b3fd2485 100644 --- a/examples/react/with-trpc/src/server/server.ts +++ b/examples/react/with-trpc/src/server/server.ts @@ -24,7 +24,7 @@ export const createServer = async ( ) => { const app = express() - app.use('/trpc', trpcMiddleWare) + app.use('/trpc', trpcMiddleWare as any) if (!isProd) { const vite = await import('vite') diff --git a/examples/solid/basic-devtools-panel/package.json b/examples/solid/basic-devtools-panel/package.json index 4ce5f54c2f..ff3d3d96a6 100644 --- a/examples/solid/basic-devtools-panel/package.json +++ b/examples/solid/basic-devtools-panel/package.json @@ -9,8 +9,8 @@ "start": "vite" }, "dependencies": { - "@tanstack/solid-router": "^1.131.27", - "@tanstack/solid-router-devtools": "^1.131.27", + "@tanstack/solid-router": "^1.132.0-alpha.16", + "@tanstack/solid-router-devtools": "^1.132.0-alpha.16", "solid-js": "^1.9.5", "redaxios": "^0.5.1", "postcss": "^8.5.1", @@ -18,8 +18,8 @@ "tailwindcss": "^3.4.17" }, "devDependencies": { - "vite-plugin-solid": "^2.11.6", + "vite-plugin-solid": "^2.11.8", "typescript": "^5.7.2", - "vite": "^6.3.5" + "vite": "^7.1.1" } } diff --git a/examples/solid/basic-file-based/package.json b/examples/solid/basic-file-based/package.json index 38fb420733..e6a310805c 100644 --- a/examples/solid/basic-file-based/package.json +++ b/examples/solid/basic-file-based/package.json @@ -9,8 +9,8 @@ "start": "vite" }, "dependencies": { - "@tanstack/solid-router": "^1.131.27", - "@tanstack/solid-router-devtools": "^1.131.27", + "@tanstack/solid-router": "^1.132.0-alpha.16", + "@tanstack/solid-router-devtools": "^1.132.0-alpha.16", "autoprefixer": "^10.4.20", "postcss": "^8.5.1", "redaxios": "^0.5.1", @@ -19,9 +19,9 @@ "zod": "^3.24.2" }, "devDependencies": { - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "typescript": "^5.7.2", - "vite": "^6.3.5", - "vite-plugin-solid": "^2.11.2" + "vite": "^7.1.1", + "vite-plugin-solid": "^2.11.8" } } diff --git a/examples/solid/basic-non-nested-devtools/package.json b/examples/solid/basic-non-nested-devtools/package.json index 8a6e98fffd..39b50aa810 100644 --- a/examples/solid/basic-non-nested-devtools/package.json +++ b/examples/solid/basic-non-nested-devtools/package.json @@ -9,8 +9,8 @@ "start": "vite" }, "dependencies": { - "@tanstack/solid-router": "^1.131.27", - "@tanstack/solid-router-devtools": "^1.131.27", + "@tanstack/solid-router": "^1.132.0-alpha.16", + "@tanstack/solid-router-devtools": "^1.132.0-alpha.16", "redaxios": "^0.5.1", "postcss": "^8.5.1", "solid-js": "^1.9.5", @@ -21,7 +21,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "typescript": "^5.7.2", - "vite": "^6.3.5", - "vite-plugin-solid": "^2.11.2" + "vite": "^7.1.1", + "vite-plugin-solid": "^2.11.8" } } diff --git a/examples/solid/basic-solid-query-file-based/package.json b/examples/solid/basic-solid-query-file-based/package.json index 9fd42f656d..561d7694ff 100644 --- a/examples/solid/basic-solid-query-file-based/package.json +++ b/examples/solid/basic-solid-query-file-based/package.json @@ -12,8 +12,8 @@ "dependencies": { "@tanstack/solid-query": "^5.71.9", "@tanstack/solid-query-devtools": "^5.71.9", - "@tanstack/solid-router": "^1.131.27", - "@tanstack/solid-router-devtools": "^1.131.27", + "@tanstack/solid-router": "^1.132.0-alpha.16", + "@tanstack/solid-router-devtools": "^1.132.0-alpha.16", "solid-js": "^1.9.5", "redaxios": "^0.5.1", "postcss": "^8.5.1", @@ -22,9 +22,9 @@ "zod": "^3.24.2" }, "devDependencies": { - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "typescript": "^5.7.2", - "vite": "^6.3.5", - "vite-plugin-solid": "^2.11.2" + "vite": "^7.1.1", + "vite-plugin-solid": "^2.11.8" } } diff --git a/examples/solid/basic-solid-query/package.json b/examples/solid/basic-solid-query/package.json index a8753480b6..e2e10ff53e 100644 --- a/examples/solid/basic-solid-query/package.json +++ b/examples/solid/basic-solid-query/package.json @@ -11,8 +11,8 @@ "dependencies": { "@tanstack/solid-query": "^5.71.9", "@tanstack/solid-query-devtools": "^5.71.9", - "@tanstack/solid-router": "^1.131.27", - "@tanstack/solid-router-devtools": "^1.131.27", + "@tanstack/solid-router": "^1.132.0-alpha.16", + "@tanstack/solid-router-devtools": "^1.132.0-alpha.16", "solid-js": "^1.9.5", "redaxios": "^0.5.1", "postcss": "^8.5.1", @@ -20,9 +20,9 @@ "tailwindcss": "^3.4.17" }, "devDependencies": { - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "typescript": "^5.7.2", - "vite": "^6.3.5", - "vite-plugin-solid": "^2.11.2" + "vite": "^7.1.1", + "vite-plugin-solid": "^2.11.8" } } diff --git a/examples/solid/basic-ssr-streaming-file-based/package.json b/examples/solid/basic-ssr-streaming-file-based/package.json index e510325686..4ce7b6b8d8 100644 --- a/examples/solid/basic-ssr-streaming-file-based/package.json +++ b/examples/solid/basic-ssr-streaming-file-based/package.json @@ -11,13 +11,12 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/solid-router": "^1.131.27", - "@tanstack/solid-router-devtools": "^1.131.27", + "@tanstack/solid-router": "^1.132.0-alpha.16", + "@tanstack/solid-router-devtools": "^1.132.0-alpha.16", "autoprefixer": "^10.4.20", "compression": "^1.7.5", "express": "^4.21.2", "get-port": "^7.1.0", - "isbot": "^5.1.22", "node-fetch": "^3.3.2", "postcss": "^8.5.1", "redaxios": "^0.5.1", @@ -26,10 +25,10 @@ "zod": "^3.24.2" }, "devDependencies": { - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "@types/express": "^4.17.21", "typescript": "^5.7.2", - "vite": "^6.3.5", - "vite-plugin-solid": "^2.11.2" + "vite": "^7.1.1", + "vite-plugin-solid": "^2.11.8" } } diff --git a/examples/solid/basic/package.json b/examples/solid/basic/package.json index bf87ae2799..7b9034d5a4 100644 --- a/examples/solid/basic/package.json +++ b/examples/solid/basic/package.json @@ -9,8 +9,8 @@ "start": "vite" }, "dependencies": { - "@tanstack/solid-router": "^1.131.27", - "@tanstack/solid-router-devtools": "^1.131.27", + "@tanstack/solid-router": "^1.132.0-alpha.16", + "@tanstack/solid-router-devtools": "^1.132.0-alpha.16", "redaxios": "^0.5.1", "postcss": "^8.5.1", "solid-js": "^1.9.5", @@ -21,7 +21,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "typescript": "^5.7.2", - "vite": "^6.3.5", - "vite-plugin-solid": "^2.11.2" + "vite": "^7.1.1", + "vite-plugin-solid": "^2.11.8" } } diff --git a/examples/solid/kitchen-sink-file-based/package.json b/examples/solid/kitchen-sink-file-based/package.json index 483d1f7acb..a4939956a9 100644 --- a/examples/solid/kitchen-sink-file-based/package.json +++ b/examples/solid/kitchen-sink-file-based/package.json @@ -9,8 +9,8 @@ "start": "vite" }, "dependencies": { - "@tanstack/solid-router": "^1.131.27", - "@tanstack/solid-router-devtools": "^1.131.27", + "@tanstack/solid-router": "^1.132.0-alpha.16", + "@tanstack/solid-router-devtools": "^1.132.0-alpha.16", "immer": "^10.1.1", "solid-js": "^1.9.5", "redaxios": "^0.5.1", @@ -20,9 +20,9 @@ "zod": "^3.24.2" }, "devDependencies": { - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "typescript": "^5.7.2", - "vite": "^6.3.5", - "vite-plugin-solid": "^2.11.2" + "vite": "^7.1.1", + "vite-plugin-solid": "^2.11.8" } } diff --git a/examples/solid/quickstart-file-based/package.json b/examples/solid/quickstart-file-based/package.json index 123e3178d7..3be0918270 100644 --- a/examples/solid/quickstart-file-based/package.json +++ b/examples/solid/quickstart-file-based/package.json @@ -9,8 +9,8 @@ "start": "vite" }, "dependencies": { - "@tanstack/solid-router": "^1.131.27", - "@tanstack/solid-router-devtools": "^1.131.27", + "@tanstack/solid-router": "^1.132.0-alpha.16", + "@tanstack/solid-router-devtools": "^1.132.0-alpha.16", "autoprefixer": "^10.4.20", "postcss": "^8.5.1", "redaxios": "^0.5.1", @@ -19,9 +19,9 @@ "zod": "^3.24.2" }, "devDependencies": { - "@tanstack/router-plugin": "^1.131.27", + "@tanstack/router-plugin": "^1.132.0-alpha.16", "typescript": "^5.7.2", - "vite": "^6.3.5", - "vite-plugin-solid": "^2.11.2" + "vite": "^7.1.1", + "vite-plugin-solid": "^2.11.8" } } diff --git a/examples/solid/start-bare/package.json b/examples/solid/start-bare/package.json index a4a46cc667..62e476fe69 100644 --- a/examples/solid/start-bare/package.json +++ b/examples/solid/start-bare/package.json @@ -9,9 +9,9 @@ "start": "vite start" }, "dependencies": { - "@tanstack/solid-router": "^1.131.27", - "@tanstack/solid-router-devtools": "^1.131.27", - "@tanstack/solid-start": "^1.131.27", + "@tanstack/solid-router": "^1.132.0-alpha.16", + "@tanstack/solid-router-devtools": "^1.132.0-alpha.16", + "@tanstack/solid-start": "^1.132.0-alpha.17", "solid-js": "^1.9.5", "redaxios": "^0.5.1", "tailwind-merge": "^2.6.0", @@ -19,10 +19,10 @@ }, "devDependencies": { "@types/node": "^22.10.2", - "vite-plugin-solid": "^2.11.2", + "vite-plugin-solid": "^2.11.8", "combinate": "^1.1.11", "typescript": "^5.7.2", - "vite": "^6.3.5", + "vite": "^7.1.1", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/solid/start-bare/vite.config.ts b/examples/solid/start-bare/vite.config.ts index bae1bfaad6..1a2219f443 100644 --- a/examples/solid/start-bare/vite.config.ts +++ b/examples/solid/start-bare/vite.config.ts @@ -1,6 +1,7 @@ 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: { @@ -11,5 +12,6 @@ export default defineConfig({ projects: ['./tsconfig.json'], }), tanstackStart(), + viteSolid({ ssr: true }), ], }) diff --git a/examples/solid/start-basic-static/package.json b/examples/solid/start-basic-static/package.json index b3373d60eb..f35086de31 100644 --- a/examples/solid/start-basic-static/package.json +++ b/examples/solid/start-basic-static/package.json @@ -9,9 +9,10 @@ "start": "vite start" }, "dependencies": { - "@tanstack/solid-router": "^1.131.27", - "@tanstack/solid-router-devtools": "^1.131.27", - "@tanstack/solid-start": "^1.131.27", + "@tanstack/solid-router": "^1.132.0-alpha.16", + "@tanstack/solid-router-devtools": "^1.132.0-alpha.16", + "@tanstack/solid-start": "^1.132.0-alpha.17", + "@tanstack/start-static-server-functions": "^1.132.0-alpha.16", "solid-js": "^1.9.5", "redaxios": "^0.5.1", "tailwind-merge": "^2.5.5" @@ -22,7 +23,8 @@ "postcss": "^8.4.49", "tailwindcss": "^3.4.15", "typescript": "^5.6.2", - "vite": "^6.3.5", - "vite-tsconfig-paths": "^5.1.3" + "vite": "^7.1.1", + "vite-tsconfig-paths": "^5.1.3", + "vite-plugin-solid": "^2.11.8" } } diff --git a/examples/solid/start-basic-static/src/routes/__root.tsx b/examples/solid/start-basic-static/src/routes/__root.tsx index c439d9dfcd..6d60d836c7 100644 --- a/examples/solid/start-basic-static/src/routes/__root.tsx +++ b/examples/solid/start-basic-static/src/routes/__root.tsx @@ -73,68 +73,63 @@ function RootComponent() { function RootLayout({ children }: { children: Solid.JSX.Element }) { return ( - - - - - -
    - - Home - {' '} - - Posts - {' '} - - Users - {' '} - - Pathless Layout - {' '} - - Deferred - {' '} - - This Route Does Not Exist - -
    -
    - {children} - - - - + <> +
    + + Home + {' '} + + Posts + {' '} + + Users + {' '} + + Pathless Layout + {' '} + + Deferred + {' '} + + This Route Does Not Exist + +
    +
    + {children} + + + ) } diff --git a/examples/solid/start-basic-static/src/routes/deferred.tsx b/examples/solid/start-basic-static/src/routes/deferred.tsx index ce617191eb..17ea8b7400 100644 --- a/examples/solid/start-basic-static/src/routes/deferred.tsx +++ b/examples/solid/start-basic-static/src/routes/deferred.tsx @@ -1,14 +1,17 @@ import { Await, createFileRoute } from '@tanstack/solid-router' import { createServerFn } from '@tanstack/solid-start' import { Suspense, createSignal } from 'solid-js' +import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' -const personServerFn = createServerFn({ method: 'GET', type: 'static' }) +const personServerFn = createServerFn({ method: 'GET' }) + .middleware([staticFunctionMiddleware]) .validator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) -const slowServerFn = createServerFn({ method: 'GET', type: 'static' }) +const slowServerFn = createServerFn({ method: 'GET' }) + .middleware([staticFunctionMiddleware]) .validator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) diff --git a/examples/solid/start-basic-static/src/routes/posts.$postId.tsx b/examples/solid/start-basic-static/src/routes/posts.$postId.tsx index 73bbe72553..df0b03af9e 100644 --- a/examples/solid/start-basic-static/src/routes/posts.$postId.tsx +++ b/examples/solid/start-basic-static/src/routes/posts.$postId.tsx @@ -12,7 +12,7 @@ export const Route = createFileRoute('/posts/$postId')({ }, }) -export function PostErrorComponent({ error }: ErrorComponentProps) { +function PostErrorComponent({ error }: ErrorComponentProps) { return } @@ -21,12 +21,12 @@ function PostComponent() { return (
    -

    {post.title}

    -
    {post.body}
    +

    {post().title}

    +
    {post().body}
    fetchPost({ data: postId, }), - errorComponent: PostErrorComponent, component: PostDeepComponent, }) diff --git a/examples/solid/start-basic-static/src/routes/users.$userId.tsx b/examples/solid/start-basic-static/src/routes/users.$userId.tsx index 928077c240..2c667b8ceb 100644 --- a/examples/solid/start-basic-static/src/routes/users.$userId.tsx +++ b/examples/solid/start-basic-static/src/routes/users.$userId.tsx @@ -4,8 +4,10 @@ import { createServerFn } from '@tanstack/solid-start' import type { ErrorComponentProps } from '@tanstack/solid-router' import type { User } from '~/utils/users' import { NotFound } from '~/components/NotFound' +import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' -const fetchUser = createServerFn({ method: 'GET', type: 'static' }) +const fetchUser = createServerFn({ method: 'GET' }) + .middleware([staticFunctionMiddleware]) .validator((d: string) => d) .handler(async ({ data: userId }) => { return axios @@ -29,7 +31,7 @@ export const Route = createFileRoute('/users/$userId')({ }, }) -export function UserErrorComponent({ error }: ErrorComponentProps) { +function UserErrorComponent({ error }: ErrorComponentProps) { return } diff --git a/examples/solid/start-basic-static/src/routes/users.tsx b/examples/solid/start-basic-static/src/routes/users.tsx index 1b5e9e23a2..19a36135ac 100644 --- a/examples/solid/start-basic-static/src/routes/users.tsx +++ b/examples/solid/start-basic-static/src/routes/users.tsx @@ -2,9 +2,11 @@ import { Link, Outlet, createFileRoute } from '@tanstack/solid-router' import axios from 'redaxios' import { createServerFn } from '@tanstack/solid-start' import type { User } from '../utils/users' +import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' -const fetchUsers = createServerFn({ method: 'GET', type: 'static' }).handler( - async () => { +const fetchUsers = createServerFn({ method: 'GET' }) + .middleware([staticFunctionMiddleware]) + .handler(async () => { console.info('Fetching users...') const res = await axios.get>( 'https://jsonplaceholder.typicode.com/users', @@ -13,8 +15,7 @@ const fetchUsers = createServerFn({ method: 'GET', type: 'static' }).handler( return res.data .slice(0, 10) .map((u) => ({ id: u.id, name: u.name, email: u.email })) - }, -) + }) export const Route = createFileRoute('/users')({ loader: async () => fetchUsers(), diff --git a/examples/solid/start-basic-static/src/utils/posts.tsx b/examples/solid/start-basic-static/src/utils/posts.tsx index 204230b7fe..01a6673569 100644 --- a/examples/solid/start-basic-static/src/utils/posts.tsx +++ b/examples/solid/start-basic-static/src/utils/posts.tsx @@ -2,6 +2,7 @@ import { createServerFn } from '@tanstack/solid-start' import axios from 'redaxios' import { notFound } from '@tanstack/solid-router' import { logMiddleware } from './loggingMiddleware' +import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' export type PostType = { id: string @@ -9,8 +10,8 @@ export type PostType = { body: string } -export const fetchPost = createServerFn({ method: 'GET', type: 'static' }) - .middleware([logMiddleware]) +export const fetchPost = createServerFn({ method: 'GET' }) + .middleware([logMiddleware, staticFunctionMiddleware]) .validator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) @@ -27,8 +28,8 @@ export const fetchPost = createServerFn({ method: 'GET', type: 'static' }) return post }) -export const fetchPosts = createServerFn({ method: 'GET', type: 'static' }) - .middleware([logMiddleware]) +export const fetchPosts = createServerFn({ method: 'GET' }) + .middleware([logMiddleware, staticFunctionMiddleware]) .handler(async () => { console.info('Fetching posts...') return axios diff --git a/examples/solid/start-basic-static/vite.config.ts b/examples/solid/start-basic-static/vite.config.ts index 213bd9189e..97fcbafb57 100644 --- a/examples/solid/start-basic-static/vite.config.ts +++ b/examples/solid/start-basic-static/vite.config.ts @@ -1,6 +1,7 @@ import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import { defineConfig } from 'vite' import tsConfigPaths from 'vite-tsconfig-paths' +import viteSolid from 'vite-plugin-solid' export default defineConfig({ server: { @@ -13,7 +14,20 @@ export default defineConfig({ tanstackStart({ spa: { enabled: true, + prerender: { + crawlLinks: true, + }, + }, + sitemap: { + host: 'https://localhost:3000', + }, + prerender: { + failOnError: true, + filter: (page) => { + return !page.path.includes('exist') + }, }, }), + viteSolid({ ssr: true }), ], }) diff --git a/examples/solid/start-basic/package.json b/examples/solid/start-basic/package.json index b60df07623..ad50e11246 100644 --- a/examples/solid/start-basic/package.json +++ b/examples/solid/start-basic/package.json @@ -9,9 +9,9 @@ "start": "vite start" }, "dependencies": { - "@tanstack/solid-router": "^1.131.27", - "@tanstack/solid-router-devtools": "^1.131.27", - "@tanstack/solid-start": "^1.131.27", + "@tanstack/solid-router": "^1.132.0-alpha.16", + "@tanstack/solid-router-devtools": "^1.132.0-alpha.16", + "@tanstack/solid-start": "^1.132.0-alpha.17", "solid-js": "^1.9.5", "redaxios": "^0.5.1", "tailwind-merge": "^2.6.0" @@ -22,8 +22,8 @@ "postcss": "^8.5.1", "tailwindcss": "^3.4.17", "typescript": "^5.7.2", - "vite": "^6.3.5", - "vite-plugin-solid": "^2.11.7", + "vite": "^7.1.1", + "vite-plugin-solid": "^2.11.8", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/solid/start-basic/src/utils/posts.tsx b/examples/solid/start-basic/src/utils/posts.tsx index e29706d38c..22db5ebb5f 100644 --- a/examples/solid/start-basic/src/utils/posts.tsx +++ b/examples/solid/start-basic/src/utils/posts.tsx @@ -8,7 +8,7 @@ export type PostType = { body: string } -export const fetchPost = createServerFn({ method: 'GET', type: 'static' }) +export const fetchPost = createServerFn({ method: 'GET' }) .validator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) @@ -28,7 +28,6 @@ export const fetchPost = createServerFn({ method: 'GET', type: 'static' }) export const fetchPosts = createServerFn({ method: 'GET', - type: 'static', }).handler(async () => { console.info('Fetching posts...') return axios diff --git a/examples/solid/start-basic/vite.config.ts b/examples/solid/start-basic/vite.config.ts index 93d987e62a..1a2219f443 100644 --- a/examples/solid/start-basic/vite.config.ts +++ b/examples/solid/start-basic/vite.config.ts @@ -11,7 +11,7 @@ export default defineConfig({ tsConfigPaths({ projects: ['./tsconfig.json'], }), - tanstackStart({ customViteSolidPlugin: true }), + tanstackStart(), viteSolid({ ssr: true }), ], }) diff --git a/labeler-config.yml b/labeler-config.yml index 015ae4ec3a..bce0cbe37b 100644 --- a/labeler-config.yml +++ b/labeler-config.yml @@ -25,9 +25,6 @@ 'package: react-start-client': - changed-files: - any-glob-to-any-file: 'packages/react-start-client/**/*' -'package: react-start-plugin': - - changed-files: - - any-glob-to-any-file: 'packages/react-start-plugin/**/*' 'package: react-start-server': - changed-files: - any-glob-to-any-file: 'packages/react-start-server/**/*' @@ -73,9 +70,6 @@ 'package: solid-start-client': - changed-files: - any-glob-to-any-file: 'packages/solid-start-client/**/*' -'package: solid-start-plugin': - - changed-files: - - any-glob-to-any-file: 'packages/solid-start-plugin/**/*' 'package: solid-start-server': - changed-files: - any-glob-to-any-file: 'packages/solid-start-server/**/*' @@ -88,15 +82,9 @@ 'package: start-server-core': - changed-files: - any-glob-to-any-file: 'packages/start-server-core/**/*' -'package: start-server-functions-client': +'package: start-static-server-functions': - changed-files: - - any-glob-to-any-file: 'packages/start-server-functions-client/**/*' -'package: start-server-functions-fetcher': - - changed-files: - - any-glob-to-any-file: 'packages/start-server-functions-fetcher/**/*' -'package: start-server-functions-server': - - changed-files: - - any-glob-to-any-file: 'packages/start-server-functions-server/**/*' + - any-glob-to-any-file: 'packages/start-static-server-functions/**/*' 'package: start-storage-context': - changed-files: - any-glob-to-any-file: 'packages/start-storage-context/**/*' diff --git a/package.json b/package.json index f4d91cf9ba..ec29778600 100644 --- a/package.json +++ b/package.json @@ -61,13 +61,13 @@ "rimraf": "^6.0.1", "tinyglobby": "^0.2.12", "typescript": "^5.9.0", - "vite": "6.3.5", - "vitest": "^3.0.6", "typescript54": "npm:typescript@5.4", "typescript55": "npm:typescript@5.5", "typescript56": "npm:typescript@5.6", "typescript57": "npm:typescript@5.7", - "typescript58": "npm:typescript@5.8" + "typescript58": "npm:typescript@5.8", + "vite": "^7.1.1", + "vitest": "^3.2.4" }, "pnpm": { "overrides": { @@ -99,15 +99,10 @@ "@tanstack/arktype-adapter": "workspace:*", "@tanstack/react-start": "workspace:*", "@tanstack/react-start-client": "workspace:*", - "@tanstack/react-start-plugin": "workspace:*", "@tanstack/react-start-server": "workspace:*", "@tanstack/solid-start": "workspace:*", "@tanstack/solid-start-client": "workspace:*", - "@tanstack/solid-start-plugin": "workspace:*", "@tanstack/solid-start-server": "workspace:*", - "@tanstack/start-server-functions-fetcher": "workspace:*", - "@tanstack/start-server-functions-client": "workspace:*", - "@tanstack/start-server-functions-server": "workspace:*", "@tanstack/start-plugin-core": "workspace:*", "@tanstack/start-client-core": "workspace:*", "@tanstack/start-server-core": "workspace:*", @@ -115,7 +110,8 @@ "@tanstack/eslint-plugin-router": "workspace:*", "@tanstack/server-functions-plugin": "workspace:*", "@tanstack/directive-functions-plugin": "workspace:*", - "@tanstack/router-utils": "workspace:*" + "@tanstack/router-utils": "workspace:*", + "@tanstack/start-static-server-functions": "workspace:*" } } } diff --git a/packages/arktype-adapter/package.json b/packages/arktype-adapter/package.json index 2ac8442be1..8862a44ffe 100644 --- a/packages/arktype-adapter/package.json +++ b/packages/arktype-adapter/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/arktype-adapter", - "version": "1.131.27", + "version": "1.132.0-alpha.16", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/directive-functions-plugin/package.json b/packages/directive-functions-plugin/package.json index 62c5b30da8..d98148407c 100644 --- a/packages/directive-functions-plugin/package.json +++ b/packages/directive-functions-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/directive-functions-plugin", - "version": "1.131.2", + "version": "1.132.0-alpha.9", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -77,9 +77,10 @@ "@types/babel__code-frame": "^7.0.6", "@types/babel__core": "^7.20.5", "@types/babel__traverse": "^7.20.7", - "vite": "^6.0.0" + "dedent": "^1.6.0", + "vite": "^7.1.1" }, "peerDependencies": { - "vite": ">=6.0.0" + "vite": ">=6.0.0 || >=7.0.0" } } diff --git a/packages/directive-functions-plugin/tests/compiler.test.ts b/packages/directive-functions-plugin/tests/compiler.test.ts index e405a7411e..a943f7f080 100644 --- a/packages/directive-functions-plugin/tests/compiler.test.ts +++ b/packages/directive-functions-plugin/tests/compiler.test.ts @@ -825,12 +825,14 @@ describe('server function compilation', () => { expect(client.compiledResult.code).toMatchInlineSnapshot(` "import { createClientRpc } from "my-rpc-lib-client"; const generator_1 = createClientRpc("test_ts--generator_1"); - const generator = generator_1;"`) + const generator = generator_1;" + `) expect(ssr.compiledResult.code).toMatchInlineSnapshot(` "import { createSsrRpc } from "my-rpc-lib-server"; const generator_1 = createSsrRpc("test_ts--generator_1"); - const generator = generator_1;"`) + const generator = generator_1;" + `) expect(server.compiledResult.code).toMatchInlineSnapshot(` "import { createServerRpc } from "my-rpc-lib-server"; @@ -839,7 +841,8 @@ describe('server function compilation', () => { return 'hello world'; }); const generator = generator_1; - export { generator_1 };"`) + export { generator_1 };" + `) }) test('async generator function', () => { const code = ` @@ -864,12 +867,14 @@ describe('server function compilation', () => { expect(client.compiledResult.code).toMatchInlineSnapshot(` "import { createClientRpc } from "my-rpc-lib-client"; const asyncGenerator_1 = createClientRpc("test_ts--asyncGenerator_1"); - const asyncGenerator = asyncGenerator_1;"`) + const asyncGenerator = asyncGenerator_1;" + `) expect(ssr.compiledResult.code).toMatchInlineSnapshot(` "import { createSsrRpc } from "my-rpc-lib-server"; const asyncGenerator_1 = createSsrRpc("test_ts--asyncGenerator_1"); - const asyncGenerator = asyncGenerator_1;"`) + const asyncGenerator = asyncGenerator_1;" + `) expect(server.compiledResult.code).toMatchInlineSnapshot(` "import { createServerRpc } from "my-rpc-lib-server"; @@ -878,6 +883,7 @@ describe('server function compilation', () => { return 'hello world'; }); const asyncGenerator = asyncGenerator_1; - export { asyncGenerator_1 };"`) + export { asyncGenerator_1 };" + `) }) }) diff --git a/packages/eslint-plugin-router/package.json b/packages/eslint-plugin-router/package.json index f52e05f35f..c28a627330 100644 --- a/packages/eslint-plugin-router/package.json +++ b/packages/eslint-plugin-router/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/eslint-plugin-router", - "version": "1.131.2", + "version": "1.132.0-alpha.1", "description": "ESLint plugin for TanStack Router", "author": "Manuel Schiller", "license": "MIT", diff --git a/packages/history/package.json b/packages/history/package.json index 022d1a175d..f6a63175a9 100644 --- a/packages/history/package.json +++ b/packages/history/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/history", - "version": "1.131.2", + "version": "1.132.0-alpha.1", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/react-router-devtools/package.json b/packages/react-router-devtools/package.json index a60807bc08..0463cad6a7 100644 --- a/packages/react-router-devtools/package.json +++ b/packages/react-router-devtools/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router-devtools", - "version": "1.131.27", + "version": "1.132.0-alpha.16", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/react-router-ssr-query/package.json b/packages/react-router-ssr-query/package.json index 6f9f0092cc..918561540e 100644 --- a/packages/react-router-ssr-query/package.json +++ b/packages/react-router-ssr-query/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router-ssr-query", - "version": "1.131.27", + "version": "1.132.0-alpha.16", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/react-router/package.json b/packages/react-router/package.json index f96dfc6b4b..2e021d27ad 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router", - "version": "1.131.27", + "version": "1.132.0-alpha.16", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/react-router/src/ScriptOnce.tsx b/packages/react-router/src/ScriptOnce.tsx index 5cae90d3c7..54614183d3 100644 --- a/packages/react-router/src/ScriptOnce.tsx +++ b/packages/react-router/src/ScriptOnce.tsx @@ -13,7 +13,7 @@ export function ScriptOnce({ ` + return `` }) }, dehydrate: async () => { @@ -106,12 +105,21 @@ export function attachRouterServerSsrUtils( _dehydrated = true const p = createControlledPromise() + const trackPlugins = { didRun: false } + const plugins = + ( + router.options.serializationAdapters as + | Array + | undefined + )?.map((t) => makeSsrSerovalPlugin(t, trackPlugins)) ?? [] crossSerializeStream(dehydratedRouter, { - refs: serializationRefs, - // TODO make plugins configurable - plugins: [ReadableStreamPlugin, ShallowErrorPlugin], + refs: new Map(), + plugins: [...plugins, ...defaultSerovalPlugins], onSerialize: (data, initial) => { - const serialized = initial ? `${GLOBAL_TSR}["router"]=` + data : data + let serialized = initial ? GLOBAL_TSR + '.router=' + data : data + if (trackPlugins.didRun) { + serialized = GLOBAL_TSR + '.p(()=>' + serialized + ')' + } router.serverSsr!.injectScript(() => serialized) }, scopeId: SCOPE_ID, diff --git a/packages/router-core/src/ssr/tsrScript.ts b/packages/router-core/src/ssr/tsrScript.ts index bd8c2a0e0f..c399733fd8 100644 --- a/packages/router-core/src/ssr/tsrScript.ts +++ b/packages/router-core/src/ssr/tsrScript.ts @@ -1,7 +1,11 @@ self.$_TSR = { - c: () => { + c() { document.querySelectorAll('.\\$tsr').forEach((o) => { o.remove() }) }, + p(script) { + !this.initialized ? this.buffer.push(script) : script() + }, + buffer: [], } diff --git a/packages/router-core/src/utils.ts b/packages/router-core/src/utils.ts index d446509498..67a30649ae 100644 --- a/packages/router-core/src/utils.ts +++ b/packages/router-core/src/utils.ts @@ -411,47 +411,6 @@ export function createControlledPromise(onResolve?: (value: T) => void) { return controlledPromise } -/** - * - * @deprecated use `jsesc` instead - */ -export function escapeJSON(jsonString: string) { - return jsonString - .replace(/\\/g, '\\\\') // Escape backslashes - .replace(/'/g, "\\'") // Escape single quotes - .replace(/"/g, '\\"') // Escape double quotes -} - -export function shallow(objA: T, objB: T) { - if (Object.is(objA, objB)) { - return true - } - - if ( - typeof objA !== 'object' || - objA === null || - typeof objB !== 'object' || - objB === null - ) { - return false - } - - const keysA = Object.keys(objA) - if (keysA.length !== Object.keys(objB).length) { - return false - } - - for (const item of keysA) { - if ( - !Object.prototype.hasOwnProperty.call(objB, item) || - !Object.is(objA[item as keyof T], objB[item as keyof T]) - ) { - return false - } - } - return true -} - export function isModuleNotFoundError(error: any): boolean { // chrome: "Failed to fetch dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split" // firefox: "error loading dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split" diff --git a/packages/router-core/tests/match-by-path.test.ts b/packages/router-core/tests/match-by-path.test.ts index afc1db3f54..51466ab0d5 100644 --- a/packages/router-core/tests/match-by-path.test.ts +++ b/packages/router-core/tests/match-by-path.test.ts @@ -3,20 +3,20 @@ import { matchByPath } from '../src' describe('default path matching', () => { it.each([ - ['', '', '', {}], - ['', '/', '', {}], - ['', '', '/', {}], - ['', '/', '/', {}], - ['/', '/', '/', {}], - ['/', '/a', '/a', {}], - ['/', '/a/b', '/a/b', {}], - ['/', '/a', '/a/', {}], - ['/', '/a/', '/a/', {}], - ['/', '/a/', '/a', undefined], - ['/', '/b', '/a', undefined], - ])('static %s %s => %s', (base, from, to, result) => { + ['', '', {}], + ['/', '', {}], + ['', '/', {}], + ['/', '/', {}], + ['/', '/', {}], + ['/a', '/a', {}], + ['/a/b', '/a/b', {}], + ['/a', '/a/', {}], + ['/a/', '/a/', {}], + ['/a/', '/a', undefined], + ['/b', '/a', undefined], + ])('static %s %s => %s', (from, to, result) => { expect( - matchByPath(base, from, { to, caseSensitive: true, fuzzy: false }), + matchByPath(from, { to, caseSensitive: true, fuzzy: false }), ).toEqual(result) }) @@ -27,7 +27,7 @@ describe('default path matching', () => { ['/a/1/b/2', '/a/$id/b/$id', { id: '2' }], ])('params %s => %s', (from, to, result) => { expect( - matchByPath('/', from, { to, caseSensitive: true, fuzzy: false }), + matchByPath(from, { to, caseSensitive: true, fuzzy: false }), ).toEqual(result) }) @@ -35,14 +35,13 @@ describe('default path matching', () => { // in the value: basically everything except / and % expect( matchByPath( - '/', '/a/@&é"\'(§è!çà)-_°^¨$*€£`ù=+:;.,?~<>|î©#0123456789\\😀}{', { to: '/a/$id' }, ), ).toEqual({ id: '@&é"\'(§è!çà)-_°^¨$*€£`ù=+:;.,?~<>|î©#0123456789\\😀}{' }) // in the key: basically everything except / and % and $ expect( - matchByPath('/', '/a/1', { + matchByPath('/a/1', { to: '/a/$@&é"\'(§è!çà)-_°^¨*€£`ù=+:;.,?~<>|î©#0123456789\\😀}{', }), ).toEqual({ '@&é"\'(§è!çà)-_°^¨*€£`ù=+:;.,?~<>|î©#0123456789\\😀}{': '1' }) @@ -60,7 +59,7 @@ describe('default path matching', () => { ['/a/1/b/2', '/a/{-$id}/b/{-$id}', { id: '2' }], ])('optional %s => %s', (from, to, result) => { expect( - matchByPath('/', from, { to, caseSensitive: true, fuzzy: false }), + matchByPath(from, { to, caseSensitive: true, fuzzy: false }), ).toEqual(result) }) @@ -71,7 +70,7 @@ describe('default path matching', () => { ['/a/b/c', '/a/$/foo', { _splat: 'b/c', '*': 'b/c' }], ])('wildcard %s => %s', (from, to, result) => { expect( - matchByPath('/', from, { to, caseSensitive: true, fuzzy: false }), + matchByPath(from, { to, caseSensitive: true, fuzzy: false }), ).toEqual(result) }) }) @@ -91,7 +90,7 @@ describe('case insensitive path matching', () => { ['/', '/b', '/A', undefined], ])('static %s %s => %s', (base, from, to, result) => { expect( - matchByPath(base, from, { to, caseSensitive: false, fuzzy: false }), + matchByPath(from, { to, caseSensitive: false, fuzzy: false }), ).toEqual(result) }) @@ -102,7 +101,7 @@ describe('case insensitive path matching', () => { ['/a/1/b/2', '/A/$id/B/$id', { id: '2' }], ])('params %s => %s', (from, to, result) => { expect( - matchByPath('/', from, { to, caseSensitive: false, fuzzy: false }), + matchByPath(from, { to, caseSensitive: false, fuzzy: false }), ).toEqual(result) }) @@ -118,7 +117,7 @@ describe('case insensitive path matching', () => { ['/a/1/b/2', '/A/{-$id}/B/{-$id}', { id: '2' }], ])('optional %s => %s', (from, to, result) => { expect( - matchByPath('/', from, { to, caseSensitive: false, fuzzy: false }), + matchByPath(from, { to, caseSensitive: false, fuzzy: false }), ).toEqual(result) }) @@ -129,7 +128,7 @@ describe('case insensitive path matching', () => { ['/a/b/c', '/A/$/foo', { _splat: 'b/c', '*': 'b/c' }], ])('wildcard %s => %s', (from, to, result) => { expect( - matchByPath('/', from, { to, caseSensitive: false, fuzzy: false }), + matchByPath(from, { to, caseSensitive: false, fuzzy: false }), ).toEqual(result) }) }) @@ -153,9 +152,9 @@ describe('fuzzy path matching', () => { ['/', '/b', '/a', undefined], ['/', '/a', '/b', undefined], ])('static %s %s => %s', (base, from, to, result) => { - expect( - matchByPath(base, from, { to, fuzzy: true, caseSensitive: true }), - ).toEqual(result) + expect(matchByPath(from, { to, fuzzy: true, caseSensitive: true })).toEqual( + result, + ) }) it.each([ @@ -165,9 +164,9 @@ describe('fuzzy path matching', () => { ['/a/1/b/2', '/a/$id/b/$other', { id: '1', other: '2' }], ['/a/1/b/2/c', '/a/$id/b/$other', { id: '1', other: '2', '**': 'c' }], ])('params %s => %s', (from, to, result) => { - expect( - matchByPath('/', from, { to, fuzzy: true, caseSensitive: true }), - ).toEqual(result) + expect(matchByPath(from, { to, fuzzy: true, caseSensitive: true })).toEqual( + result, + ) }) it.each([ @@ -181,9 +180,9 @@ describe('fuzzy path matching', () => { ['/a/b/2/d', '/a/{-$id}/b/{-$other}', { other: '2', '**': 'd' }], ['/a/1/b/2/c', '/a/{-$id}/b/{-$other}', { id: '1', other: '2', '**': 'c' }], ])('optional %s => %s', (from, to, result) => { - expect( - matchByPath('/', from, { to, fuzzy: true, caseSensitive: true }), - ).toEqual(result) + expect(matchByPath(from, { to, fuzzy: true, caseSensitive: true })).toEqual( + result, + ) }) it.each([ @@ -192,8 +191,8 @@ describe('fuzzy path matching', () => { ['/a', '/a/$', { _splat: '', '*': '' }], ['/a/b/c/d', '/a/$/foo', { _splat: 'b/c/d', '*': 'b/c/d' }], ])('wildcard %s => %s', (from, to, result) => { - expect( - matchByPath('/', from, { to, fuzzy: true, caseSensitive: true }), - ).toEqual(result) + expect(matchByPath(from, { to, fuzzy: true, caseSensitive: true })).toEqual( + result, + ) }) }) diff --git a/packages/router-core/tests/optional-path-params-clean.test.ts b/packages/router-core/tests/optional-path-params-clean.test.ts index 57f7d50f2a..f9cbd0c4fd 100644 --- a/packages/router-core/tests/optional-path-params-clean.test.ts +++ b/packages/router-core/tests/optional-path-params-clean.test.ts @@ -99,43 +99,43 @@ describe('Optional Path Parameters - Clean Comprehensive Tests', () => { describe('matchPathname', () => { it('should match optional dynamic params when present', () => { - const result = matchPathname('/', '/posts/tech', { + const result = matchPathname('/posts/tech', { to: '/posts/{-$category}', }) expect(result).toEqual({ category: 'tech' }) }) it('should match optional dynamic params when absent', () => { - const result = matchPathname('/', '/posts', { + const result = matchPathname('/posts', { to: '/posts/{-$category}', }) expect(result).toEqual({}) }) it('should handle multiple optional dynamic params', () => { - const result1 = matchPathname('/', '/posts/tech/hello', { + const result1 = matchPathname('/posts/tech/hello', { to: '/posts/{-$category}/{-$slug}', }) expect(result1).toEqual({ category: 'tech', slug: 'hello' }) - const result2 = matchPathname('/', '/posts/tech', { + const result2 = matchPathname('/posts/tech', { to: '/posts/{-$category}/{-$slug}', }) expect(result2).toEqual({ category: 'tech' }) - const result3 = matchPathname('/', '/posts', { + const result3 = matchPathname('/posts', { to: '/posts/{-$category}/{-$slug}', }) expect(result3).toEqual({}) }) it('should handle mixed required and optional dynamic params', () => { - const result1 = matchPathname('/', '/posts/tech/user/123', { + const result1 = matchPathname('/posts/tech/user/123', { to: '/posts/{-$category}/user/$id', }) expect(result1).toEqual({ category: 'tech', id: '123' }) - const result2 = matchPathname('/', '/posts/user/123', { + const result2 = matchPathname('/posts/user/123', { to: '/posts/{-$category}/user/$id', }) expect(result2).toEqual({ id: '123' }) diff --git a/packages/router-core/tests/optional-path-params.test.ts b/packages/router-core/tests/optional-path-params.test.ts index a34c54bb2f..bf54607300 100644 --- a/packages/router-core/tests/optional-path-params.test.ts +++ b/packages/router-core/tests/optional-path-params.test.ts @@ -389,7 +389,7 @@ describe('Optional Path Parameters', () => { expectedMatchedParams: {}, }, ])('$name', ({ input, matchingOptions, expectedMatchedParams }) => { - expect(matchPathname('/', input, matchingOptions)).toStrictEqual( + expect(matchPathname(input, matchingOptions)).toStrictEqual( expectedMatchedParams, ) }) @@ -422,16 +422,16 @@ describe('Optional Path Parameters', () => { ] tests.forEach(({ input, pattern, expected }) => { - expect(matchPathname('/', input, { to: pattern })).toEqual(expected) + expect(matchPathname(input, { to: pattern })).toEqual(expected) }) }) it('should prioritize more specific routes over optional param routes', () => { // Test that /posts/featured matches a static route, not optional param route - const staticMatch = matchPathname('/', '/posts/featured', { + const staticMatch = matchPathname('/posts/featured', { to: '/posts/featured', }) - const optionalMatch = matchPathname('/', '/posts/featured', { + const optionalMatch = matchPathname('/posts/featured', { to: '/posts/{-$category}', }) @@ -448,7 +448,7 @@ describe('Optional Path Parameters', () => { _splat: 'extra/path', } - expect(matchPathname('/', input, { to: pattern })).toEqual(expected) + expect(matchPathname(input, { to: pattern })).toEqual(expected) }) }) }) diff --git a/packages/router-core/tests/path.test.ts b/packages/router-core/tests/path.test.ts index 2a241bcb77..96458b4259 100644 --- a/packages/router-core/tests/path.test.ts +++ b/packages/router-core/tests/path.test.ts @@ -7,95 +7,12 @@ import { interpolatePath, matchPathname, parsePathname, - removeBasepath, removeTrailingSlash, resolvePath, trimPathLeft, } from '../src/path' import type { Segment as PathSegment } from '../src/path' -describe('removeBasepath', () => { - it.each([ - { - name: '`/` should leave pathname as-is', - basepath: '/', - pathname: '/path', - expected: '/path', - }, - { - name: 'should return empty string if basepath is the same as pathname', - basepath: '/path', - pathname: '/path', - expected: '', - }, - { - name: 'should remove basepath from the beginning of the pathname', - basepath: '/app', - pathname: '/app/path/app', - expected: '/path/app', - }, - { - name: 'should remove multisegment basepath from the beginning of the pathname', - basepath: '/app/new', - pathname: '/app/new/path/app/new', - expected: '/path/app/new', - }, - { - name: 'should remove basepath only in case it matches segments completely', - basepath: '/app', - pathname: '/application', - expected: '/application', - }, - { - name: 'should remove multisegment basepath only in case it matches segments completely', - basepath: '/app/new', - pathname: '/app/new-application', - expected: '/app/new-application', - }, - ])('$name', ({ basepath, pathname, expected }) => { - expect(removeBasepath(basepath, pathname)).toBe(expected) - }) - describe('case sensitivity', () => { - describe('caseSensitive = true', () => { - it.each([ - { - name: 'should not remove basepath from the beginning of the pathname', - basepath: '/app', - pathname: '/App/path/App', - expected: '/App/path/App', - }, - { - name: 'should not remove basepath from the beginning of the pathname with multiple segments', - basepath: '/app/New', - pathname: '/App/New/path/App', - expected: '/App/New/path/App', - }, - ])('$name', ({ basepath, pathname, expected }) => { - expect(removeBasepath(basepath, pathname, true)).toBe(expected) - }) - }) - - describe('caseSensitive = false', () => { - it.each([ - { - name: 'should remove basepath from the beginning of the pathname', - basepath: '/App', - pathname: '/app/path/app', - expected: '/path/app', - }, - { - name: 'should remove multisegment basepath from the beginning of the pathname', - basepath: '/App/New', - pathname: '/app/new/path/app', - expected: '/path/app', - }, - ])('$name', ({ basepath, pathname, expected }) => { - expect(removeBasepath(basepath, pathname, false)).toBe(expected) - }) - }) - }) -}) - describe.each([{ basepath: '/' }, { basepath: '/app' }, { basepath: '/app/' }])( 'removeTrailingSlash with basepath $basepath', ({ basepath }) => { @@ -167,39 +84,32 @@ describe.each([{ basepath: '/' }, { basepath: '/app' }, { basepath: '/app/' }])( describe('resolvePath', () => { describe.each([ - ['/', '/', '/', '/'], - ['/', '/', '/a', '/a'], - ['/', '/', 'a/', '/a'], - ['/', '/', '/a/b', '/a/b'], - ['/', 'a', 'b', '/a/b'], - ['/a/b', 'c', '/a/b/c', '/a/b/c'], - ['/a/b', '/', 'c', '/a/b/c'], - ['/a/b', '/', './c', '/a/b/c'], - ['/', '/', 'a/b', '/a/b'], - ['/', '/', './a/b', '/a/b'], - ['/', '/a/b/c', 'd', '/a/b/c/d'], - ['/', '/a/b/c', './d', '/a/b/c/d'], - ['/', '/a/b/c', './../d', '/a/b/d'], - ['/', '/a/b/c/d', './../d', '/a/b/c/d'], - ['/', '/a/b/c', '../../d', '/a/d'], - ['/', '/a/b/c', '../d', '/a/b/d'], - ['/', '/a/b/c', '..', '/a/b'], - ['/', '/a/b/c', '../..', '/a'], - ['/', '/a/b/c', '../../..', '/'], - ['/', '/a/b/c/', '../../..', '/'], - ['/products', '/', '/products-list', '/products/products-list'], - ['/basepath', '/products', '.', '/basepath/products'], - ])('resolves correctly', (base, a, b, eq) => { - it(`Base: ${base} - ${a} to ${b} === ${eq}`, () => { - expect(resolvePath({ basepath: base, base: a, to: b })).toEqual(eq) + ['/', '/', '/'], + ['/', '/a', '/a'], + ['/', 'a/', '/a'], + ['/', '/a/b', '/a/b'], + ['/a', 'b', '/a/b'], + ['/', 'a/b', '/a/b'], + ['/', './a/b', '/a/b'], + ['/a/b/c', 'd', '/a/b/c/d'], + ['/a/b/c', './d', '/a/b/c/d'], + ['/a/b/c', './../d', '/a/b/d'], + ['/a/b/c/d', './../d', '/a/b/c/d'], + ['/a/b/c', '../../d', '/a/d'], + ['/a/b/c', '../d', '/a/b/d'], + ['/a/b/c', '..', '/a/b'], + ['/a/b/c', '../..', '/a'], + ['/a/b/c', '../../..', '/'], + ['/a/b/c/', '../../..', '/'], + ])('resolves correctly', (a, b, eq) => { + it(`${a} to ${b} === ${eq}`, () => { + expect(resolvePath({ base: a, to: b })).toEqual(eq) }) - it(`Base: ${base} - ${a}/ to ${b} === ${eq} (trailing slash)`, () => { - expect(resolvePath({ basepath: base, base: a + '/', to: b })).toEqual(eq) + it(`${a}/ to ${b} === ${eq} (trailing slash)`, () => { + expect(resolvePath({ base: a + '/', to: b })).toEqual(eq) }) - it(`Base: ${base} - ${a}/ to ${b}/ === ${eq} (trailing slash + trailing slash)`, () => { - expect( - resolvePath({ basepath: base, base: a + '/', to: b + '/' }), - ).toEqual(eq) + it(`${a}/ to ${b}/ === ${eq} (trailing slash + trailing slash)`, () => { + expect(resolvePath({ base: a + '/', to: b + '/' })).toEqual(eq) }) }) describe('trailingSlash', () => { @@ -207,7 +117,6 @@ describe('resolvePath', () => { it('keeps trailing slash', () => { expect( resolvePath({ - basepath: '/', base: '/a/b/c', to: 'd/', trailingSlash: 'always', @@ -217,7 +126,6 @@ describe('resolvePath', () => { it('adds trailing slash', () => { expect( resolvePath({ - basepath: '/', base: '/a/b/c', to: 'd', trailingSlash: 'always', @@ -229,7 +137,6 @@ describe('resolvePath', () => { it('removes trailing slash', () => { expect( resolvePath({ - basepath: '/', base: '/a/b/c', to: 'd/', trailingSlash: 'never', @@ -239,7 +146,6 @@ describe('resolvePath', () => { it('does not add trailing slash', () => { expect( resolvePath({ - basepath: '/', base: '/a/b/c', to: 'd', trailingSlash: 'never', @@ -251,7 +157,6 @@ describe('resolvePath', () => { it('keeps trailing slash', () => { expect( resolvePath({ - basepath: '/', base: '/a/b/c', to: 'd/', trailingSlash: 'preserve', @@ -261,7 +166,6 @@ describe('resolvePath', () => { it('does not add trailing slash', () => { expect( resolvePath({ - basepath: '/', base: '/a/b/c', to: 'd', trailingSlash: 'preserve', @@ -294,11 +198,9 @@ describe('resolvePath', () => { const candidate = base + trimPathLeft(to) expect( resolvePath({ - basepath: '/', base, to: candidate, trailingSlash: 'never', - caseSensitive: false, }), ).toEqual(candidate) }) @@ -324,11 +226,9 @@ describe('resolvePath', () => { const candidate = base + trimPathLeft(to) expect( resolvePath({ - basepath: '/', base, to: candidate, trailingSlash: 'never', - caseSensitive: false, }), ).toEqual(candidate) }) @@ -571,63 +471,6 @@ describe('interpolatePath', () => { }) describe('matchPathname', () => { - describe('basepath matching', () => { - it.each([ - { - name: 'should match when the input is the same as the basepath', - basepath: '/basepath', - input: '/basepath', - matchingOptions: { - to: '/', - }, - expectedMatchedParams: {}, - }, - { - name: 'should match when the input starts with the basepath and `to` is set to the remaining', - basepath: '/basepath', - input: '/basepath/abc', - matchingOptions: { - to: '/abc', - }, - expectedMatchedParams: {}, - }, - { - name: 'should not match when the input is `/` and does not start with the basepath', - basepath: '/basepath', - input: '/', - matchingOptions: { - to: '/', - }, - expectedMatchedParams: undefined, - }, - { - name: 'should not match when the input completely does not start with the basepath', - basepath: '/basepath', - input: '/abc', - matchingOptions: { - to: '/abc', - }, - expectedMatchedParams: undefined, - }, - { - name: 'should not match when the input only partially matches the basepath', - basepath: '/base', - input: '/basepath/abc', - matchingOptions: { - to: '/abc', - }, - expectedMatchedParams: undefined, - }, - ])( - '$name', - ({ basepath, input, matchingOptions, expectedMatchedParams }) => { - expect(matchPathname(basepath, input, matchingOptions)).toStrictEqual( - expectedMatchedParams, - ) - }, - ) - }) - describe('path param(s) matching', () => { it.each([ { @@ -703,7 +546,7 @@ describe('matchPathname', () => { }, }, ])('$name', ({ input, matchingOptions, expectedMatchedParams }) => { - expect(matchPathname('/', input, matchingOptions)).toStrictEqual( + expect(matchPathname(input, matchingOptions)).toStrictEqual( expectedMatchedParams, ) }) @@ -767,7 +610,7 @@ describe('matchPathname', () => { }, }, ])('$name', ({ input, matchingOptions, expectedMatchedParams }) => { - expect(matchPathname('/', input, matchingOptions)).toStrictEqual( + expect(matchPathname(input, matchingOptions)).toStrictEqual( expectedMatchedParams, ) }) @@ -826,7 +669,7 @@ describe('matchPathname', () => { }, }, ])('$name', ({ input, matchingOptions, expectedMatchedParams }) => { - expect(matchPathname('/', input, matchingOptions)).toStrictEqual( + expect(matchPathname(input, matchingOptions)).toStrictEqual( expectedMatchedParams, ) }) diff --git a/packages/router-core/tests/processRouteTree.test.ts b/packages/router-core/tests/processRouteTree.test.ts index 67ffc5a260..b8197a9883 100644 --- a/packages/router-core/tests/processRouteTree.test.ts +++ b/packages/router-core/tests/processRouteTree.test.ts @@ -302,7 +302,6 @@ describe('processRouteTree', () => { // Test actual path matching for `/foo` const matchResult = getMatchedRoutes({ pathname: '/foo', - basepath: '/', caseSensitive: false, routesByPath: result.routesByPath, routesById: result.routesById, diff --git a/packages/router-devtools-core/package.json b/packages/router-devtools-core/package.json index fc91c7e609..3d6b113ac3 100644 --- a/packages/router-devtools-core/package.json +++ b/packages/router-devtools-core/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-devtools-core", - "version": "1.131.27", + "version": "1.132.0-alpha.16", "description": "Modern and scalable routing for Web applications", "author": "Tanner Linsley", "license": "MIT", @@ -67,7 +67,7 @@ "solid-js": "^1.9.5" }, "devDependencies": { - "vite-plugin-solid": "^2.11.6" + "vite-plugin-solid": "^2.11.8" }, "peerDependencies": { "tiny-invariant": "^1.3.3", diff --git a/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx b/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx index a84f318bc6..d8da987c08 100644 --- a/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx +++ b/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx @@ -98,6 +98,8 @@ function RouteComp({ routerState: Accessor< RouterState< Route< + any, + any, any, '/', '/', @@ -111,7 +113,9 @@ function RouteComp({ {}, undefined, any, - FileRouteTypes + FileRouteTypes, + unknown, + undefined >, MakeRouteMatchUnion > diff --git a/packages/router-devtools/package.json b/packages/router-devtools/package.json index 6f12d1c94b..ba74ae110f 100644 --- a/packages/router-devtools/package.json +++ b/packages/router-devtools/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-devtools", - "version": "1.131.27", + "version": "1.132.0-alpha.16", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/router-generator/package.json b/packages/router-generator/package.json index 39c4c335a0..7f402b0313 100644 --- a/packages/router-generator/package.json +++ b/packages/router-generator/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-generator", - "version": "1.131.27", + "version": "1.132.0-alpha.16", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/router-generator/src/generator.ts b/packages/router-generator/src/generator.ts index 122976d417..1880d0adf3 100644 --- a/packages/router-generator/src/generator.ts +++ b/packages/router-generator/src/generator.ts @@ -1,6 +1,6 @@ import path from 'node:path' import * as fsp from 'node:fs/promises' -import { mkdirSync } from 'node:fs' +import { existsSync, mkdirSync } from 'node:fs' import crypto from 'node:crypto' import { deepEqual, rootRouteId } from '@tanstack/router-core' import { logging } from './logger' @@ -194,7 +194,7 @@ export class Generator { this.logger = logging({ disabled: this.config.disableLogging }) this.root = opts.root this.fs = opts.fs || DefaultFileSystem - this.generatedRouteTreePath = path.resolve(this.config.generatedRouteTree) + this.generatedRouteTreePath = this.getGeneratedRouteTreePath() this.targetTemplate = getTargetTemplate(this.config) this.routesDirectoryPath = this.getRoutesDirectoryPath() @@ -212,6 +212,22 @@ export class Generator { }) } + private getGeneratedRouteTreePath() { + const generatedRouteTreePath = path.isAbsolute( + this.config.generatedRouteTree, + ) + ? this.config.generatedRouteTree + : path.resolve(this.root, this.config.generatedRouteTree) + + const generatedRouteTreeDir = path.dirname(generatedRouteTreePath) + + if (!existsSync(generatedRouteTreeDir)) { + mkdirSync(generatedRouteTreeDir, { recursive: true }) + } + + return generatedRouteTreePath + } + private getRoutesDirectoryPath() { return path.isAbsolute(this.config.routesDirectory) ? this.config.routesDirectory diff --git a/packages/router-generator/tests/generator.test.ts b/packages/router-generator/tests/generator.test.ts index dbd5e49540..1c4d921f14 100644 --- a/packages/router-generator/tests/generator.test.ts +++ b/packages/router-generator/tests/generator.test.ts @@ -270,4 +270,56 @@ describe('generator works', async () => { await postprocess(folderName) }, ) + + it('should create directory for routeTree if it does not exist', async () => { + const folderName = 'only-root' + const folderRoot = makeFolderDir(folderName) + let pathCreated = false + + const config = await setupConfig(folderName) + + rewriteConfigByFolderName(folderName, config) + + await preprocess(folderName) + config.generatedRouteTree = join( + folderRoot, + 'generated', + '/routeTree.gen.ts', + ) + const generator = new Generator({ config, root: folderRoot }) + const error = shouldThrow(folderName) + if (error) { + try { + await generator.run() + } catch (e) { + expect(e).toBeInstanceOf(Error) + expect((e as Error).message.startsWith(error)).toBeTruthy() + } + } else { + await generator.run() + + const generatedRouteTree = await getRouteTreeFileText(config) + + await expect(generatedRouteTree).toMatchFileSnapshot( + join( + 'generator', + folderName, + `routeTree.generated.snapshot.${config.disableTypes ? 'js' : 'ts'}`, + ), + ) + + pathCreated = await fs.access(dirname(config.generatedRouteTree)).then( + () => true, + () => false, + ) + + await expect(pathCreated).toBe(true) + } + + await postprocess(folderName) + + if (pathCreated) { + await fs.rm(dirname(config.generatedRouteTree), { recursive: true }) + } + }) }) diff --git a/packages/router-generator/tests/generator/only-root/routeTree.generated.snapshot.ts b/packages/router-generator/tests/generator/only-root/routeTree.generated.snapshot.ts new file mode 100644 index 0000000000..7766df9832 --- /dev/null +++ b/packages/router-generator/tests/generator/only-root/routeTree.generated.snapshot.ts @@ -0,0 +1,35 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './../routes/__root' + +export interface FileRoutesByFullPath {} +export interface FileRoutesByTo {} +export interface FileRoutesById { + __root__: typeof rootRouteImport +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: never + fileRoutesByTo: FileRoutesByTo + to: never + id: '__root__' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren {} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath {} +} + +const rootRouteChildren: RootRouteChildren = {} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/packages/router-plugin/package.json b/packages/router-plugin/package.json index 33290cb717..c8b0ce68dd 100644 --- a/packages/router-plugin/package.json +++ b/packages/router-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-plugin", - "version": "1.131.27", + "version": "1.132.0-alpha.16", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -127,8 +127,8 @@ "peerDependencies": { "@rsbuild/core": ">=1.0.2", "@tanstack/react-router": "workspace:^", - "vite": ">=5.0.0 || >=6.0.0", - "vite-plugin-solid": "^2.11.2", + "vite": ">=5.0.0 || >=6.0.0 || >=7.0.0", + "vite-plugin-solid": "^2.11.8", "webpack": ">=5.92.0" }, "peerDependenciesMeta": { diff --git a/packages/router-ssr-query-core/package.json b/packages/router-ssr-query-core/package.json index 03b14ee5a3..f19705e382 100644 --- a/packages/router-ssr-query-core/package.json +++ b/packages/router-ssr-query-core/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-ssr-query-core", - "version": "1.131.27", + "version": "1.132.0-alpha.16", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/router-utils/package.json b/packages/router-utils/package.json index f1e872dc4e..f874a9ea44 100644 --- a/packages/router-utils/package.json +++ b/packages/router-utils/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-utils", - "version": "1.131.2", + "version": "1.132.0-alpha.9", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -68,7 +68,9 @@ "@babel/parser": "^7.27.5", "@babel/preset-typescript": "^7.27.1", "ansis": "^4.1.0", - "diff": "^8.0.2" + "diff": "^8.0.2", + "fast-glob": "^3.3.3", + "pathe": "^2.0.3" }, "devDependencies": { "@babel/types": "^7.27.6", diff --git a/packages/router-utils/src/ast.ts b/packages/router-utils/src/ast.ts index 829471ad97..812824a121 100644 --- a/packages/router-utils/src/ast.ts +++ b/packages/router-utils/src/ast.ts @@ -8,10 +8,8 @@ export type ParseAstOptions = ParserOptions & { code: string } -export function parseAst({ - code, - ...opts -}: ParseAstOptions): ParseResult<_babel_types.File> { +export type ParseAstResult = ParseResult<_babel_types.File> +export function parseAst({ code, ...opts }: ParseAstOptions): ParseAstResult { return parse(code, { plugins: ['jsx', 'typescript', 'explicitResourceManagement'], sourceType: 'module', diff --git a/packages/router-utils/src/copy-files-plugin.ts b/packages/router-utils/src/copy-files-plugin.ts new file mode 100644 index 0000000000..13cfd31ec4 --- /dev/null +++ b/packages/router-utils/src/copy-files-plugin.ts @@ -0,0 +1,34 @@ +import { copyFile, mkdir } from 'node:fs/promises' +import { dirname, join } from 'pathe' +import fg from 'fast-glob' +import type { Plugin } from 'vite' + +export function copyFilesPlugin({ + fromDir, + toDir, + pattern = '**', +}: { + pattern?: string | Array + fromDir: string + toDir: string +}): Plugin { + return { + name: 'copy-files', + async writeBundle() { + const entries = await fg(pattern, { cwd: fromDir }) + if (entries.length === 0) { + throw new Error( + `No files found matching pattern "${pattern}" in directory "${fromDir}"`, + ) + } + + for (const entry of entries) { + const srcPath = join(fromDir, entry) + const destPath = join(toDir, entry) + // Ensure the destination directory exists + await mkdir(dirname(destPath), { recursive: true }) + await copyFile(srcPath, destPath) + } + }, + } +} diff --git a/packages/router-utils/src/index.ts b/packages/router-utils/src/index.ts index f238e8c695..85c3f38590 100644 --- a/packages/router-utils/src/index.ts +++ b/packages/router-utils/src/index.ts @@ -1,3 +1,5 @@ export { parseAst, generateFromAst } from './ast' -export type { ParseAstOptions, GeneratorResult } from './ast' +export type { ParseAstOptions, ParseAstResult, GeneratorResult } from './ast' export { logDiff } from './logger' + +export { copyFilesPlugin } from './copy-files-plugin' diff --git a/packages/router-vite-plugin/package.json b/packages/router-vite-plugin/package.json index 2827558b43..cd28344ac0 100644 --- a/packages/router-vite-plugin/package.json +++ b/packages/router-vite-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-vite-plugin", - "version": "1.131.27", + "version": "1.132.0-alpha.16", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/server-functions-plugin/package.json b/packages/server-functions-plugin/package.json index dc5876d26f..9502c6d66c 100644 --- a/packages/server-functions-plugin/package.json +++ b/packages/server-functions-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/server-functions-plugin", - "version": "1.131.2", + "version": "1.132.0-alpha.9", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/server-functions-plugin/src/index.ts b/packages/server-functions-plugin/src/index.ts index 8a396252ed..710fe0b2ba 100644 --- a/packages/server-functions-plugin/src/index.ts +++ b/packages/server-functions-plugin/src/index.ts @@ -8,11 +8,7 @@ import type { ReplacerFn, } from '@tanstack/directive-functions-plugin' -export type CreateRpcFn = ( - functionId: string, - serverBase: string, - splitImportFn?: string, -) => any +export type CreateRpcFn = (functionId: string, splitImportFn?: string) => any export type ServerFnPluginOpts = { /** diff --git a/packages/solid-router-devtools/package.json b/packages/solid-router-devtools/package.json index 4cb71c7e53..7f600d1412 100644 --- a/packages/solid-router-devtools/package.json +++ b/packages/solid-router-devtools/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/solid-router-devtools", - "version": "1.131.27", + "version": "1.132.0-alpha.16", "description": "Modern and scalable routing for Solid applications", "author": "Tanner Linsley", "license": "MIT", @@ -70,7 +70,7 @@ }, "devDependencies": { "solid-js": "^1.9.5", - "vite-plugin-solid": "^2.11.6" + "vite-plugin-solid": "^2.11.8" }, "peerDependencies": { "solid-js": "^1.9.5", diff --git a/packages/solid-router/package.json b/packages/solid-router/package.json index b8664d1cb5..be959f07e8 100644 --- a/packages/solid-router/package.json +++ b/packages/solid-router/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/solid-router", - "version": "1.131.27", + "version": "1.132.0-alpha.16", "description": "Modern and scalable routing for Solid applications", "author": "Tanner Linsley", "license": "MIT", @@ -114,7 +114,7 @@ "combinate": "^1.1.11", "eslint-plugin-solid": "^0.14.5", "solid-js": "^1.9.5", - "vite-plugin-solid": "^2.11.2", + "vite-plugin-solid": "^2.11.8", "zod": "^3.23.8" }, "peerDependencies": { diff --git a/packages/solid-router/src/ScriptOnce.tsx b/packages/solid-router/src/ScriptOnce.tsx index 7799f56a8c..681f5fd3cb 100644 --- a/packages/solid-router/src/ScriptOnce.tsx +++ b/packages/solid-router/src/ScriptOnce.tsx @@ -11,8 +11,8 @@ export function ScriptOnce({ return (