Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

♻️ Introduce loaders.ts: split request facing reads from the parameterized DAL (#2737)

Luke Vellaaf047e6a6477
diff --git a/CLAUDE.md b/CLAUDE.md
index 4583d5f62..b4c84d395 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -179,7 +179,8 @@ Always use gitmoji prefixes in commit messages. Follow the gitmoji convention (h
**Feature file vocabulary** — closed set; new file names require a team decision. Applies recursively in sub-concern directories:
-- `data.ts` — reads (Prisma queries), must start with `import "server-only"`
+- `data.ts` — parameterized reads (Prisma queries), must start with `import "server-only"`. Trusts its input: every query takes explicit arguments and carries its tenant scope in the where clause. Never reads the request — no `next/headers`, `next/navigation`, or session state (lint enforced)
+- `loaders.ts` — request facing reads: resolve the actor from the session, apply page semantics (redirects to /login and /setup, `InvalidSessionError` on bans), and delegate to `data.ts` with proven scope. Loaders always consume `data.ts`, never the reverse, and never import `@rallly/database` — so query logic cannot fork between the session path and the API path. Server components call loaders; API routes, webhooks and cron call `data.ts` with proven scope from their own gate (API routes are lint banned from `@/features/**/loaders`). Naming note: `session-data.ts` and `queries.ts` were considered and rejected
- `mutations.ts` — writes + cache invalidation, must start with `import "server-only"`. Trusts its input: takes explicit parameters (`userId`, not headers), no session reads, no `headers()`, callable from system contexts (webhooks, cron, moderation). Authorization happens in `actions.ts` (safe-action middleware + CASL against the database). Never call Better-Auth endpoints from a mutation — they resolve the target user from request headers and authorize against the session snapshot; use adapter-level APIs (`authLib.$context` → `internalAdapter`) instead
- `actions.ts` — `"use server"` actions, thin wrappers over mutations, validated via safe-action + `schema.ts`. Owns authentication and authorization (safe-action clients + CASL checks against database state, never against the session snapshot). Exception to the thin-wrapper rule: writes whose target user is defined by the session (self-profile updates) call the Better-Auth endpoint directly in the action — the endpoint refreshes the session snapshot and cookie cache in one step. Rule of thumb: target user from a parameter → mutation via `internalAdapter`; target user from the session → Better-Auth endpoint in the action
- `schema.ts` — Zod schemas (isomorphic, no Prisma imports)
@@ -193,7 +194,16 @@ Always use gitmoji prefixes in commit messages. Follow the gitmoji convention (h
- `assets/` — static files used by the feature
- NOT allowed: `index.ts` barrels, `helpers.ts`, `queries.ts`, `hooks.ts`, `lib/`, `libs/`
-**DAL enforcement** — `@rallly/database` may only be imported from `features/**/data.ts` and `features/**/mutations.ts` (lint-enforced via `noRestrictedImports`; existing violations sit on a shrinking migration allowlist in `apps/web/biome.json`). Parameterized reads take their tenant scope as `spaceId: AuthorizedSpaceId` (from `@/features/space/types`); only the session gate (`createSpaceDTO`) and the API key middleware may cast to it. API routes under `app/api/**` (except tRPC and better-auth) must not import session scoped DAL modules — they authenticate their own way and pass proven scope to parameterized reads. `api/private` handlers own serialization and must parse response bodies through their zod schemas.
+**Read/write symmetry** — the request facing / core split is the same on both sides:
+
+| | Request facing (session, redirects, auth) | Core (parameterized, trusts input) |
+| -- | -- | -- |
+| Reads | `loaders.ts` | `data.ts` |
+| Writes | `actions.ts` | `mutations.ts` |
+
+**Loader placement** — route by default, promote on the second consumer. Page data needs are view shaped, so the server component composes in the route: it calls the session gate loaders (`getActiveSpace()`, `requireUser()` — both trust the session cookie cache, no database read; `getCurrentUser()` is the database-verified read for pages that need DB-fresh user state) and passes proven scope to `data.ts` reads; extract to a route private file only when the page gets long. Never import another route's loader. Promote to `features/<domain>/loaders.ts` only when a second route segment needs the same read — that is evidence of a domain concept, not a view shape. The test: a loader belongs in the feature when its contract is stated in domain terms and every consumer wants exactly that contract; it stays in the route when its shape is "what this page happens to display." Most features never have a `loaders.ts` (today: `space`, `user`).
+
+**DAL enforcement** — `@rallly/database` may only be imported from `features/**/data.ts` and `features/**/mutations.ts` (lint-enforced via `noRestrictedImports`; existing violations sit on a shrinking migration allowlist in `apps/web/biome.json`; `loaders.ts` is absent from the allowlist, so database imports are banned there by default). Parameterized reads take their tenant scope as `spaceId: AuthorizedSpaceId` (from `@/features/space/types`); only the session gate (`createSpaceDTO`) and the API key middleware may cast to it. API routes under `app/api/**` (except tRPC and better-auth) must not import `@/features/**/loaders` — they authenticate their own way and pass proven scope to parameterized reads. `api/private` handlers own serialization and must parse response bodies through their zod schemas.
**Cross-feature imports** — allowed, public surface only (the vocabulary files above); never reach into another feature's internals. No cycles between features (CI-enforced). For UI, prefer composing multiple features at the page level in `app/` over feature-to-feature component imports.
diff --git a/apps/web/biome.json b/apps/web/biome.json
index 2d5482eff..4be9cee64 100644
--- a/apps/web/biome.json
+++ b/apps/web/biome.json
@@ -161,11 +161,8 @@
},
"patterns": [
{
- "group": [
- "@/features/user/data",
- "@/features/api-keys/data"
- ],
- "message": "Session scoped DAL modules derive the actor from cookies and must not be used in API routes. Webhooks, cron and API key routes authenticate their own way and pass proven scope to parameterized reads."
+ "group": ["@/features/**/loaders"],
+ "message": "Loaders derive the actor from session cookies and must not be used in API routes. Webhooks, cron and API key routes authenticate their own way and pass proven scope to parameterized reads in data.ts."
},
{
"group": ["@/utils", "@/utils/**"],
@@ -202,11 +199,8 @@
},
"patterns": [
{
- "group": [
- "@/features/user/data",
- "@/features/api-keys/data"
- ],
- "message": "Session scoped DAL modules derive the actor from cookies and must not be used in API routes. Webhooks, cron and API key routes authenticate their own way and pass proven scope to parameterized reads."
+ "group": ["@/features/**/loaders"],
+ "message": "Loaders derive the actor from session cookies and must not be used in API routes. Webhooks, cron and API key routes authenticate their own way and pass proven scope to parameterized reads in data.ts."
},
{
"group": ["@/utils", "@/utils/**"],
@@ -370,6 +364,8 @@
"paths": {
"dayjs": "Use the formatters in `@/lib/datetime` for display. dayjs is only allowed in files on the migration allowlist (see overrides in biome.json).",
"@/lib/dayjs": "Use the formatters in `@/lib/datetime` for display. dayjs is only allowed in files on the migration allowlist (see overrides in biome.json).",
+ "next/headers": "The DAL core trusts its input: data.ts and mutations.ts take explicit parameters and never read the request. Session and request facing reads belong in loaders.ts, writes resolve their actor in actions.ts.",
+ "next/navigation": "The DAL core trusts its input: data.ts and mutations.ts take explicit parameters and never redirect. Page semantics (redirects) belong in loaders.ts or the route.",
"@/lib/posthog": {
"message": "User-attributed analytics events must go through track() from @/lib/posthog so guest person-profile handling cannot be forgotten at capture sites. The raw client is reserved for non-capture APIs (feature flags, identity merge) in allowlisted files (see overrides in apps/web/biome.json).",
"importNames": ["posthog"]
@@ -485,7 +481,7 @@
"useFilenamingConvention": {
"level": "warn",
"options": {
- "match": "(?:data|mutations|actions|schema|types|ability|constants|utils|service)[.]ts|client[.]tsx|.+[.]test[.]tsx?",
+ "match": "(?:data|loaders|mutations|actions|schema|types|ability|constants|utils|service)[.]ts|client[.]tsx|.+[.]test[.]tsx?",
"filenameCases": ["kebab-case"]
}
}
diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/polls/page.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/polls/page.tsx
index 7c2f7c3ca..5a3a86d95 100644
--- a/apps/web/src/app/[locale]/(space)/(dashboard)/polls/page.tsx
+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/polls/page.tsx
@@ -1,7 +1,7 @@
import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import type { Metadata } from "next";
import { getPollStatusCounts } from "@/features/poll/data";
-import { getActiveSpace } from "@/features/space/data";
+import { getActiveSpace } from "@/features/space/loaders";
import { getTranslation } from "@/i18n/server";
import { createPrivateSSRHelper } from "@/trpc/server/create-ssr-helper";
import { PollsPage } from "./polls-page";
diff --git a/apps/web/src/app/[locale]/(space)/layout.tsx b/apps/web/src/app/[locale]/(space)/layout.tsx
index 0cc9547c9..fd8d85982 100644
--- a/apps/web/src/app/[locale]/(space)/layout.tsx
+++ b/apps/web/src/app/[locale]/(space)/layout.tsx
@@ -1,7 +1,7 @@
import { SessionRefresher } from "@/components/session-refresher";
import { PayWall } from "@/features/billing/components/pay-wall";
import { SpaceProvider } from "@/features/space/client";
-import { getActiveSpace } from "@/features/space/data";
+import { getActiveSpace } from "@/features/space/loaders";
import { UserProvider } from "@/features/user/client";
import { TimeZoneMismatchDialog } from "@/features/user/components/timezone-mismatch-dialog";
import { getLocale } from "@/i18n/server/get-locale";
diff --git a/apps/web/src/app/[locale]/(space)/settings/api-keys/components/api-keys-list.tsx b/apps/web/src/app/[locale]/(space)/settings/api-keys/components/api-keys-list.tsx
index 039f2bf5a..a1e3c2380 100644
--- a/apps/web/src/app/[locale]/(space)/settings/api-keys/components/api-keys-list.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/api-keys/components/api-keys-list.tsx
@@ -15,10 +15,7 @@ import { Trans } from "@/i18n/client";
import { useDateTime } from "@/lib/datetime/client";
import { RevokeApiKeyButton } from "./revoke-api-key-button";
-type ApiKey = Extract<
- Awaited<ReturnType<typeof getSpaceApiKeys>>,
- { ok: true }
->["apiKeys"][number];
+type ApiKey = Awaited<ReturnType<typeof getSpaceApiKeys>>[number];
export function ApiKeysList({ apiKeys }: { apiKeys: ApiKey[] }) {
const { toRelativeTime } = useDateTime();
diff --git a/apps/web/src/app/[locale]/(space)/settings/api-keys/page.tsx b/apps/web/src/app/[locale]/(space)/settings/api-keys/page.tsx
index 2580c997c..031dd2d3d 100644
--- a/apps/web/src/app/[locale]/(space)/settings/api-keys/page.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/api-keys/page.tsx
@@ -1,5 +1,5 @@
import type { Metadata } from "next";
-import { notFound, redirect } from "next/navigation";
+import { notFound } from "next/navigation";
import {
PageSection,
PageSectionContent,
@@ -13,29 +13,25 @@ import {
SettingsPageHeader,
SettingsPageTitle,
} from "@/components/settings-layout";
-import { getApiKeysPageState, getSpaceApiKeys } from "@/features/api-keys/data";
+import { getSpaceApiKeys, isApiAccessEnabled } from "@/features/api-keys/data";
+import { getActiveSpace } from "@/features/space/loaders";
+import { requireUser } from "@/features/user/loaders";
import { Trans } from "@/i18n/client";
import { getTranslation } from "@/i18n/server";
-import { getPathname } from "@/lib/pathname";
-import { buildSafeRedirectUrl } from "@/lib/utils/redirect";
import { ApiAccessUpgrade } from "./components/api-access-upgrade";
import { ApiKeysList } from "./components/api-keys-list";
import { ApiUsageLimits } from "./components/api-usage-limits";
import { CreateApiKeyButton } from "./components/create-api-key-button";
export default async function ApiKeysSettingsPage() {
- const pageState = await getApiKeysPageState();
+ const user = await requireUser();
- if (pageState.state === "unauthorized") {
- redirect(
- buildSafeRedirectUrl({
- destination: "/login",
- returnUrl: await getPathname(),
- }),
- );
- }
+ const space = await getActiveSpace();
+ const enabled = await isApiAccessEnabled(user, space);
- if (pageState.state === "unavailable") {
+ // "Needs to upgrade" (hobby tier) gets its own screen; every other reason
+ // access is blocked (feature flag off, not the owner) is a 404.
+ if (!enabled && space.tier !== "hobby") {
notFound();
}
@@ -51,36 +47,29 @@ export default async function ApiKeysSettingsPage() {
defaults="Manage API keys for programmatic access to your space"
/>
</SettingsPageDescription>
- {pageState.state === "enabled" ? (
+ {enabled ? (
<SettingsPageAction>
<CreateApiKeyButton />
</SettingsPageAction>
) : null}
</SettingsPageHeader>
<SettingsPageContent>
- {pageState.state === "upgrade_required" ? (
- <ApiAccessUpgrade />
- ) : (
- <ApiKeysContent />
- )}
+ {enabled ? <ApiKeysContent /> : <ApiAccessUpgrade />}
</SettingsPageContent>
</SettingsPage>
);
}
async function ApiKeysContent() {
- const result = await getSpaceApiKeys();
-
- if (!result.ok) {
- notFound();
- }
+ const space = await getActiveSpace();
+ const apiKeys = await getSpaceApiKeys({ spaceId: space.id });
return (
<PageSectionGroup>
<ApiUsageLimits />
<PageSection>
<PageSectionContent>
- <ApiKeysList apiKeys={result.apiKeys} />
+ <ApiKeysList apiKeys={apiKeys} />
</PageSectionContent>
</PageSection>
</PageSectionGroup>
diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/page.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/page.tsx
index ded2222f4..0531a8f20 100644
--- a/apps/web/src/app/[locale]/(space)/settings/billing/page.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/billing/page.tsx
@@ -1,7 +1,7 @@
import { Alert, AlertDescription, AlertTitle } from "@rallly/ui/alert";
import { CheckCircleIcon, ShieldXIcon } from "lucide-react";
import type { Metadata } from "next";
-import { notFound, redirect } from "next/navigation";
+import { notFound } from "next/navigation";
import {
EmptyState,
EmptyStateDescription,
@@ -25,14 +25,12 @@ import {
SettingsPageTitle,
} from "@/components/settings-layout";
import { getSpaceSubscription } from "@/features/billing/data";
-import { getActiveSpace, getSeatUsage } from "@/features/space/data";
+import { getActiveSpace, getSeatUsage } from "@/features/space/loaders";
import { defineAbilityForMember } from "@/features/space/member/ability";
-import { getCurrentUser } from "@/features/user/data";
+import { requireUser } from "@/features/user/loaders";
import { Trans } from "@/i18n/client";
import { getTranslation } from "@/i18n/server";
import { isFeatureEnabled } from "@/lib/feature-flags/server";
-import { getPathname } from "@/lib/pathname";
-import { buildSafeRedirectUrl } from "@/lib/utils/redirect";
import { ContactSupportLink } from "./components/contact-support-link";
import { HobbyPlanCard } from "./components/hobby-plan-card";
import { ProPlanCard } from "./components/pro-plan-card";
@@ -46,16 +44,7 @@ export default async function BillingSettingsPage({
notFound();
}
- const user = await getCurrentUser();
-
- if (!user) {
- redirect(
- buildSafeRedirectUrl({
- destination: "/login",
- returnUrl: await getPathname(),
- }),
- );
- }
+ const user = await requireUser();
const space = await getActiveSpace();
diff --git a/apps/web/src/app/[locale]/(space)/settings/members/page.tsx b/apps/web/src/app/[locale]/(space)/settings/members/page.tsx
index 38c2f1350..13b8da55a 100644
--- a/apps/web/src/app/[locale]/(space)/settings/members/page.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/members/page.tsx
@@ -1,6 +1,6 @@
import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import type { Metadata } from "next";
-import { getSeatUsage } from "@/features/space/data";
+import { getSeatUsage } from "@/features/space/loaders";
import { getTranslation } from "@/i18n/server";
import { createPrivateSSRHelper } from "@/trpc/server/create-ssr-helper";
import { MembersSettingsPageClient } from "./page-client";
diff --git a/apps/web/src/app/[locale]/(space)/settings/preferences/page.tsx b/apps/web/src/app/[locale]/(space)/settings/preferences/page.tsx
index 42e944bd2..e192517b7 100644
--- a/apps/web/src/app/[locale]/(space)/settings/preferences/page.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/preferences/page.tsx
@@ -1,5 +1,4 @@
import type { Metadata } from "next";
-import { redirect } from "next/navigation";
import { DateTimePreferences } from "@/app/[locale]/(space)/settings/preferences/components/date-time-preferences";
import { LanguagePreference } from "@/app/[locale]/(space)/settings/preferences/components/language-preference";
import { ThemePreference } from "@/app/[locale]/(space)/settings/preferences/components/theme-preference";
@@ -19,23 +18,12 @@ import {
SettingsPageHeader,
SettingsPageTitle,
} from "@/components/settings-layout";
-import { getCurrentUser } from "@/features/user/data";
+import { requireUser } from "@/features/user/loaders";
import { Trans } from "@/i18n/client";
import { getTranslation } from "@/i18n/server";
-import { getPathname } from "@/lib/pathname";
-import { buildSafeRedirectUrl } from "@/lib/utils/redirect";
export default async function Page() {
- const user = await getCurrentUser();
-
- if (!user) {
- redirect(
- buildSafeRedirectUrl({
- destination: "/login",
- returnUrl: await getPathname(),
- }),
- );
- }
+ const user = await requireUser();
return (
<SettingsPage>
diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/account-deletion-summary.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/account-deletion-summary.tsx
index e7b47ee35..0d3afd5a2 100644
--- a/apps/web/src/app/[locale]/(space)/settings/profile/components/account-deletion-summary.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/account-deletion-summary.tsx
@@ -3,8 +3,8 @@ import { Icon } from "@rallly/ui/icon";
import { Skeleton } from "@rallly/ui/skeleton";
import { BarChart2Icon, CalendarIcon, InfoIcon } from "lucide-react";
import { getAccountDeletionSummary } from "@/features/user/account-deletion/data";
+import { requireUser } from "@/features/user/loaders";
import { Trans } from "@/i18n/client";
-import { requireUser } from "@/lib/auth";
// Streamed into the delete account dialog behind Suspense so opening the
// settings page never waits on the counts.
diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/page.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/page.tsx
index 1b3a915c0..4a1e8391e 100644
--- a/apps/web/src/app/[locale]/(space)/settings/profile/page.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/profile/page.tsx
@@ -18,7 +18,7 @@ import {
SettingsPageHeader,
SettingsPageTitle,
} from "@/components/settings-layout";
-import { getCurrentUser } from "@/features/user/data";
+import { getCurrentUser } from "@/features/user/loaders";
import { Trans } from "@/i18n/client";
import { getTranslation } from "@/i18n/server";
import { getPathname } from "@/lib/pathname";
@@ -33,6 +33,8 @@ import { ProfileEmailAddress } from "./components/profile-email-address";
import { ProfileSettings } from "./components/profile-settings";
export default async function Page() {
+ // Read from the database — the pending deletion notice depends on
+ // deletedAt, which the session snapshot doesn't carry.
const user = await getCurrentUser();
if (!user) {
diff --git a/apps/web/src/app/[locale]/(space)/settings/security/page.tsx b/apps/web/src/app/[locale]/(space)/settings/security/page.tsx
index d11c0d23f..318cdaf62 100644
--- a/apps/web/src/app/[locale]/(space)/settings/security/page.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/security/page.tsx
@@ -18,9 +18,9 @@ import {
SettingsPageTitle,
} from "@/components/settings-layout";
import { getUserHasPassword } from "@/features/user/data";
+import { requireUser } from "@/features/user/loaders";
import { Trans } from "@/i18n/client";
import { getTranslation } from "@/i18n/server";
-import { requireUser } from "@/lib/auth";
import { isFeatureEnabled } from "@/lib/feature-flags/server";
import { ChangePasswordForm } from "./components/change-password-form";
import { SetupPasswordForm } from "./components/setup-password-form";
diff --git a/apps/web/src/app/[locale]/(space)/settings/spaces/page.tsx b/apps/web/src/app/[locale]/(space)/settings/spaces/page.tsx
index 99a6e308f..56e361ae7 100644
--- a/apps/web/src/app/[locale]/(space)/settings/spaces/page.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/spaces/page.tsx
@@ -9,9 +9,9 @@ import {
SettingsPageHeader,
SettingsPageTitle,
} from "@/components/settings-layout";
+import { requireUser } from "@/features/user/loaders";
import { Trans } from "@/i18n/client";
import { getTranslation } from "@/i18n/server";
-import { requireUser } from "@/lib/auth";
import { createPrivateSSRHelper } from "@/trpc/server/create-ssr-helper";
import { SpacesList } from "./components/spaces-list";
diff --git a/apps/web/src/app/[locale]/accept-invite/[inviteId]/page.tsx b/apps/web/src/app/[locale]/accept-invite/[inviteId]/page.tsx
index ffd05907d..594037964 100644
--- a/apps/web/src/app/[locale]/accept-invite/[inviteId]/page.tsx
+++ b/apps/web/src/app/[locale]/accept-invite/[inviteId]/page.tsx
@@ -4,9 +4,9 @@ import { notFound } from "next/navigation";
import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";
import { Logo } from "@/features/branding/components/logo";
import { SpaceIcon } from "@/features/space/components/space-icon";
+import { requireUser } from "@/features/user/loaders";
import { Trans } from "@/i18n/client";
import { getTranslation } from "@/i18n/server";
-import { requireUser } from "@/lib/auth";
import { AcceptInviteButton } from "./components/accept-invite-button";
import { SignOutButton } from "./components/sign-out-button";
diff --git a/apps/web/src/app/[locale]/admin-setup/page.tsx b/apps/web/src/app/[locale]/admin-setup/page.tsx
index 41dec40e7..452c00fb1 100644
--- a/apps/web/src/app/[locale]/admin-setup/page.tsx
+++ b/apps/web/src/app/[locale]/admin-setup/page.tsx
@@ -11,9 +11,10 @@ import {
EmptyStateTitle,
} from "@/components/empty-state";
import { isInitialAdmin } from "@/features/instance-settings/utils";
-import { getCurrentUser } from "@/features/user/data";
+import { getCurrentUser } from "@/features/user/loaders";
import { Trans } from "@/i18n/client";
import { getTranslation } from "@/i18n/server";
+import { getPathname } from "@/lib/pathname";
import { buildSafeRedirectUrl } from "@/lib/utils/redirect";
import { MakeMeAdminButton } from "./make-me-admin-button";
@@ -26,7 +27,7 @@ export default async function AdminSetupPage() {
redirect(
buildSafeRedirectUrl({
destination: "/login",
- returnUrl: "/admin-setup",
+ returnUrl: await getPathname(),
}),
);
}
diff --git a/apps/web/src/app/[locale]/setup/page.tsx b/apps/web/src/app/[locale]/setup/page.tsx
index 05e6b79c8..6f71c89d4 100644
--- a/apps/web/src/app/[locale]/setup/page.tsx
+++ b/apps/web/src/app/[locale]/setup/page.tsx
@@ -5,9 +5,9 @@ import { SetupForm } from "@/app/[locale]/setup/components/setup-form";
import { ThemeSwitcher } from "@/components/theme-switcher";
import { Logo } from "@/features/branding/components/logo";
import { getActiveSpaceForUser } from "@/features/space/data";
+import { requireUser } from "@/features/user/loaders";
import { Trans } from "@/i18n/client";
import { getTranslation } from "@/i18n/server";
-import { requireUser } from "@/lib/auth";
import { getDeviceDateTimeConfig } from "@/lib/datetime/server";
import { validateRedirectUrl } from "@/lib/utils/redirect";
diff --git a/apps/web/src/features/api-keys/actions.ts b/apps/web/src/features/api-keys/actions.ts
index 13c09d1e5..4045d75b4 100644
--- a/apps/web/src/features/api-keys/actions.ts
+++ b/apps/web/src/features/api-keys/actions.ts
@@ -1,11 +1,13 @@
"use server";
-import { getApiKeyAccessContext } from "@/features/api-keys/data";
+import { isApiAccessEnabled } from "@/features/api-keys/data";
import { createApiKey, revokeApiKey } from "@/features/api-keys/mutations";
import {
createApiKeySchema,
revokeApiKeySchema,
} from "@/features/api-keys/schema";
+import { getActiveSpaceForUser } from "@/features/space/data";
+import { getCurrentUser } from "@/features/user/loaders";
import { AppError } from "@/lib/errors/app-error";
import { track } from "@/lib/posthog";
import { authActionClient } from "@/lib/safe-action/server";
@@ -13,29 +15,32 @@ import { authActionClient } from "@/lib/safe-action/server";
// The UI never offers these actions to users without API access, so a
// failed gate is unexpected here — throw for the global error handler.
async function requireApiAccess() {
- const context = await getApiKeyAccessContext();
+ const user = await getCurrentUser();
- if (!context.ok) {
- switch (context.reason) {
- case "unauthorized":
- throw new AppError({
- code: "UNAUTHORIZED",
- message: "You are not authenticated.",
- });
- case "no_active_space":
- throw new AppError({
- code: "NOT_FOUND",
- message: "Space not found",
- });
- case "api_access_not_enabled":
- throw new AppError({
- code: "FORBIDDEN",
- message: "API access is not enabled for this user or space",
- });
- }
+ if (!user) {
+ throw new AppError({
+ code: "UNAUTHORIZED",
+ message: "You are not authenticated.",
+ });
+ }
+
+ const space = await getActiveSpaceForUser(user.id);
+
+ if (!space) {
+ throw new AppError({
+ code: "NOT_FOUND",
+ message: "Space not found",
+ });
+ }
+
+ if (!(await isApiAccessEnabled(user, space))) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "API access is not enabled for this user or space",
+ });
}
- return context;
+ return { user, space };
}
export const createApiKeyAction = authActionClient
diff --git a/apps/web/src/features/api-keys/data.ts b/apps/web/src/features/api-keys/data.ts
index 4ec2bdedb..9073c733c 100644
--- a/apps/web/src/features/api-keys/data.ts
+++ b/apps/web/src/features/api-keys/data.ts
@@ -1,49 +1,15 @@
import "server-only";
import { prisma } from "@rallly/database";
-import { cache } from "react";
-import { getActiveSpaceForUser } from "@/features/space/data";
import type { SpaceTier } from "@/features/space/schema";
-import { getCurrentUser } from "@/features/user/data";
+import type { AuthorizedSpaceId } from "@/features/space/types";
import { isSelfHosted } from "@/lib/constants";
import { posthog } from "@/lib/posthog";
-/**
- * Resolve the current user's space and verify API access. Auth is enforced
- * here in the DAL so no call site can fetch API keys without the gate.
- * Failures are returned as values; stale sessions still throw
- * InvalidSessionError from getCurrentUser for the boundary to handle.
- */
-export const getApiKeyAccessContext = cache(async () => {
- const user = await getCurrentUser();
-
- if (!user) {
- return { ok: false, reason: "unauthorized" } as const;
- }
-
- const space = await getActiveSpaceForUser(user.id);
-
- if (!space) {
- return { ok: false, reason: "no_active_space" } as const;
- }
-
- if (!(await isApiAccessEnabled(user, space))) {
- return { ok: false, reason: "api_access_not_enabled" } as const;
- }
-
- return { ok: true, user, space } as const;
-});
-
-export const getSpaceApiKeys = cache(async () => {
- const context = await getApiKeyAccessContext();
-
- if (!context.ok) {
- return context;
- }
-
- const apiKeys = await prisma.spaceApiKey.findMany({
+export function getSpaceApiKeys({ spaceId }: { spaceId: AuthorizedSpaceId }) {
+ return prisma.spaceApiKey.findMany({
where: {
- spaceId: context.space.id,
+ spaceId,
},
select: {
id: true,
@@ -58,39 +24,7 @@ export const getSpaceApiKeys = cache(async () => {
createdAt: "desc",
},
});
-
- return { ok: true, apiKeys } as const;
-});
-
-/**
- * Resolve the current space's tier for the API keys page. Lets the page tell
- * "needs to upgrade" (hobby tier) apart from other reasons access is blocked
- * (feature flag off, not the owner), which all collapse to a single reason in
- * getApiKeyAccessContext.
- */
-export const getApiKeysPageState = cache(async () => {
- const user = await getCurrentUser();
-
- if (!user) {
- return { state: "unauthorized" } as const;
- }
-
- const space = await getActiveSpaceForUser(user.id);
-
- if (!space) {
- return { state: "unauthorized" } as const;
- }
-
- if (await isApiAccessEnabled(user, space)) {
- return { state: "enabled" } as const;
- }
-
- if (space.tier === "hobby") {
- return { state: "upgrade_required" } as const;
- }
-
- return { state: "unavailable" } as const;
-});
+}
/**
* Determines if a user has access to API features (API keys, developer tools)
@@ -98,7 +32,7 @@ export const getApiKeysPageState = cache(async () => {
* @param space - The space to check access for
* @returns True if the user can access API features
*/
-async function isApiAccessEnabled(
+export async function isApiAccessEnabled(
user: {
id: string;
},
diff --git a/apps/web/src/features/space/data.ts b/apps/web/src/features/space/data.ts
index 8efb4b4e6..ad3b1e75f 100644
--- a/apps/web/src/features/space/data.ts
+++ b/apps/web/src/features/space/data.ts
@@ -6,7 +6,6 @@ import type {
} from "@rallly/database";
import { prisma } from "@rallly/database";
import { createLogger } from "@rallly/logger";
-import { redirect } from "next/navigation";
import { cache } from "react";
import { getSpaceSubscription } from "@/features/billing/data";
@@ -16,12 +15,8 @@ import type { MemberDTO } from "@/features/space/member/types";
import { effectiveSpaceMemberWhere } from "@/features/space/member/utils";
import type { AuthorizedSpaceId, SpaceDTO } from "@/features/space/types";
import { fromDBRole } from "@/features/space/utils";
-import { getSessionState } from "@/lib/auth";
import { isSelfHosted } from "@/lib/constants";
import { AppError } from "@/lib/errors/app-error";
-import { InvalidSessionError } from "@/lib/errors/invalid-session-error";
-import { getPathname } from "@/lib/pathname";
-import { buildSafeRedirectUrl } from "@/lib/utils/redirect";
const logger = createLogger("space/data");
@@ -133,21 +128,6 @@ export async function getTotalSeatsForSpace(spaceId: string): Promise<number> {
}
}
-/**
- * Seat usage for the signed-in user's active space. Session scoped —
- * server component/page use only, per getActiveSpace.
- */
-export const getSeatUsage = cache(async () => {
- const space = await getActiveSpace();
-
- const [total, used] = await Promise.all([
- getTotalSeatsForSpace(space.id),
- getSpaceSeatCount(space.id),
- ]);
-
- return { total, used };
-});
-
export function createSpaceDTO(space: {
id: string;
ownerId: string;
@@ -218,69 +198,6 @@ export function getSpaceBranding(spaceId: string) {
});
}
-/**
- * The active space for the signed-in user, gated for server rendering:
- * redirects to /login when unauthenticated or a guest, redirects to /setup
- * when the user has no name, timezone, time format, or space, and throws
- * InvalidSessionError when banned.
- * React cached, so every page and layout that needs the space in a request
- * shares one gate and one query. Server component/page use only — the
- * redirects make it unsuitable for route handlers and tRPC procedures.
- */
-export const getActiveSpace = cache(async () => {
- const state = await getSessionState();
-
- // An unreadable session (store unreachable, transient failure) is not
- // "logged out" — redirecting to /login on it is one leg of a redirect
- // loop. Fail the render instead so the user gets the error boundary's
- // retry page.
- if (state.status === "error") {
- throw new Error("Failed to read session");
- }
-
- const user =
- state.status === "authenticated" ? state.session.user : undefined;
-
- if (!user || user.isGuest) {
- redirect(
- buildSafeRedirectUrl({
- destination: "/login",
- returnUrl: await getPathname(),
- }),
- );
- }
-
- if (user.banned) {
- throw new InvalidSessionError();
- }
-
- // Accounts created through the OTP registration flow start without a
- // name, timezone, or time format; /setup collects them before they can
- // use the app. Pre-existing accounts missing any of these go through
- // the same (prefilled) form once.
- if (!user.name || !user.timeZone || !user.timeFormat) {
- redirect(
- buildSafeRedirectUrl({
- destination: "/setup",
- returnUrl: await getPathname(),
- }),
- );
- }
-
- const space = await getActiveSpaceForUser(user.id);
-
- if (!space) {
- redirect(
- buildSafeRedirectUrl({
- destination: "/setup",
- returnUrl: await getPathname(),
- }),
- );
- }
-
- return space;
-});
-
export const getOwnedSpace = cache(async (userId: string) => {
return prisma.space.findFirst({
where: { ownerId: userId },
diff --git a/apps/web/src/features/space/loaders.ts b/apps/web/src/features/space/loaders.ts
new file mode 100644
index 000000000..f1c7aabf2
--- /dev/null
+++ b/apps/web/src/features/space/loaders.ts
@@ -0,0 +1,92 @@
+import "server-only";
+
+import { redirect } from "next/navigation";
+import { cache } from "react";
+
+import {
+ getActiveSpaceForUser,
+ getSpaceSeatCount,
+ getTotalSeatsForSpace,
+} from "@/features/space/data";
+import { getSessionState } from "@/lib/auth";
+import { InvalidSessionError } from "@/lib/errors/invalid-session-error";
+import { getPathname } from "@/lib/pathname";
+import { buildSafeRedirectUrl } from "@/lib/utils/redirect";
+
+/**
+ * The active space for the signed-in user, gated for server rendering:
+ * redirects to /login when unauthenticated or a guest, redirects to /setup
+ * when the user has no name, timezone, time format, or space, and throws
+ * InvalidSessionError when banned.
+ * React cached, so every page and layout that needs the space in a request
+ * shares one gate and one query. Server component/page use only — the
+ * redirects make it unsuitable for route handlers and tRPC procedures.
+ */
+export const getActiveSpace = cache(async () => {
+ const state = await getSessionState();
+
+ // An unreadable session (store unreachable, transient failure) is not
+ // "logged out" — redirecting to /login on it is one leg of a redirect
+ // loop. Fail the render instead so the user gets the error boundary's
+ // retry page.
+ if (state.status === "error") {
+ throw new Error("Failed to read session");
+ }
+
+ const user =
+ state.status === "authenticated" ? state.session.user : undefined;
+
+ if (!user || user.isGuest) {
+ redirect(
+ buildSafeRedirectUrl({
+ destination: "/login",
+ returnUrl: await getPathname(),
+ }),
+ );
+ }
+
+ if (user.banned) {
+ throw new InvalidSessionError();
+ }
+
+ // Accounts created through the OTP registration flow start without a
+ // name, timezone, or time format; /setup collects them before they can
+ // use the app. Pre-existing accounts missing any of these go through
+ // the same (prefilled) form once.
+ if (!user.name || !user.timeZone || !user.timeFormat) {
+ redirect(
+ buildSafeRedirectUrl({
+ destination: "/setup",
+ returnUrl: await getPathname(),
+ }),
+ );
+ }
+
+ const space = await getActiveSpaceForUser(user.id);
+
+ if (!space) {
+ redirect(
+ buildSafeRedirectUrl({
+ destination: "/setup",
+ returnUrl: await getPathname(),
+ }),
+ );
+ }
+
+ return space;
+});
+
+/**
+ * Seat usage for the signed-in user's active space. Session scoped —
+ * server component/page use only, per getActiveSpace.
+ */
+export const getSeatUsage = cache(async () => {
+ const space = await getActiveSpace();
+
+ const [total, used] = await Promise.all([
+ getTotalSeatsForSpace(space.id),
+ getSpaceSeatCount(space.id),
+ ]);
+
+ return { total, used };
+});
diff --git a/apps/web/src/features/user/data.ts b/apps/web/src/features/user/data.ts
index 6919a17c2..6ae4656ea 100644
--- a/apps/web/src/features/user/data.ts
+++ b/apps/web/src/features/user/data.ts
@@ -2,10 +2,7 @@ import "server-only";
import type { User } from "@rallly/database";
import { prisma } from "@rallly/database";
-import { cache } from "react";
import type { UserDTO } from "@/features/user/schema";
-import { getSession } from "@/lib/auth";
-import { InvalidSessionError } from "@/lib/errors/invalid-session-error";
export const createUserDTO = (user: User): UserDTO => ({
id: user.id,
@@ -23,29 +20,17 @@ export const createUserDTO = (user: User): UserDTO => ({
deletedAt: user.deletedAt ?? undefined,
});
-/**
- * The current signed-in user, fetched from the database. Returns null
- * when there is no session or the user is a guest — the caller decides
- * how to respond (redirect, 401, etc.). Throws InvalidSessionError when
- * the session references a user that no longer exists or is banned.
- */
-export const getCurrentUser = cache(async () => {
- const session = await getSession();
-
- if (!session?.user || session.user.isGuest) {
- return null;
- }
-
+export const getUser = async (userId: string) => {
const user = await prisma.user.findUnique({
- where: { id: session.user.id },
+ where: { id: userId },
});
- if (!user || user.banned) {
- throw new InvalidSessionError();
+ if (!user) {
+ return null;
}
return createUserDTO(user);
-});
+};
export function getUserProfile(userId: string) {
return prisma.user.findUnique({
diff --git a/apps/web/src/features/user/loaders.ts b/apps/web/src/features/user/loaders.ts
new file mode 100644
index 000000000..c81673f2b
--- /dev/null
+++ b/apps/web/src/features/user/loaders.ts
@@ -0,0 +1,64 @@
+import "server-only";
+
+import { redirect } from "next/navigation";
+import { cache } from "react";
+import { getUser } from "@/features/user/data";
+import type { UserDTO } from "@/features/user/schema";
+import { getSession, getSessionState } from "@/lib/auth";
+import { InvalidSessionError } from "@/lib/errors/invalid-session-error";
+import { getPathname } from "@/lib/pathname";
+import { buildSafeRedirectUrl } from "@/lib/utils/redirect";
+
+/**
+ * The current signed-in user, fetched from the database. Returns null
+ * when there is no session or the user is a guest — the caller decides
+ * how to respond (redirect, 401, etc.). Throws InvalidSessionError when
+ * the session references a user that no longer exists or is banned.
+ */
+export const getCurrentUser = cache(async () => {
+ const session = await getSession();
+
+ if (!session?.user || session.user.isGuest) {
+ return null;
+ }
+
+ const user = await getUser(session.user.id);
+
+ if (!user || user.banned) {
+ throw new InvalidSessionError();
+ }
+
+ return user;
+});
+
+/**
+ * Gate for server pages that require a logged-in (non-guest) user.
+ * Trusts the session cookie cache (no database read). Redirects to /login
+ * when unauthenticated, fails the render on an unreadable session so a
+ * transient session-store failure can't feed a / ↔ /login redirect loop.
+ * Use getCurrentUser where the user is optional or must be read from the
+ * database (mutation gates, stale-role-sensitive pages).
+ */
+export const requireUser = cache(async (): Promise<UserDTO> => {
+ const state = await getSessionState();
+
+ if (state.status === "error") {
+ throw new Error("Failed to read session");
+ }
+
+ const user =
+ state.status === "authenticated" ? state.session.user : undefined;
+
+ if (!user || user.isGuest) {
+ const pathname = await getPathname();
+ redirect(
+ buildSafeRedirectUrl({ destination: "/login", returnUrl: pathname }),
+ );
+ }
+
+ if (user.banned) {
+ throw new InvalidSessionError();
+ }
+
+ return user;
+});
diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts
index 10045d072..a088dace5 100644
--- a/apps/web/src/lib/auth.ts
+++ b/apps/web/src/lib/auth.ts
@@ -31,16 +31,13 @@ import type { UserDTO } from "@/features/user/schema";
import { getTranslation } from "@/i18n/server";
import { getLocale } from "@/i18n/server/get-locale";
import { hostOnlyCookieCleanup } from "@/lib/auth-plugins/host-only-cookie-cleanup";
-import { InvalidSessionError } from "@/lib/errors/invalid-session-error";
import { redis } from "@/lib/kv";
import {
LOCALE_COOKIE_NAME,
LOCALE_COOKIE_OPTIONS,
} from "@/lib/locale/constants";
-import { getPathname } from "@/lib/pathname";
import { track } from "@/lib/posthog";
import { getValueByPath } from "@/lib/utils/get-value-by-path";
-import { buildSafeRedirectUrl } from "@/lib/utils/redirect";
const kv = redis;
@@ -630,36 +627,6 @@ export const getSession = async () => {
return state.status === "authenticated" ? state.session : null;
};
-/**
- * Gate for server pages that require a logged-in (non-guest) user.
- * Trusts the session cookie cache (no database read). Redirects to /login
- * when unauthenticated, fails the render on an unreadable session so a
- * transient session-store failure can't feed a / ↔ /login redirect loop.
- */
-export const requireUser = cache(async (): Promise<UserDTO> => {
- const state = await getSessionState();
-
- if (state.status === "error") {
- throw new Error("Failed to read session");
- }
-
- const user =
- state.status === "authenticated" ? state.session.user : undefined;
-
- if (!user || user.isGuest) {
- const pathname = await getPathname();
- redirect(
- buildSafeRedirectUrl({ destination: "/login", returnUrl: pathname }),
- );
- }
-
- if (user.banned) {
- throw new InvalidSessionError();
- }
-
- return user;
-});
-
export const signOut = async () => {
await authLib.api.signOut({
headers: await headers(),
diff --git a/apps/web/src/lib/safe-action/server.ts b/apps/web/src/lib/safe-action/server.ts
index 3a309fa20..51ca4b935 100644
--- a/apps/web/src/lib/safe-action/server.ts
+++ b/apps/web/src/lib/safe-action/server.ts
@@ -5,7 +5,7 @@ import { APIError } from "better-auth/api";
import { createMiddleware, createSafeActionClient } from "next-safe-action";
import * as z from "zod";
import { defineAbilityFor } from "@/features/user/ability";
-import { getCurrentUser } from "@/features/user/data";
+import { getCurrentUser } from "@/features/user/loaders";
import { signOut } from "@/lib/auth";
import { AppError } from "@/lib/errors/app-error";
import { InvalidSessionError } from "@/lib/errors/invalid-session-error";
diff --git a/apps/web/src/trpc/server/create-ssr-helper.ts b/apps/web/src/trpc/server/create-ssr-helper.ts
index 3f312086c..0286a5863 100644
--- a/apps/web/src/trpc/server/create-ssr-helper.ts
+++ b/apps/web/src/trpc/server/create-ssr-helper.ts
@@ -3,8 +3,8 @@ import { notFound, redirect } from "next/navigation";
import { cache } from "react";
import superjson from "superjson";
import { isInitialAdmin } from "@/features/instance-settings/utils";
-import { getCurrentUser } from "@/features/user/data";
-import { getSession, requireUser } from "@/lib/auth";
+import { getCurrentUser, requireUser } from "@/features/user/loaders";
+import { getSession } from "@/lib/auth";
import { getPathname } from "@/lib/pathname";
import { buildSafeRedirectUrl } from "@/lib/utils/redirect";
import type { TRPCContext } from "../context";
diff --git a/scripts/check-feature-structure.mjs b/scripts/check-feature-structure.mjs
index 499d5511c..611ac7b06 100644
--- a/scripts/check-feature-structure.mjs
+++ b/scripts/check-feature-structure.mjs
@@ -21,6 +21,7 @@ const FEATURES_DIR = path.resolve(
const ALLOWED_FILES = new Set([
"data.ts",
+ "loaders.ts",
"mutations.ts",
"actions.ts",
"schema.ts",