“对内类型安全、对外契约稳定”——同一批数据用两种 API 姿态对待。你做过的系统里,内部调用和对外接口是混在一起还是分开的?如果分开,你会怎么划界?tRPC 这种“前后端共享类型”的收益,在什么规模/团队结构下最划算?
The first three parts followed the write direction: how data comes in, where it's stored, how it's merged and persisted. From this part on
we trace reads in reverse — how the UI and SDKs query data back out. First stop: the web app's skeleton.
Langfuse's frontend is a Next.js app, with the vast majority of pages on the veteran Pages Router, running three API
styles in parallel: tRPC for its own UI, a public REST API for SDKs, and a handful of App-Router handlers for streaming/webhooks. Grasp this "door
map" and the next seven lessons won't get you lost.
🏢 Analogy
Think of the web app as a building (Next.js) with three doors for three kinds of visitors: a staff
entrance (tRPC — only for its own UI, type-safe, direct internal access), a public reception (REST /api/public —
for external SDKs, stable, versioned), and a special loading dock (App-Router / SSE handlers — for special cargo needing streaming
pushes or webhook callbacks). All three doors lead into the same building, the same data, but each serves its own crowd: staff skip
reception, external visitors can't use the staff entrance. Sort out these three doors and you've sorted out every Langfuse external interface.
One building, three doors
The big picture first. web/ is a Next.js app; under web/src sit a few big areas: features/ (vertical, by-feature
modules, dozens of them), components/ (shared UI, including the table system), server/ (auth + tRPC), pages/ (pages and API
routes), plus a small app/ (App Router). And the external interfaces are exactly the three doors from the intro:
features/vertical feature modules (dozens)
"Vertical slices" cut by business feature: traces, search-bar, public-api, batch-exports… each gathers its own pages, components, and server logic in one place. Most Langfuse code lives here.
components/shared UI
Cross-feature reusable components, most importantly components/table/ (Lesson 24) — lists, filtering, pagination, column control, row selection, the skeleton of the whole back-office UI.
server/auth + tRPC
server/api/{root,trpc}.ts is the tRPC root, middleware, and procedure definitions (Lesson 21); server/auth.ts is the NextAuth session. The "staff entrance" security check.
pages/ · app/routing
pages/ is the trunk (UI pages + API routes), app/ is just 4 files for special semantics. Plus hooks/, ee/ (enterprise), etc.
Pause on features/'s organizing philosophy: it's cut by "feature", not by "technical layer". A traditional layout might dump all
pages in pages/, all components in components/, all endpoints in api/ — finding one feature's code means hopping across
three or four directories. Langfuse inverts this: each feature (say search-bar, batch-exports) is a self-contained vertical slice gathering its
frontend components, state hooks, server logic, even a README under one features/<feature>/. The payoff: to understand or change a feature you
mostly read just one directory; boundaries between features are clear, so they don't entangle. That's why nearly every later lesson can point
precisely at a features/ subfolder.
Three doors, each serving its own crowd: tRPC (pages/api/trpc/[trpc].ts) for the UI, type-safe; REST (pages/api/public/**) for external SDKs, stable and versioned; special semantics (App Router app/api/** 4 files + a Pages-Router streaming SSE endpoint) for webhooks and streaming. Source: web/src/server/api/root.ts, web/src/features/public-api/, web/src/app/.
The request descends layer by layer (per web/src/server/api and web/src/pages): a browser action enters via Next.js pages//api and lands on the tRPC routers; the protectedProjectProcedure middleware checks project membership first, then the repository layer reads Postgres/ClickHouse. Each layer crosses one clear boundary — easy to test and swap.
web/src/pages/api/ & web/src/app/three API entries
// ① tRPC: the UI's type-safe backend, one file catches all ~62 routers
web/src/pages/api/trpc/[trpc].ts // → appRouter (Lesson 21)// ② public REST: the stable interface for SDKs, by resource + version folder
web/src/pages/api/public/traces/index.ts
web/src/pages/api/public/v2/scores/… // folder = version (Lesson 27)// ③ App Router: only 4 files, for endpoints needing raw Request/streaming/webhook
web/src/app/api/billing/stripe-webhook/route.ts
web/src/app/api/chatCompletion/route.ts
web/src/app/api/in-app-agent/route.ts
web/src/pages/api/dashboard/execute-query-stream.ts // SSE streaming dashboards
Why it's almost all Pages Router
You may notice a contrast: even though Next.js shipped the App Router long ago, Langfuse uses the old Pages Router for almost everything —
the App Router has all of 4 files. This isn't being behind the times; it's a pragmatic choice.
Pragmatic, not behind: Pages Router carries nearly all UI and APIs (tRPC + REST); App Router keeps just 4 files, for endpoints needing raw Request, streaming responses, webhook callbacks — semantics Pages Router handles awkwardly. Source: web/src/app/ (layout + 3 route.ts).
this door
for whom
where
why
tRPC
own UI (React)
pages/api/trpc/[trpc].ts
types flow backend → frontend, change one spot and the whole chain errors; internal API needn't be externally stable
public REST
external SDK / user scripts
pages/api/public/**
the external contract must be stable, versioned, with Fern generating multi-language SDKs (Lesson 27)
needs raw Request, text/event-stream, etc. — semantics a plain Pages-Router route handles awkwardly
Behind this split is a clear boundary: internally, seek "type-safe, fast to change"; externally, seek "stable contract, controlled versions".
The UI and backend are one team, one repo, so tRPC threads types end to end — the compiler errors instantly on refactors; whereas the SDK faces countless external
users, where a published interface can't change freely, so REST + version numbers + the Fern contract enforce strict stability. Same data, two external
postures — the internal API can evolve daily, the external contract must stay stable for years; forcing them into one API style would only hobble each
other. This is the master plan of Part 4's read path.
A preview of the whole read path: whichever door you enter, a "query data" request roughly takes these steps. The next seven lessons dive into each stop:
1
entry (tRPC or REST)
The UI fires a tRPC call, the SDK a REST request; each entry first does auth, confirming you can read this project (Lessons 21, 27).
2
filter & query build
The UI's FilterState (or SDK query params) is compiled into parameterized SQL, with the mandatory project_id and time window (Lesson 23).
3
repository executes
Through a unified ClickHouse executor: OTel span, query tags, backoff retry on failure, resource errors turned into friendly messages (Lesson 22).
4
read-model shaping
Lists use a "compact rows + lazy metrics" dual query; details fetch the "whole observation tree" — different read models per scenario (Lessons 24, 25).
5
return + frontend render
Results return to the UI, where the table system renders them fast and shareably with URL state, column presets, row selection (Lesson 24).
🎯 Design trade-off
Why not chase the trend and migrate fully to App Router, or just use REST as the one API? Because architecture choices should serve
team reality, not novelty. Langfuse laid a solid foundation on Pages Router + tRPC before the App Router matured — tRPC lets front and back
share one type system, the key to this full-stack team iterating fast; a rash migration is low-reward, high-risk. As for the API: internal and
external are two utterly different needs. Internal (UI) wants "change one spot, instant type-check across the chain" — tRPC fits perfectly;
external (SDK) wants "the integration I wrote two years ago still runs today" — which demands a stable contract and explicit versions. Force the two into one
API and you sacrifice either internal velocity or external stability. Langfuse's answer is don't force unity; divide and conquer by audience —
with App Router catching the few special semantics. Fit matters more than uniformity.
🎯 Key points
Langfuse's frontend is a Next.js app, mostly Pages Router; App Router is just 4 files for raw Request/streaming/webhook.
Three API styles coexist: tRPC (UI, type-safe), public REST (SDK, stable+versioned), special-semantics endpoints (App Router handlers + a Pages-Router streaming SSE, for webhook/streaming).
Core boundary: internally seek type-safety and iteration speed (tRPC), externally seek contract stability and version control (REST + Fern) — same data, two external postures.
This is Part 4's read-path overview; the next seven lessons drill into the tRPC backbone, repository layer, filtering, tables, detail, sessions, and the public REST API.
🧪 Self-test - think about the design
1. Why does Langfuse's web app run three API styles (tRPC, public REST, App-Router/SSE) rather than unifying into one?
because developers forgot to delete old code
because internal and external are two needs: the UI wants type-safety and fast change (tRPC, shared types front-to-back); SDKs want a stable, versioned contract (REST + Fern); a few streaming/webhook cases need raw Request semantics (App-Router). Forcing unity sacrifices one of them
because Next.js mandates all three
because each API is individually faster
Show answer & explanation click to expand
Answer: B. The core boundary: internally seek type-safety and iteration speed, externally seek a stable, versioned contract. UI and backend share one repo/team, so tRPC threads types and errors instantly on refactor; the SDK faces external users where published interfaces can't change freely, needing REST+versions+Fern. Same data, two external postures — dividing by audience fits better than forced uniformity.
2. Langfuse uses the old Pages Router for almost everything, with only 4 files under App Router. What does this show?
a pragmatic choice: Pages Router + tRPC is a solid foundation laid before App Router matured, so a rash migration is low-reward/high-risk; App Router is kept only for raw Request/streaming/webhook semantics Pages Router handles awkwardly
the codebase is outdated and unmaintained
the team doesn't know App Router exists
App Router is completely unusable
Show answer & explanation click to expand
Answer: A. Architecture serves team reality, not novelty. tRPC's shared types are key to fast full-stack iteration; migration is costly and low-reward. App Router's 4 files (layout + stripe-webhook/chatCompletion/in-app-agent) are exactly the cases needing raw Request, streaming, or webhook semantics — fit matters more than uniformity.
3. Langfuse's web/src cuts by 'feature' under features/ (~80 vertical modules) rather than by 'technical layer' (all pages/all components/all APIs each in one dir). The main benefit?
each feature is a self-contained vertical slice gathering its components, state, and server logic in one place; to understand or change a feature you mostly read one directory, with clear boundaries that don't entangle
to force all features to share code
to have fewer directories
to make builds faster
Show answer & explanation click to expand
Answer: A. By-feature (vertical-slice) organization gathers a feature's whole code under features//, avoiding hops across pages/components/api. Localized changes and clear boundaries are key to large-frontend maintainability — which is why nearly every later lesson points at a features/ subfolder.
💭 Open questions (no single right answer - just think or try)
'Internal type-safety, external stable contract' — the same data treated with two API postures. In systems you've built, are internal calls and external interfaces mixed or separated? If separated, how would you draw the line? At what scale/team structure does tRPC's 'shared types front-to-back' pay off most?