TanStack Features in TSStarter

Article
Featured

TanStack Features in TSStarter

TSStarter leverages TanStack Start, Router, Query, and Form to build a modern, type-safe, and production-ready TypeScript application

TSStarter Team
Author
8/24/2025
Published

TanStack Features in TSStarter

TSStarter is built on the powerful TanStack ecosystem - Start, Router, Query, and Form - to provide a comprehensive full-stack TypeScript solution that delivers exceptional developer experience and production-ready features.

๐Ÿš€ TanStack Router: Type-Safe Routing

TanStack Router provides the foundation for our routing system with file-based routing, type safety, and excellent developer experience.

File-Based Routing Structure

TSStarter uses TanStack Router's file-based routing system where each file in the src/routes/ directory automatically becomes a route. This provides:

  • Type-safe routing with automatic route generation
  • SSR integration with data prefetching
  • Protected routes with authentication guards
  • Dynamic routes for blog posts and documentation
  • Automatic code splitting with route-based chunking

Protected Routes with Authentication

Protected routes are implemented using TanStack Router's beforeLoad function, ensuring users are authenticated before accessing sensitive pages:

// Example: Protected dashboard route
export const Route = createFileRoute("/dashboard")({
  beforeLoad: async ({ context }) => {
    const session = await context.auth.getSession();
    if (!session) {
      throw redirect({ to: "/login" });
    }
  },
  component: DashboardPage,
});

Dynamic Routes with Type Safety

Dynamic routes like /blog/$ and /docs/$ provide type-safe access to content collections, with automatic 404 handling for missing content:

// Type-safe dynamic route with content validation
export const Route = createFileRoute("/blog/$")({
  validateSearch: (search: Record<string, unknown>) => {
    return z.object({
      slug: z.string(),
    }).parse(search);
  },
  loaderDeps: ({ search: { slug } }) => ({ slug }),
  loader: async ({ deps: { slug } }) => {
    const post = await getBlogPost(slug);
    if (!post) throw notFound();
    return post;
  },
});

๐Ÿ”„ TanStack Query: Powerful Data Management

TanStack Query handles all our data fetching, caching, and real-time updates with excellent TypeScript support.

Real-Time Data Fetching

TSStarter implements real-time data fetching using TanStack Query with oRPC:

  • Suspense queries for immediate data loading
  • Real-time updates using oRPC with Server-Sent Events (SSE)
  • Automatic cache invalidation on data changes
  • Optimistic updates for better user experience
  • Background refetching for data freshness

Mutations with Optimistic Updates

All data mutations use TanStack Query's mutation system with:

  • Optimistic updates for immediate UI feedback
  • Error handling with automatic rollback
  • Cache invalidation for data consistency
  • Loading states for better UX
// Example: Task creation with optimistic updates
const createTaskMutation = useMutation({
  mutationFn: createTask,
  onMutate: async (newTask) => {
    // Cancel outgoing refetches
    await queryClient.cancelQueries({ queryKey: ["tasks"] });
    
    // Snapshot previous value
    const previousTasks = queryClient.getQueryData(["tasks"]);
    
    // Optimistically update
    queryClient.setQueryData(["tasks"], (old) => [...old, newTask]);
    
    return { previousTasks };
  },
  onError: (err, newTask, context) => {
    // Rollback on error
    queryClient.setQueryData(["tasks"], context.previousTasks);
  },
  onSettled: () => {
    // Always refetch after error or success
    queryClient.invalidateQueries({ queryKey: ["tasks"] });
  },
});

SSR Integration with TanStack Router

TanStack Query is fully integrated with SSR through setupRouterSsrQueryIntegration, providing:

  • Server-side data prefetching for faster initial page loads
  • Hydration safety to prevent client/server mismatches
  • Automatic cache synchronization between server and client
  • Seamless SSR/CSR transitions with proper data hydration

Real-time features: Integration with oRPC

// Frontend: TanStack Query + oRPC integration
const { data: tasks } = useQuery({
  queryKey: ["tasks"],
  queryFn: () => orpc.tasks.getAll(), // oRPC type-safe call
  staleTime: 0, // Always fresh for real-time updates
});

// Real-time updates via TanStack Query + oRPC SSE
const { data: eventGenerator } = useQuery({
  queryKey: ["realtime-tasks"],
  queryFn: () => client.realtimeTasks(), // oRPC SSE stream
  refetchInterval: false, // Disable polling - use SSE instead
  staleTime: Infinity, // Keep data fresh since it's real-time
});

๐Ÿ“ TanStack Form: Type-Safe Form Management

TanStack Form provides excellent form handling with Zod validation and type safety.

Form Setup with Validation

All forms in TSStarter use TanStack Form with:

  • Type-safe form state
  • Real-time validation
  • Field-level error handling
  • Automatic form reset
  • Accessibility features
// Example: Type-safe form with validation
const form = useForm({
  defaultValues: {
    title: "",
    description: "",
    priority: "medium",
  },
  validators: {
    title: (value) => {
      if (!value) return "Title is required";
      if (value.length < 3) return "Title must be at least 3 characters";
    },
    description: (value) => {
      if (value && value.length > 500) return "Description too long";
    },
  },
});

