tRPC v11 with TanStack Query on TanStack Start! Part 2

Jack HerringtonAbout 5 min readApr 8, 2025Watch original
THE SUMMARYAI-generated

Key Concepts

TRPC v11, TanStack Query, TanStack Start, Mutations, Authentication, Clerk, Clerk Agentic Toolkit, Server-Side Rendering (SSR), Client-Side Tool Calls, AI Assistant, Global State Management (Context API), Custom Hooks, User Preferences, Personalization.

Clerk Integration and Authentication

  • Clerk as Authentication Provider: The video demonstrates integrating Clerk for user authentication. Clerk is chosen over rolling a custom solution.
  • Clerk Setup:
    • Clerk libraries are installed using npm install @clerk/clerk-react @clerk/nextjs.
    • A clerk directory is created to house Clerk-related components.
    • ClerkProvider is set up to wrap the application, requiring a Clerk API key.
    • API keys are obtained from the Clerk dashboard (Configuration -> API Keys) and stored in .env.local.
  • UI Components:
    • HeaderUser.tsx component is created to include sign-in, sign-out, and user profile buttons using components from clerk-react.
    • The HeaderUser component is integrated into the main header.
  • Benefits: Clerk simplifies authentication with pre-built UI components and backend integration.

Cart Functionality Implementation with TRPC and Mutations

  • Cart Data Structure: A cart is defined as an object containing an array of guitars.
  • In-Memory Cart Storage: Carts are stored in memory, associated with users.
  • TRPC Cart Router:
    • A cartRouter is created within the TRPC backend.
    • get (Query): Retrieves the cart for the current user. It uses getAuth from @clerk/nextjs/server and getWebRequest from vinci to identify the user.
    • add (Mutation): Adds a guitar to the user's cart. It takes a guitarId as input.
      • It verifies the user's identity using getAuth.
      • It retrieves the user's cart.
      • It performs a sanity check on the guitarId.
      • It adds the guitar to the cart and returns the updated cart.
  • TRPC Router Integration: The cartRouter is added to the main TRPC router.

Global Cart Store using React Context API

  • Purpose: To manage cart state globally for use across different components (header, detail page, AI assistant).
  • Implementation:
    • cart.tsx is created in the store directory.
    • useCartStore (Custom Hook):
      • Uses useUser from @clerk/clerk-react to determine if the user is signed in.
      • Uses trpc.cart.get.useQuery to fetch the cart data if the user is signed in.
      • Uses trpc.cart.add.useMutation to create an addToCart mutation function.
      • refetch function is used to update the cart state after a successful mutation.
      • Returns the current cart, addToCart function, and a list of guitars in the cart.
    • CartStoreContext (Context): Creates a context to hold the useCartStore hook.
    • CartStoreProvider (Provider): Provides the useCartStore hook to the application. It's wrapped around the ClerkProvider in _app.tsx.
    • useStore (Helper Hook): A simple hook to access the CartStoreContext.
  • Integration: The CartStoreProvider is added to _app.tsx to make the cart store available throughout the application.

Add to Cart Implementation on Detail Page

  • useStore Hook: The useStore hook is imported into the guitar detail page.
  • addToCart Function: The addToCart function is retrieved from the useStore hook.
  • Button Implementation: The addToCart function is called when the "Add to Cart" button is clicked, passing the guitar ID as an argument.

Cart UI Component

  • Cart.tsx: A component is created to display the cart contents in a dialog.
  • Shadcn UI: The component uses Shadcn UI components like Button and Dialog.
  • Data Display: The component uses the useStore hook to access the cart data and displays the guitars in the cart along with the total price.
  • Integration: The Cart component is added to the header.

AI Assistant Integration for Adding to Cart

  • Tool Definition: A new tool called addGuitarToCart is defined for the AI assistant.
    • Description: "If somebody wants you to add a guitar to the cart then use this tool."
    • Parameter: The ID of the guitar.
  • Client-Side Tool Call Handling:
    • The useChat hook in the AI assistant is modified to handle the addGuitarToCart tool call.
    • When the AI assistant calls the addGuitarToCart tool, the addToCart function from the useCartStore hook is called with the guitar ID.

Clerk Agentic Toolkit for Personalization

  • Purpose: To enable the AI assistant to personalize recommendations based on user preferences.
  • Installation: The @clerk/agent-toolkit library is installed.
  • Toolkit Creation:
    • The createClerkToolkit function is imported from @clerk/agent-toolkit.
    • The getAuth and getWebRequest functions are used to get the user's identity.
    • The createClerkToolkit function is called with the authentication context and the users tool from the Clerk tools.
  • Tool Integration: The Clerk toolkit is added to the list of tools available to the AI assistant.
  • System Prompt Modification: The system prompt is updated to inform the AI assistant about the new tools (updateUser, getUser) and how to use them to store and retrieve user preferences.
  • Preference Storage: When the user expresses a preference (e.g., "I really love acoustic guitars"), the AI assistant uses the updateUser tool to store the preference in the user's Clerk record.
  • Personalized Recommendations: When the user asks for recommendations, the AI assistant uses the getUser tool to retrieve the user's preferences and provides recommendations based on those preferences.
  • Example: The video demonstrates how the AI assistant remembers the user's preference for acoustic guitars and only recommends acoustic guitars in subsequent interactions.

Conclusion

The video demonstrates how to build a full-stack application with TRPC v11, TanStack Query, TanStack Start, Clerk authentication, and AI integration. It covers topics such as mutations, global state management, and client-side tool calls. The use of the Clerk Agentic Toolkit for personalization is highlighted as a particularly powerful feature. The presenter emphasizes the ease of integration and the benefits of using these technologies together.

AI summaries can miss context or contain errors. Check important details against the original video.

Go a little deeper.

Have a question about this video? Load its transcript to open the video chat.