tRPC
Type-safe API calls with end-to-end TypeScript safety using tRPC and React Query.
This guide explains how to use the tRPC integration for type-safe API calls in the application, including available routes, custom hooks, and best practices. This template uses tRPC with react-query under the hood. For more information, visit the tRPC documentation.
Overview
tRPC enables end-to-end typesafe APIs, ensuring that your frontend and backend are always in sync without schema validation or code generation. Our application implements a structured tRPC router system with dedicated hooks for common operations.
Key Benefits
Full Type Safety
End-to-end type safety between client and server
Auto Documentation
Automatic API documentation through TypeScript
Error Handling
Simplified error handling with proper typing
React Query
Integrated with React Query for caching and state management
Zero Config
Available Routes
The application organizes tRPC routes into logical groups by feature. Below
are the available routers defined in _app.ts
.
trpc.users.*
trpc.items.*
trpc.notifications.*
trpc.workspaces.*
trpc.members.*
trpc.invitations.*
trpc.usersSettings.*
trpc.subscriptions.*
trpc.feedbacks.*
Router Configuration
Custom Hooks
Each router has dedicated hooks organized in files like
items-hooks.ts
or users-hooks.ts
. These hooks
encapsulate common functionality and provide built-in error handling, toast
notifications, and cache invalidation.
Item Hooks Example
Custom hooks for item operations defined in items-hooks.ts
:
Using tRPC Hooks
Using Mutation Hooks
Example of using a tRPC mutation hook in a component:
Using Query Hooks
Example of fetching data with tRPC queries:
Type Safety Benefits
One of tRPC's primary benefits is its strong typing system that ensures your frontend and backend remain in sync.
Automatic Type Inference
Types flow from your backend to frontend without any manual work:
Input Validation
Input validation happens at compile time and runtime:
Error Handling
Errors are properly typed and can be handled gracefully:
Hook Patterns
Common Hook Structure
- Import dependencies - Import tRPC client and other utilities
- Access tRPC utilities - Get access to the tRPC client
- Setup mutation or query - Configure the tRPC operation
- Handle success/error cases - Manage toast messages and state updates
- Return necessary values - Expose mutate function, loading state, etc.
Cache Invalidation
Best Practices
Hook Organization
- Group related hooks in feature-specific files
- Keep hooks focused on single responsibilities
- Provide optional callback props for flexibility
- Handle errors consistently across hooks
Type Safety
- Leverage TypeScript's inference capabilities
- Define input and output types explicitly for complex operations
- Avoid using 'any' or type assertions
- Use zod schemas for validation
Performance
- Use proper cache invalidation strategies
- Implement optimistic updates for better UX
- Use suspense mode when appropriate
- Enable prefetching for frequently accessed data
Error Handling
- Provide descriptive error messages
- Use toast notifications for user feedback
- Handle different error types appropriately
- Implement proper fallbacks and loading states
Key Features
End-to-End Type Safety
🔄 Full TypeScript integration from backend to frontend
React Query Integration
⚡ Built-in caching, refetching, and state management
Error Handling
🛡️ Standardized error handling with custom error types
Developer Experience
🔍 Autocomplete and type checking in your IDE
Client Configuration
tRPC Client Setup
Creating a New tRPC Route
When adding new tRPC routes, follow these steps to maintain consistency across the application.
1. Define the Router
Create a new router file in trpc/routers/
:
2. Add to App Router
Add your new router to the app router in _app.ts
:
3. Create Custom Hooks
Create hooks for your new router:
Additional Resources
tRPC Documentation
Complete documentation for tRPC
React Query
Learn more about React Query for state management
Zod Documentation
Documentation for the Zod validation library
Server Actions
See the Server Actions documentation for another approach to server communication