Complex Form Handling

Forms handle complex scenarios like:

  • Task creation and editing
  • User sharing with email validation
  • Multi-step workflows
  • File uploads
  • Real-time collaboration

๐ŸŽฏ TanStack Start: Full-Stack Framework

TanStack Start provides the full-stack capabilities that tie everything together.

Content Collections with Server-Side Rendering (SSR)

TSStarter uses Content Collections for build-time content processing combined with Server-Side Rendering:

Build-Time Content Processing

Content Collections process MDX files at build time and generate type-safe JavaScript:

// content-collections.ts - Type-safe content schemas
const blog = defineCollection({
  name: "blog",
  directory: "content/blog",
  include: "**/*.mdx",
  schema: z.object({
    title: z.string(),
    description: z.string().optional(),
    author: z.string().optional(),
    date: z.string().optional(),
    tags: z.array(z.string()).optional(),
    readingTime: z.string().optional(),
  }),
});

Server-Side Rendering with Dynamic Routes

Blog and documentation routes use SSR with dynamic content loading:

// src/routes/blog/$.tsx - SSR blog post rendering
export const Route = createFileRoute("/blog/$")({
  loader: async ({ params }) => {
    const path = params._splat;
    const blog = allBlogs.find((b) => b._meta.path === path);
    
    if (!blog) throw notFound();
    
    return {
      content: blog.content, // MDX content processed at build time
      meta: {
        title: blog.title,
        description: blog.description,
        author: blog.author,
        publishedAt: blog.date,
        tags: blog.tags,
      },
    };
  },
});

Build-Time + SSR Benefits

  • Build-time content processing for type safety and validation
  • Server-side rendering for SEO and performance
  • Dynamic route handling for flexible content management
  • Type-safe metadata with automatic validation
  • Reading time calculation for better UX
  • Tag-based filtering for content discovery

Server-Side API Routes

API routes are implemented using TanStack Start's createServerFileRoute:

  • Type-safe API endpoints
  • Automatic request/response handling
  • Error handling with proper HTTP status codes
  • Middleware support
  • CSRF protection

Polar Integration: Payment Processing

TSStarter implements a complete payment processing system using Polar's webhook API:

// src/routes/api/polar.webhook.ts - Complete payment processing
export const ServerRoute = createServerFileRoute("/api/polar/webhook").methods({
  POST: handleWebhook,
});

async function handleOrderPaid(order: PolarOrder): Promise<Response> {
  // Find or create user from Polar customer data
  const user = await findOrCreateUser(order.customer);
  
  // Create purchase record in database
  await createPurchaseRecord(order, user.id, plan);
  
  // Update user access permissions
  await updateUserAccess(user.id, plan);
  
  // Send thank you email
  await sendThankYouEmail(order);
  
  // Invite to GitHub repository
  await sendGitHubInvite(user);
}

Key Features:

  • Automatic user creation from Polar customer data
  • Purchase tracking with duplicate prevention
  • Email notifications for successful purchases
  • GitHub repository invites for premium users
  • Comprehensive error handling and logging

๐Ÿ“Š Feature Summary

TanStack LibraryFeatures ImplementedUsage
TanStack RouterFile-based routing, Type-safe routes, SSR integration, Protected routesAll routing, navigation, and page structure
TanStack QueryData fetching, Caching, Mutations, Real-time updates, SSR integrationAll API calls, state management, and real-time features
TanStack FormType-safe forms, Validation, Field management, Form stateAll user input forms, task creation, sharing, etc.
TanStack StartFull-stack framework, SSR, API routes, Isomorphic functionsServer-side rendering, API endpoints, full-stack integration
Content CollectionsMDX support, Blog system, Documentation, Type-safe contentBlog posts, documentation pages, content management

๐ŸŽฏ Benefits of Using TanStack in TSStarter

1. Type Safety

  • End-to-end type safety from database to UI
  • Compile-time error detection
  • IntelliSense support throughout the stack

2. Developer Experience

  • Excellent DX with hot reload, devtools, and clear patterns
  • File-based routing with automatic type generation
  • Integrated development tools

3. Performance

  • SSR with data prefetching - Server-side rendering with client hydration
  • Query caching - 2-minute stale time with background refetching
  • Route-based code splitting - Automatic chunking by route
  • Optimistic updates - Immediate UI feedback with automatic rollback

4. Real-time Capabilities

  • oRPC backend infrastructure with EventPublisher and Server-Sent Events
  • TanStack frontend data management with Query caching and UI state management
  • Live updates without page refreshes
  • Collaborative features with type-safe communication

5. Full-stack Integration

  • Seamless integration between frontend and backend
  • Shared types and validation
  • Isomorphic functions

๐ŸŽ‰ Conclusion

The TanStack ecosystem in TSStarter provides a modern, type-safe, and performant foundation for building full-stack TypeScript applications. Each library is carefully integrated to work together seamlessly, providing an excellent developer experience and production-ready features.

Whether you're building a simple blog, a complex SaaS application, or an enterprise system, TSStarter with TanStack gives you the tools and patterns you need to succeed.


TSStarter - Premium TypeScript Starter for Modern Web Applications.