Implementing Query Procedures
Create read-only data fetching endpoints using tRPC query procedures with input and output types.
What are tRPC Queries?
Queries are like asking a question to your server. They are designed for fetching data, not changing it. Think of them as the "GET" requests in a traditional REST API.
- Read-only: Queries should never change data on your server.
- Idempotent: Running a query multiple times should produce the same result.
- Cached: Clients can often cache query results for better performance.
They are the foundation for retrieving information in your tRPC application.
Defining a Simple Query
In tRPC, you define queries within a router using .query(). Let's look at the basic structure.
First, you need to initialize tRPC (usually done once in your server setup):
const t = initTRPC.create();Then, define your router and add a query:
import { initTRPC } from '@trpc/server';
// 1. Initialize tRPC
const t = initTRPC.create();
// 2. Create a router
const appRouter = t.router({
// 3. Define a query named 'hello'
hello: t.procedure.query(() => {
return 'Hello from tRPC!';
}),
});
// This snippet shows the core definition.
// A full server setup is needed to run it.All lessons in this course
- Structuring with tRPC Routers
- Implementing Query Procedures
- Developing Mutation Procedures
- Merging and Nesting Routers