An end-to-end recipe: a "Reports" feature with a table, a tRPC router, a page and a sidebar link. Follow the same steps for anything you build.
1. Model the data
Create packages/database/prisma/reports.prisma:
model Report {
id String @id @default(cuid())
userId String
title String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId])
@@schema("user_schema")
}
Add the back-relation to User in user.prisma (reports Report[]). Use an existing Postgres schema, or add a new one to schemas in schema.prisma. With the Organizations module, add an organizationId and filter by workspace instead of user.
pnpm migrate # name it add_reports, then read the SQL
2. Write the router
apps/web/trpc/routers/reportProcedures.ts:
import { z } from "zod";
import db from "@workspace/database/client";
import { createTRPCRouter, protectedProcedure } from "@/trpc/init";
export const reportRouter = createTRPCRouter({
list: protectedProcedure.query(({ ctx }) =>
db.report.findMany({ where: { userId: ctx.session.user.id }, orderBy: { createdAt: "desc" } }),
),
create: protectedProcedure
.input(z.object({ title: z.string().trim().min(1).max(120) }))
.mutation(({ ctx, input }) =>
db.report.create({ data: { title: input.title, userId: ctx.session.user.id } }),
),
});
Register it in apps/web/trpc/routers/_app.ts (report: reportRouter) and describe it in apps/web/trpc/apiRegistry.ts:
{
group: "report",
label: "Reports",
calls: [
{ name: "list", type: "query", access: "authenticated" },
{ name: "create", type: "mutation", access: "authenticated" },
],
},
If the logic is more than a query, put it in a service in apps/web/lib/ and call it from the router; routers stay thin and services stay testable.
3. Build the UI
A client component in apps/web/components/reports/ReportsList.tsx:
"use client";
import { useState } from "react";
import { useMutation, useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
import { Button } from "@workspace/ui/components/shadcn/button";
import { Input } from "@workspace/ui/components/shadcn/input";
import { useTRPC } from "@/trpc/client";
export default function ReportsList() {
const trpc = useTRPC();
const queryClient = useQueryClient();
const [title, setTitle] = useState("");
const { data: reports } = useSuspenseQuery(trpc.report.list.queryOptions());
const create = useMutation(
trpc.report.create.mutationOptions({
onSuccess: () => {
setTitle("");
queryClient.invalidateQueries({ queryKey: trpc.report.list.queryKey() });
},
}),
);
return (
<div className="flex flex-col gap-4 p-6">
<form
className="flex gap-2"
onSubmit={(e) => {
e.preventDefault();
create.mutate({ title });
}}
>
<Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Report title" />
<Button type="submit" disabled={create.isPending}>Create</Button>
</form>
<ul>
{reports.map((report) => (
<li key={report.id}>{report.title}</li>
))}
</ul>
</div>
);
}
Reusable pieces belong in packages/ui so the desktop app can use them too.
4. Add the page
apps/web/app/(home)/reports/page.tsx:
import { Suspense } from "react";
import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import LoadingState from "@workspace/ui/components/misc/LoadingState";
import { getQueryClient, trpc } from "@/trpc/server";
import ReportsList from "@/components/reports/ReportsList";
export default async function ReportsPage() {
const queryClient = getQueryClient();
await queryClient.ensureQueryData(trpc.report.list.queryOptions());
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<Suspense fallback={<LoadingState title="Loading reports" description="One moment" />}>
<ReportsList />
</Suspense>
</HydrationBoundary>
);
}
Pages under (home) are protected by the middleware automatically. Public pages go under app/landing and need no session.
5. Link it
Add an entry to the sidebar in apps/web/components/home/AppSidebar.tsx, next to the existing items.
6. Test it
apps/web/trpc/routers/__tests__/reportProcedures.test.ts:
import { describe, expect, it, vi } from "vitest";
import { reportRouter } from "../reportProcedures";
vi.mock("@workspace/database/client", () => ({
default: {
report: { findMany: vi.fn().mockResolvedValue([{ id: "r1", title: "Q3" }]) },
},
}));
describe("reportRouter", () => {
it("lists the user's reports", async () => {
const caller = reportRouter.createCaller({
session: { user: { id: "user_1", role: "user" } } as any,
headers: new Headers(),
});
await expect(caller.list()).resolves.toEqual([{ id: "r1", title: "Q3" }]);
});
it("rejects signed-out callers", async () => {
const caller = reportRouter.createCaller({ session: null, headers: new Headers() });
await expect(caller.list()).rejects.toThrow("logged in");
});
});
7. Check everything
pnpm typecheck && pnpm lint && pnpm test && pnpm arch:check
Variations
| Need | Do this |
|---|---|
| Admin-only feature | adminProcedure, and show the link only when session.user.role === "admin" |
| Paid feature | Check and deduct credits in the procedure: see Billing & Credits |
| Workspace data | orgProcedure and ctx.org.id: see Organizations & Teams |
| File uploads | A session route with guardRoute and the image helpers: see File Storage |
| Webhook or public endpoint | A route handler plus a route-policy row: see API Routes & Route Policy |
| New env var | .env.example, env.ts requirements, a doctor hint: see Environment Variables |
| Desktop or mobile screen | Reuse the packages/ui component; mobile screens go in apps/mobile/app/(home) |
