tRPC query() Method Basics
What you'll learn: How to define read-only procedures using .query() and when queries are the right choice over mutations.
Understanding .query() in tRPC
In tRPC, queries are procedures designed specifically for read-only operations—fetching data without causing side effects. The .query() method defines these procedures on your router.
Think of it like the difference between reading a book (query) and writing in it (mutation). When you want to retrieve data—user profiles, product listings, dashboard statistics—you use .query().
Basic query() Syntax
When defining a query procedure, you tell tRPC:
- What input to expect (if any)
- What logic to execute
- What data to return
The magic of tRPC is that the return type automatically flows to your frontend, giving you full type safety without manual type definitions.
import { router, publicProcedure } from './trpc';
const appRouter = router({
getUser: publicProcedure.query(() => {
return { id: 1, name: 'Alice', role: 'admin' };
}),
});
In this example, any frontend calling getUser will know it receives an object with id, name, and role properties—all inferred automatically.
When to Use .query()
Use .query() for operations that:
- Fetch data from databases
- Read from external APIs
- Calculate results without storing anything
- Are safe to retry without consequences
- Don't modify server state
Queries should be idempotent: calling them multiple times produces the same result and doesn't change anything on the server.
Key Takeaway: Use .query() to define read-only tRPC procedures that fetch or compute data without side effects, enabling type-safe data retrieval across your application.