「把安全检查收敛成中间件、用声明式 procedure 组合,而不是每个接口各写一遍」——这条原则你能用到自己的系统吗?如果你的 API 有几十个端点都要做同一种权限校验,你会怎么设计,才能让「新增端点几乎不可能漏掉校验」?
Last lesson named the three doors; this one pushes open the "staff entrance" — tRPC — and shows its skeleton. tRPC is the type-safe
contract between UI and server: types the backend defines flow end to end to the frontend caller, so a change in one place errors the
whole chain instantly. Its structure is surprisingly lean: one root router aggregates ~62 feature routers, plus a handful of "procedure
builders" that guard auth and RBAC uniformly via layered middleware. Grasp this middleware stack and you grasp the security and the flow
of Langfuse's entire UI backend.
🛂 Analogy
Think of each tRPC request as walking a security corridor. The checkpoints along it are the middleware: first a camera
logs that you came (OTel tracing), then a responder stands ready to catch exceptions (error handling), then an ID check (are you
logged in), and finally the guest list (are you on the access list for this room — i.e. "are you a member of this project").
Different doors (procedures) carry different numbers of checkpoints: a public door passes only the first two, a protected door walks them all. Define a
checkpoint once, each door picks what it needs — that's the essence of procedure builders.
A procedure = a stackable middleware chain
The essence of tRPC: a procedure is built by stacking middleware. Each middleware does one thing, chained in .use() order; different
procedure builders stack different checkpoints. Langfuse defines a set in web/src/server/api/trpc.ts: from the bare-bones publicProcedure to
the layered protectedProjectProcedure.
Layered middleware, composed on demand: publicProcedure(OTel+error) → authenticatedProcedure(+login) → protectedProjectProcedure(+project-member RBAC). Plus variants protectedOrganizationProcedure, protectedGetTraceProcedure. Source: web/src/server/api/trpc.ts:238-583.
One type runs end to end (per web/src/server/api/trpc.ts): the component's query and the server procedure share the same TypeScript types, so a front/back mismatch fails at compile time. The key step is the protectedProjectProcedure middleware — before any procedure runs it checks project membership first (Lessons 10, 48).
web/src/server/api/trpc.tsprocedure builders
const withOtelTracingProcedure = t.procedure.use(withOtelInstrumentation);
// public: only OTel + error handlingexport const publicProcedure = withOtelTracingProcedure.use(withErrorHandling);
// authenticated: add a "are you logged in" layerexport const authenticatedProcedure = withOtelTracingProcedure
.use(withErrorHandling).use(enforceUserIsAuthed);
// protected (project-level): add "are you a member of this project" — the most usedexport const protectedProjectProcedure = withOtelTracingProcedure
.use(withErrorHandling).use(enforceUserIsAuthedAndProjectMember);
Note the first two layers every door stacks — OTel tracing and error handling — are the common base of all
procedures. The error-handling layer (withErrorHandling) is especially careful: it uniformly translates resolver exceptions into a
frontend-friendly form — hiding 5xx internal detail and stacks (no leaks), and specially caring for ClickHouse resource errors (out-of-memory,
query timeout), mapping them to UNPROCESSABLE_CONTENT with actionable advice like "try a smaller time range". So whatever router,
whatever blew up, the user sees a consistent, readable error that doesn't expose the internals.
A UI query's journey, and RBAC's key move
Put this skeleton into a real data flow. A React Query hook in the UI (e.g. api.traces.all.useQuery) fires a call, through the unified entry
pages/api/trpc/[trpc].ts; first createTRPCContext injects the context — attaching { session, headers, prisma }
to every request (session from NextAuth); then the middleware stack runs, finally reaching the router's resolver, which calls a @langfuse/shared
repository/service to read ClickHouse/Postgres:
From hook to database: createTRPCContext (trpc.ts:57) injects {session, headers, prisma} into every request; the middleware stack guards auth/RBAC; the resolver calls a @langfuse/shared repository. The return type threads all the way to the frontend. Source: root.ts:70 (appRouter aggregates ~62 routers).
That context injected into every request looks unremarkable but is the bedrock — it gathers, in one shot, "who is this request, what did it
carry, what tools may it use":
sessionwho you are (NextAuth)
The current logged-in user and their "organization → project" membership tree. The RBAC middleware reads exactly this tree to decide whether you can access a project — identity arrives with the session, no per-request DB lookup.
headerswhat the request carried
Raw request headers, used by cross-cutting concerns like rate limiting, tracing, feature flags — e.g. rate-limit by source, or tie the request to an OTel trace.
prismawhat tools you may use
The Postgres client (Lesson 9), letting resolvers and middleware read control-plane data (e.g. the admin fallback looking up a project's owning org). ClickHouse is fetched on demand by the repository layer (Lesson 22).
RBAC's key move hides in enforceUserIsAuthedAndProjectMember: rather than waiting for the resolver, it pulls projectId out of the
request input at the middleware stage, then checks the session for "are you a member of this project". This way every protected router gets uniform
tenant checking automatically, never re-written per router, and no backdoor left by one router author's lapse (echoing Lesson 10's "project_id is the
isolation key"):
const enforceUserIsAuthedAndProjectMember = t.middleware(async (opts) => {
if (!ctx.session?.user) throw new TRPCError({ code: "UNAUTHORIZED" });
// key: pull projectId out of the raw input, before the resolverconst input = inputProjectSchema.parse(await opts.getRawInput());
// search the session's "org → project" tree: are you a member of this project?const member = ctx.session.user.organizations
.flatMap((org) => org.projects)
.find((p) => p.id === input.projectId);
if (!member && !ctx.session.user.admin) throw new TRPCError({ code: "FORBIDDEN" });
return next({ /* attach the verified scope to ctx */ });
});
procedure
checkpoints stacked
used where
publicProcedure
OTel + error handling
no login (health check, public share)
authenticatedProcedure
+ login check
account-level, cross-project ops
protectedProjectProcedure
+ project-member RBAC
most business routers (traces/scores/…)
protectedOrganizationProcedure
+ org-member check
org-level admin
protectedGetTraceProcedure
+ trace-access check (incl. public traces)
single-trace reads (allows public share)
😖 if each router wrote its own auth
62 routers each hand-write "check login, check project membership". One person forgetting it, or writing it inconsistently, and that spot becomes a tenant-isolation breach — another project's data could be read. Security code dreads exactly this "single omission".
😀 converged into middleware + procedure
The check is written once, tested once; a router author just picks the right door (protectedProjectProcedure) and RBAC applies automatically and uniformly. A new router can hardly miss tenant checking — security backstopped by structure.
🎯 Design trade-off
Why make auth a "middleware + procedure builder" rather than an if-check hand-written in each router? Because security code most fears
"omission" and "drift". If 62 routers each hand-write "check login, check project membership", sooner or later someone forgets one, or writes it
inconsistently — and that one spot is a hole in tenant isolation. Converging the checks into a few middleware, then composing them
declaratively via procedure builders, means a router author only picks the right "door" (protectedProjectProcedure) and RBAC takes
effect automatically and uniformly. Even better is the "pull projectId from the input" move: it makes the check happen
before business logic, so no protected router can ever touch data without verifying the tenant first. This is Lesson 6's "converge complexity
into one strictly testable place" and Lesson 10's "project_id is the isolation key" landing at the API layer — security guaranteed by structure, not by
everyone's diligence.
🎯 Key points
tRPC is the type-safe contract between UI and backend: one root router appRouter (root.ts:70) aggregates ~62 feature routers, the return type threading to the frontend.
context (createTRPCContext) injects { session, headers, prisma } into every request; session from NextAuth.
A procedure = a stackable middleware chain: publicProcedure(OTel+error) → authenticatedProcedure(+login) → protectedProjectProcedure(+project RBAC).
RBAC's key move: enforceUserIsAuthedAndProjectMember pulls projectId from the input at the middleware stage and checks session membership — uniform, before the resolver (echoing Lesson 10).
Tradeoff: converging auth into middleware + declarative procedures avoids 62 routers each writing (and mis-writing) it; security guaranteed by structure (Lesson 6). The error layer also turns ClickHouse resource errors into friendly advice.
🧪 Self-test - think about the design
1. Langfuse defines tRPC endpoints with procedure builders (publicProcedure / authenticatedProcedure / protectedProjectProcedure). What's the essence of this 'layered middleware stack'?
a procedure is a stack of middleware chained by .use(); a public door passes only OTel+error handling, a protected door adds login and project-member checks. Middleware is defined once and each router picks what it needs — RBAC isn't rewritten per router
only one middleware is allowed, no stacking
procedures just name endpoints, with no real effect
every router must hand-write full auth logic
Show answer & explanation click to expand
Answer: A. tRPC's essence is procedure = stackable middleware. withOtelTracingProcedure adds OTel, then .use(withErrorHandling) gives publicProcedure, then .use(enforceUserIsAuthed) gives authenticatedProcedure, then swapping in enforceUserIsAuthedAndProjectMember gives protectedProjectProcedure. Declarative composition lets a security check be written once and reused everywhere.
2. protectedProjectProcedure's RBAC middleware does one key thing: it pulls projectId from the request input before the resolver runs. Why does this matter?
to make requests return faster
projectId is only used for logging
the check happens before business logic: no protected router can ever touch data before verifying 'you're a member of this project', so tenant isolation is guaranteed by structure, not by each router author's diligence
to save database connections
Show answer & explanation click to expand
Answer: C. enforceUserIsAuthedAndProjectMember pulls projectId via getRawInput(), then checks membership in the session's 'org→project' tree, throwing FORBIDDEN otherwise. This gives every protected router uniform, up-front tenant checking — Lesson 10's 'project_id is the isolation key' landing at the API layer, security by structure not by people.
3. All procedures stack withErrorHandling at the base. What special handling does it give ClickHouse resource errors (out-of-memory, timeout)?
automatically retries a hundred times
ignores the error and returns empty results
returns the raw stack and SQL straight to the frontend
maps them to UNPROCESSABLE_CONTENT with actionable advice like 'try a smaller time range'; and hides 5xx internal detail and stacks to prevent leaks
Show answer & explanation click to expand
Answer: D. withErrorHandling uniformly translates exceptions: 5xx hides internal detail to prevent leaks; ClickHouse resource errors (memory/timeout) are special-cased to UNPROCESSABLE_CONTENT with actionable advice like 'narrow the time range'. So whatever router blew up, the user sees a consistent, readable error that doesn't expose internals.
💭 Open questions (no single right answer - just think or try)
'Converge security checks into middleware and compose via declarative procedures, rather than hand-writing per endpoint' — can you apply this to your systems? If your API has dozens of endpoints all needing the same permission check, how would you design it so 'a new endpoint can hardly miss the check'?