tRPC mutation() Method Basics
You'll learn how to define mutation procedures using .mutation() for operations that change server state.
What Mutations Represent
In tRPC, while queries are for reading data, mutations are for writing it. Any operation that creates, updates, or deletes data on the server should be a mutation. Think of mutations as the "write" operations in your API contract.
The .mutation() method tells tRPC: "This procedure will change something on the server, so treat it accordingly."
Basic Mutation Syntax
Creating a mutation looks similar to creating a query, but you use .mutation() instead:
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
const t = initTRPC.create();
const appRouter = t.router({
createPost: t.procedure
.input(z.object({
title: z.string(),
content: z.string()
}))
.mutation(({ input }) => {
// This changes server state
const newPost = {
id: Math.random().toString(),
title: input.title,
content: input.content
};
return newPost;
})
});
The .mutation() method receives the same arguments as .query() — primarily { input } — but signals to tRPC that this operation should be treated as a state-changing action.
Why the Distinction Matters
Separating queries from mutations enables:
- HTTP method mapping: Mutations typically use POST, queries use GET
- Client-side optimizations: React Query (used by tRPC's React client) caches queries but handles mutations differently
- Semantic clarity: Your API contract explicitly shows what reads vs. writes data
Key Differences from Queries
While both use similar syntax, mutations:
- Should never be called automatically on component mount
- Typically invalidate cached query results after completion
- Signal to the client that side effects are happening
Key Takeaway: Use .mutation() to define any tRPC procedure that creates, updates, or deletes server-side data, giving you type-safe write operations with explicit semantics.