Admin app
apps/web is the internal, authenticated Campus OS surface today — and it is admin-only, by
deliberate scoping rather than accident. The architecture docs describe admin, faculty, HoD, IQAC,
warden, and placement portals; no wired-up /portal/* self-service surface exists yet.
Built on TanStack Start (Vite dev server on port 3000) with TanStack Router, TanStack Query, and
TanStack Table. API access goes through a single typed Hono RPC client
(apps/web/src/lib/api-client.ts) — hc<AppType> importing the API's route type, with
credentials: "include" so the Better Auth session cookie rides along. That is what gives
end-to-end type safety without hand-written per-endpoint wrappers.
Every admin page uses TanStack Start's real streaming SSR (route loader + Suspense), not
client-fetch-after-mount, and the whole section runs on a distinct Aurora dark visual system —
both covered in their own sections below, since this is the part most likely to trip up a new
contributor adding a page the old way.
Routes
| Route file | Path | Streams? | What it does |
|---|---|---|---|
__root.tsx | — | — | Root layout, Header/Footer, providers, request-scoped QueryClient |
index.tsx | / | — | Landing / redirect |
login.tsx | /login | — | Email + password sign-in against apps/api |
about.tsx | /about | — | Static |
admin.tsx | /admin | — | Admin shell layout (Aurora sidebar/nav) |
admin.index.tsx | /admin | No data | Dashboard — static welcome card, nothing to stream |
admin.departments.tsx | /admin/departments | Yes (4 sections) | Org structure — departments, programmes, branches, batches |
admin.people.tsx | /admin/people | — | Pure <Outlet/> layout, no content of its own |
admin.people.index.tsx | /admin/people | Yes | Searchable/sortable people list + "Add Person" |
admin.people.$personId.tsx | /admin/people/:id | Yes (2 boundaries) | Person detail + attendance history, each its own Suspense boundary |
admin.curriculum.tsx | /admin/curriculum | Yes (2 sections) | Subjects and class sections, each filterable/paginated |
admin.attendance.tsx | /admin/attendance | Yes (3 sections) | Assignments, delegations — roster marking stays a plain query (see below) |
admin.settings.tsx | /admin/settings | Yes (4 sections) | Modules, custom fields, reference data, audit log |
admin.colleges.tsx | /admin/colleges | Yes | Platform-admin only — list/create colleges, switch into one |
admin.legacy-data.tsx | /admin/legacy-data | Yes (table list only) | Table browser — row viewer stays a plain query (see below) |
routeTree.gen.ts is generated — run bun --filter '@campus/web' generate-routes (tsr generate)
after adding a route.
Streaming architecture
Every data-bearing admin page fetches through TanStack Router's loader + TanStack Query's
queryOptions/useSuspenseQuery, wrapped in <Suspense> — real SSR streaming, not the
client-fetch-after-mount-and-show-a-spinner pattern the admin app used before. Concretely, per
section of a page:
// 1. A queryOptions() factory — the single source of truth for the query's key + fetcher,
// shared between the loader below and every component that reads this data.
const departmentsQueryOptions = queryOptions({
queryKey: ['departments'],
queryFn: async () => {
const res = await apiClient['org-structure'].departments.$get()
if (!res.ok) throw new Error('failed to load departments')
return res.json()
},
})
// 2. The route's loader kicks the fetch off — deliberately NOT awaited. An
// awaited loader blocks navigation until the data resolves (no streaming,
// just moving the spinner earlier); leaving the promise unawaited lets the
// shell render immediately and each section's own Suspense boundary
// stream its content in independently as its query resolves.
export const Route = createFileRoute('/admin/departments')({
loader: ({ context }) => {
context.queryClient.ensureQueryData(departmentsQueryOptions)
},
component: DepartmentsPage,
})
// 3. The component reads the SAME queryOptions via useSuspenseQuery — same
// queryKey means it reuses the in-flight promise the loader started, not a
// second fetch — wrapped in its own <Suspense> boundary by the parent.
function DepartmentsSection() {
const query = useSuspenseQuery(departmentsQueryOptions)
// query.data is always defined — no isLoading/error branches needed here.
}
Why one <Suspense> boundary per section, not one per page. A page with four independent
sections (like Settings: modules, custom fields, reference data, audit log) gets four separate
<Suspense> boundaries, each wrapping exactly one section's component. This is what makes a slow
section (say, a large audit log page) never block a fast one (modules) from appearing — they
resolve and paint independently. A single page-level boundary would make every section wait for the
slowest.
The router plumbing this depends on
router.tsx's getRouter() creates a fresh QueryClient per call (via
lib/query-client.ts's createQueryClient() factory) and passes it through
context: { queryClient } — this is what loader: ({ context }) => ... above is reading. This
replaced a real bug: the QueryClient used to be a module-level singleton, shared across every
concurrent SSR request — a genuine cross-request cache-leak risk, not just a style issue, fixed as
a side effect of wiring streaming up properly. __root.tsx's RootDocument reads the same instance
back out via Route.useRouteContext() for the QueryClientProvider — one source of truth, not two.
Two deliberate exceptions — not every query converts
Suspense has no concept of "maybe never fetch this." Two queries stay plain useQuery with
enabled: false on purpose, because they're genuinely conditional on a user action that may never
happen:
admin.attendance.tsx's roster query — nothing to fetch until a class section, subject, and date are picked and "Load Roster" is clicked.admin.legacy-data.tsx's row viewer — nothing to fetch until a table is selected from the list.
Forcing either into useSuspenseQuery would mean the loader has nothing meaningful to prefetch and
the component would suspend on a query that may never resolve. The table list on both pages
(unconditional, always fetched) still streams normally; only the conditional child query stays
as-is. If you're converting a new page and hit a query gated by enabled:, this is the pattern —
don't force it.
Errors: errorComponent, not an isError branch
useSuspenseQuery throws on failure instead of setting isError/data to a fallback, so the old
if (query.isError) return <ErrorMessage/> pattern doesn't apply anymore. Use the route's
errorComponent instead — TanStack Router's own mechanism for this, which catches both loader
rejections and thrown Suspense errors from anywhere in that route's component tree:
export const Route = createFileRoute('/admin/colleges')({
loader: ({ context }) => context.queryClient.ensureQueryData(platformTenantsQueryOptions),
errorComponent: () => <p>You don't have superadmin access to manage colleges.</p>,
component: CollegesPage,
})
admin.colleges.tsx is the concrete example — a non-platform-admin's 403 from
GET /platform-tenants surfaces exactly this way.
Filtering and pagination without a loading flash
Changing a filter, page, or search box re-triggers the query for that section — without care, this
means the <Suspense> fallback flashes on every click or keystroke, which reads as broken, not
fast. Two React patterns fix this, used depending on what's changing:
startTransitionwraps state updates from discrete actions — clicking a pagination button, changing a dropdown filter. React marks the update as low-priority and keeps the current content on screen until the new data is ready, instead of dropping to the fallback. Used inadmin.settings.tsx's audit log pager,admin.curriculum.tsx's two filtered sections,admin.people.$personId.tsx's attendance-history pager.useDeferredValueis the right tool specifically for a search box driving a query — the input itself stays perfectly responsive to every keystroke (it's real, synchronous state), while a deferred copy of that value is what actually feeds the query, catching up once typing pauses.admin.people.index.tsx's search field does this, plus a subtleopacity-60dim on the table whilesearch !== deferredSearchso it's visually clear results are catching up, not stuck.
Checklist for converting (or writing) a page
- Define a
queryOptions()factory per independent data section — parameterized as a plain function (function fooQueryOptions(filter) { return queryOptions({...}) }) if the query has filter/pagination state, a plain constant if it doesn't. - Add a
loaderthat callscontext.queryClient.ensureQueryData(...)for each factory, unawaited. - Replace
useQuery(...)withuseSuspenseQuery(fooQueryOptions(...))in the component; delete theisLoading/errorbranches —query.datais always defined. - Wrap each independent section in its own
<Suspense fallback={...}>in the parent, usingcomponents/ui/skeleton.tsx'sSkeleton/TableSkeletonfor the fallback. - If a component that calls
useSuspenseQueryis the one the route renders directly (not a child of the page component), split it: a thin wrapper that owns the<Suspense>boundary, and an inner component that actually calls the hook.admin.people.$personId.tsx'sPersonDetailPage→PersonDetailsplit is the reference example — necessary because a component can't be inside its own Suspense boundary. - If the query is genuinely conditional (
enabled: falsefor some state), leave it asuseQuery— see above. - If the page has an auth/permission-gated query that can legitimately fail for a normal user
(not a bug), add an
errorComponentrather than anisErrorbranch.
What the settings screen actually contains
Four sections in one page, each backed by a real endpoint:
- Modules — a badge per module the tenant is entitled to, from
GET /modules. Read-only: there is no UI or endpoint to enable or disable an entitlement yet. - Custom Fields — a table of this tenant's
custom_field_definitionsplus a create form (entity, key, label, type, enum options when type isenum, required flag, visibility). This is the no-migration extension mechanism exposed end to end. The option lists are duplicated as literals in this file with a comment pointing atpackages/db/src/schema/tenancy.tsas the source of truth — a candidate for a shared export, since the two can drift. - Reference Data — all six global lookup tables as badge groups with counts. Read-only; the reference tables are platform-managed and intentionally not tenant-writable.
- Audit Log — the paginated audit trail (50 per page) with a Previous/Next pager, action badges
coloured by create/delete/update, and the acting person resolved by name where available. Note
this is
requirePermission({ auditLog: ["view"] }), so a non-admin gets an error here.
The Colleges page and the platform-admin nav item
admin.colleges.tsx is the one route in this app not scoped to the current tenant — it calls
GET /platform-tenants (gated by requirePlatformAdmin, see API Surface)
to list every college on the platform, regardless of which one is currently active. A regular
tenant-scoped admin gets a 403 there, which the page renders as a plain "you don't have superadmin
access" message rather than crashing.
The sidebar's "Colleges" nav item itself only appears for platform admins — admin.tsx runs the
same GET /platform-tenants call as a background probe (staleTime: Infinity, since this doesn't
change during a session) and conditionally includes the nav item based on whether it succeeds. This
is the one piece of permission-aware navigation in an otherwise not-permission-aware shell (see
"Known limitations" below) — deliberately narrow, since platform admin is a genuinely separate,
rarely-granted identity rather than a role variant most users have.
The sidebar header also shows the active organization's name (authClient.useActiveOrganization())
instead of a static "Admin" label, so which college's data is on screen is always visible — useful
for anyone, but especially a platform admin who can switch colleges from /admin/colleges's
"Manage" button (POST /platform-tenants/:id/join then authClient.organization.setActive()).
Design system: Aurora
The admin app runs a distinct dark visual identity — deep-ink base, evolved from the earlier
teal/lagoon palette rather than a full break, with a teal/violet accent pair. Defined as real
Tailwind v4 theme colors in apps/web/src/styles.css's @theme block
(--color-aurora-50 … --color-aurora-950, --color-accent-teal, --color-accent-violet, plus
-strong variants of each accent for light-background contrast) — not just CSS custom properties,
so admin pages use ordinary Tailwind utility classes (bg-aurora-900, text-aurora-50,
text-accent-teal) the same way they always have, just with new tokens.
The admin shell is always dark, independent of the site-wide light/dark toggle — admin.tsx
wraps its root in a scoped dark class rather than relying on the toggle's resolved state. This is
deliberate: Header/Footer (and the toggle they contain) are already hidden for every
/admin/*//portal/* route (see __root.tsx's isAppShell), so there was no visible control to
respect in the first place — a console/ops-tool aesthetic, not tied to OS preference. If a toggle
is ever added inside the admin shell, this scoping is what would need to come out.
One real fix bundled into this: Tailwind v4's dark: variant defaults to following
prefers-color-scheme, not this app's manual class-based toggle — @custom-variant dark (&:where(.dark, .dark *)); in styles.css is what makes dark: utilities actually respond to the
.dark/.light classes ThemeToggle.tsx sets. Without it, dark: classes anywhere in the app
would silently ignore the toggle. This existed before the Aurora work and was never exercised (the
marketing pages set the toggle but the admin section, until now, had zero dark: usage to expose
the gap).
Animation primitives, alongside the pre-existing rise-in/shimmer keyframes (kept, reused):
| Class | What it does | Used for |
|---|---|---|
.rise-in | Fade + rise on mount | Cards, page headers |
.stagger-in | Same, with a delay driven by a --stagger-index inline custom property | List/table rows, nav items — set style={{ '--stagger-index': index }} per item instead of computing a delay string in JS |
.glass-surface | Translucent blur background | The admin sidebar |
.glow-teal-hover / .glow-violet-hover | Lift + colored glow on hover | Primary interactive elements (buttons, "Manage" actions) |
.animate-shimmer | Sweeping shimmer | components/ui/skeleton.tsx's loading placeholders |
Components
components/ui/ holds the primitives — badge, button, card, input, label, select,
skeleton, table — written as local components rather than pulled from a UI library, styled with
Tailwind CSS v4 via @tailwindcss/vite and, as of the Aurora redesign, the aurora-*/accent-*
tokens above with dark: companions throughout. skeleton.tsx (Skeleton, TableSkeleton) is the
newest — the standard <Suspense> fallback across every streaming page, described above. There is
a Header, Footer, ThemeToggle, and a person-picker used wherever a route needs to choose a
person.
There is no shared design system package between web and mobile yet; mobile does not exist yet, so the token-drift problem the architecture doc anticipates has not arrived.
Known limitations
- No self-service surface. Students, faculty, and parents have no UI. Faculty cannot mark
attendance through the app today even though
POST /attendance/recordssupports them — the authorization logic for it is built and tested at the API layer. - No permission-aware navigation, with one exception. The shell renders the same nav regardless
of org-level role (admin/faculty/student/staff) — combined with the read-side authorization gap in
API Surface, a low-privilege user logging in will
see screens whose writes fail with
403rather than being hidden. The one exception is the "Colleges" nav item, shown only to platform admins (see above) — narrow because that identity is rare and genuinely separate, not a template for the rest of the nav. - No real-time updates — streaming SSR is not the same thing as live updates, and it's worth being
precise about the difference. The streaming architecture above makes the initial load of a
page progressively render as each section's data resolves; it does not push new data to an
already-open page when something changes elsewhere. Everything is still request/response
underneath. The TanStack DB + ElectricSQL live-view architecture in
TECHNICAL_ARCHITECTURE.md§7 — genuinely reactive, server-push updates — is intentionally a later, separate concern. - Streaming/Suspense conversion is complete for every data-bearing admin page (see the Routes
table's "Streams?" column) — this isn't a partial rollout with some pages still on the old
pattern. The two
enabled: falseexceptions (attendance roster, legacy-data row viewer) are a deliberate architectural boundary, not gaps to close later. - No custom-field rendering on forms. Custom fields can be defined in settings, and the schema
stores their values in the target row's
attributesJSONB — but the person/enrollment/employment forms do not yet render inputs for the definitions that exist.