tRPC v11 with TanStack Query on TanStack Start! Part 1
By Jack Herrington
Share:
Key Concepts
- tRPC v11 integration with TanStack Query
create-ts-router-appfor building TanStack Router applications- tRPC client and server setup
- TanStack Start API route creation
- React hook for tRPC connection (
useTRPC) - Server-side rendering with tRPC
- Using tRPC outside of React context
Setting Up tRPC with TanStack Start
- Project Initialization:
- Use
create-ts-router-appto scaffold a new TanStack Router application. - Select the "Add-ons" functionality for additional features.
- Include options like TanStack Query, Start, Clerk (for future use), and Shadcn UI.
- Optionally, integrate the TanStack Chat example for a full-featured AI assistant demo with guitar data.
- Use
- Installing Dependencies:
- Install necessary libraries:
trpc-client,trpc-server,@trpc/react-query,superjson, andzod.
- Install necessary libraries:
- Creating the tRPC Directory:
- Create a
trpcdirectory inside thesrcfolder to house tRPC-related files.
- Create a
- Initializing tRPC:
- Create an
init.tsfile to initialize the tRPC setup. - Use
initTRPCto create the tRPC setup, providingTfor type inference. - Obtain
routerfromTto create the tRPC router. - Use
publicProcedureto define public RPC procedures.
- Create an
- Defining the Router:
- Create a
router.tsfile to define the tRPC RPC functions. - Import
createTRPCRouterandpublicProcedurefrom the initialized tRPC setup. - Import the guitar data (e.g.,
guitaristData). - Create a
guitarRouterusingcreateTRPCRouter. - Define procedures within the
guitarRouter:list: Returns the list of all guitars.byID: Takes anidas input (validated by Zod) and returns the guitar with the matching ID.
- Create the main tRPC router by combining the
guitarRouter. - Export the type of the tRPC router for type safety.
- Create a
- Creating the TanStack Start API Route:
- Create an API route file in
src/routes/api/trpc/[...].ts(using the TanStack Start file-based routing convention). - Import the tRPC router.
- Create an API file route with
getandposthandlers. - Pass the requests to a handler that wraps the
fetchRequestHandlerfrom@trpc/server/adapters/standalone.
- Create an API route file in
- Testing the Endpoint:
- Start the development server.
- Make an API request to
/api/trpc/guitars.listto verify the tRPC endpoint is working.
Integrating tRPC with React and TanStack Query
- Creating the React Hook:
- Create a
react.tsfile in thetrpcdirectory. - Import
createTRPCContextfrom@trpc/react-query. - Import the tRPC router definition.
- Use
createTRPCContextto create theuseTRPChook and theTRPCProvidercomponent.
- Create a
- Connecting with TanStack Query:
- Modify the TanStack Query setup in
Integrations/tanstack-query/index.tsx. - Import the
TRPCProvidercomponent. - Create a tRPC client using
createTRPCClient. - Use
httpBatchLinkas the transport layer. - Implement a
getURLfunction to determine the correct URL (absolute for server-side, relative for client-side). - Upgrade the TanStack Query client to use
superjsonfor serialization and deserialization. - Add the tRPC client to the context.
- Replace the
QueryClientProviderwith theTRPCProvider.
- Modify the TanStack Query setup in
- Wrapping the Application:
- Modify the base router to wrap the application in the
TRPCProvider. - Use the
routerWithQueryClientfunction to handle the TanStack Query provider functionality.
- Modify the base router to wrap the application in the
- Ensuring Type Safety:
- In the root route, add
trpcto the router context to ensure full type safety.
- In the root route, add
Implementing tRPC Queries in React Components
- Fetching Data in a Component:
- Import
useQueryfrom TanStack Query anduseTRPCfrom thetrpc/reactfile. - Use
useTRPCto get the tRPC client. - Use
useQueryto make the tRPC call (e.g.,trpc.guitars.list.useQuery()). - Map the data to the component's state.
- Import
- Server-Side Rendering:
- Create a loader in the route to prefetch the query.
- Use the loader to prefetch the data and save it as part of the page.
- The component will then use the prefetched data, avoiding the initial "blinking" behavior.
- The data will be included in the returned HTML, improving SEO.
- Parameterized Queries:
- On the details page, get the ID from the route parameters using
useParams. - Pass the ID to the
byIDprocedure in the tRPC router. - Use
useQueryto fetch the data with the ID parameter.
- On the details page, get the ID from the route parameters using
Using tRPC Outside of React Context
- Accessing the tRPC Client:
- Import the tRPC client created in the root provider.
- Making Queries:
- Use the tRPC client directly to make queries (e.g.,
await trpc.guitars.list.query()). - This allows you to use tRPC in non-React contexts, such as AI tools or server-side functions.
- Use the tRPC client directly to make queries (e.g.,
Example: Integrating tRPC with the AI Assistant
- Modifying the Tool Definition:
- In the
utils/demo-tools.tsfile, modify thegetGuitarsTooldefinition. - Import the tRPC client.
- In the
executefunction, use the tRPC client to fetch the guitar list (e.g.,await trpc.guitars.list.query()).
- In the
- Testing the Integration:
- Go to the AI assistant in the guitar demo.
- Ask for a guitar recommendation.
- The AI assistant will use the tRPC client to fetch the guitar data and provide a recommendation.
Conclusion
The video demonstrates how to integrate tRPC v11 with TanStack Query in a TanStack Start application. It covers setting up the tRPC client and server, creating API routes, implementing queries in React components, enabling server-side rendering, and using tRPC outside of the React context. The example of integrating tRPC with an AI assistant showcases the flexibility and power of tRPC for building type-safe and efficient data fetching solutions. The next video will cover mutations.
Chat with this Video
AI-PoweredLoad the transcript when you're ready to chat so the initial page stays lighter.
Related Videos

How the hometown humiliation of Putin marks a turning point for Ukraine | DW News
DW News

Shocking video shows moment paramedics are hit by Israel in 'double-tap' strike
Sky News

Inside Jeffrey Epstein's Network of Power
Bloomberg Originals

Putin Xi, To Catch a Castro, Red Carpet Rebellion • FRANCE 24 English
FRANCE 24 English

Trump's supporters furious over Trump smartphone scam.
ABC News In-depth

Nvidia Crushes Earnings again — What Jensen Huang sees next for AI
CGTN America

Throwing out the first pitch for the Rockies for STEM Day!
Sick Science!