Creating a Clerk account grants nothing. A person who has signed up but is not admitted (account_type of pending or rejected, or no verified email) is held on a single screen, /approval, where they can ask for access. A Super Admin reviews the request at /admin/access-requests, chooses which company the applicant joins and whether they are a partner or a prospect, and approves. Approval takes effect instantly: the applicant's open /approval screen notices within ~5 seconds and forwards them into the portal, with no re-login and no invite email to find.
The whole approval is an all-or-nothing saga — it either fully completes or fully reverts, with no half-provisioned state.
This page covers the request side and the approval saga. How the user is held at /approval in the first place (the three ordered layers, the admission cookie) is on Authentication & Gates.
Source: the request action lib/actions/request-approval.ts (Zod schema lib/approval/request-schema.ts), the screen app/(auth)/approval/page.tsx + ApprovalClient.tsx, the poll endpoint app/api/approval/status/route.ts (state mapping in lib/approval/status.ts), the admin actions lib/actions/access-request-admin.ts (grant validation in lib/approval/grant.ts, company pickers in lib/approval/company-options.ts), the page app/(admin)/admin/access-requests/page.tsx + AccessRequestRow.tsx, and the partner_access_requests table (Data Model).
What changed. The old flow had an anonymous
/request-accessform (no Clerk account behind it), dead-end/pendingand/access-deniedpages, and an approval that hardcodedpartnerand always created a brand-new Clerk org. All four routes are gone.submitAccessRequest(lib/actions/access-request.ts) no longer exists; identity now comes from the signed-in session.
/sign-up (Clerk) ──► account_type resolves to `pending` ──► blocked
│
/approval (the only reachable screen)
│
"Ask for approval" (requestApproval)
│
partner_access_requests row (status: pending, clerk_user_id = caller)
│
Super Admin at /admin/access-requests
┌─ Approve (role + company chosen) ─► Clerk membership + ONE transaction ─► status: approved
│ account_type = partner | prospect
│ └─► open /approval poll flips ─► full navigation to /dashboard
└─ Reject ─► status: rejected, account_type = rejected ─► /approval shows the reason + "Ask for approval" again
/approval screen#/approval is the only route reachable while not admitted (BLOCKED_ROUTE in lib/auth/admission.ts). It is in the (auth) route group and, like its siblings, follows that group's T.* token convention rather than ws-* classes (migrating the group is tracked separately). The server page (app/(auth)/approval/page.tsx) is force-dynamic:
redirect("/sign-in").admissionFor(accountType) === "admitted") → redirect("/dashboard"). An admitted user never sees a status screen for access they already hold.partner_access_requests row (matched on clerk_user_id, newest created_at) and hands ApprovalClient the initial state.approvalStateFor(row) in lib/approval/status.ts is a pure function, shared by the page, the poll endpoint and the server action:
| State | When | What the user sees |
|---|---|---|
no_request | no row for this Clerk user | A short form: company name, website, your role, optional message. One Ask for approval button. |
awaiting | row status is anything other than approved or rejected (pending, auto_approved, or an unrecognised value) | What they submitted, a live status line, and sign-out. |
approved | row status is approved | The screen says so and forwards into the portal (window.location.assign("/dashboard")). |
rejected | row status is rejected | The reviewer's note (review_note) if there is one, and the form again — Ask for approval is re-enabled so the person can re-apply. |
approvalStateFor deliberately fails toward awaiting: an unrecognised status must never read as approved, because approved forwards into the portal.
Approval forwards with a full navigation, not a router push, so middleware and the server gate re-evaluate the request from scratch.
requestApproval#lib/actions/request-approval.ts is a server action for the currently signed-in user only:
getAccountSession() — no session → "Please sign in again."; no verified email → "Verify your email address before requesting approval."requestApprovalSchema (Zod): companyName (1–200), website (optional; a bare acme.com gets https:// prepended, then must pass isSafeHttpUrl, an http(s)-only allowlist), role (1–120), message (≤2000).awaiting → "already awaiting review"; approved → "You already have access". no_request and rejected proceed — a rejected applicant may re-apply.partner_access_requests row (status: "pending", clerk_user_id = the caller, email = verified email). The role and message are folded into the message column.access_request.submitted notification and write an access_request.submitted activity-log row.The friendly "already awaiting" check is only a convenience. The real guard is the partial unique index partner_access_requests_open_per_user (one open request per clerk_user_id), which closes the read-then-insert race.
GET /api/approval/status#app/api/approval/status/route.ts returns { state, companyName, reviewNote } for the caller's own request.
| Property | Behaviour |
|---|---|
| Keyed by | The session (getAccountSession().clerkUserId) — never an id from the query string or body. There is no parameter to tamper with, so the endpoint cannot be used as an enumeration oracle for other people's applications. This is the property to preserve in any change. |
| Signed out | 401 { error: "unauthenticated" }. The client stops polling and shows a session-expired notice. |
| Database or session-resolution blip | Returns the safe payload { state: "awaiting", companyName: null, reviewNote: null } with 200, not a 500. awaiting never forwards anyone into the portal, and the next poll corrects it. Only a throw is absorbed; a genuinely null session still returns 401. |
| Caching | dynamic = "force-dynamic" and Cache-Control: no-store. |
Client behaviour (ApprovalClient.tsx):
POLL_MS = 5_000), only while the tab is visible; a visibilitychange event triggers an immediate poll when the tab returns.approved or rejected) and on a 401.awaiting without waiting out an interval./admin/access-requests#Super-Admin-only (requireSuperAdminSession). The page lists requests split into Pending Review and Actioned (read-only history). Each requestId is validated as a UUID before any work, and every transition re-asserts that the row is still undecided in its WHERE clause (actionableRequestWhere(): status in pending or auto_approved) so concurrent clicks can't double-approve or double-email.
The approve control carries four form fields — role, companyMode, orgId, companyName — validated server-side by parseGrant() in lib/approval/grant.ts:
| Choice | Options | What it provisions |
|---|---|---|
Role (role) | partner (default) or prospect | Written to account_type (assigned) and to partner_access_requests.granted_account_type. Validated through canAssignType, so an address whose domain is ineligible cannot be given the type even with a tampered form. An @matters.ai address is refused outright: staff are set from /admin/accounts, never onboarded as external. |
Company — existing (companyMode = "existing", orgId) | Any Clerk org. Orgs matching the applicant's email domain (companyOptionsForEmail, via orgIdsForDomain) are offered first and make "existing" the default; all other orgs (otherCompanyOptions) are also selectable, for applicants on gmail.com or a consultancy. | Reuses the org. The applicant is added to it as org:member. |
Company — new (companyMode = "new", companyName) | A name, defaulting to what the applicant typed. Default when no org matches the domain. | Creates a new Clerk org. The applicant is its creator and therefore org:admin, so they can invite colleagues themselves. |
The chosen org id is stored in granted_org_id. decided_at is stamped on approval (rejection records reviewed_by and review_note but does not set it).
True distributed ACID across Postgres and the external Clerk API isn't possible, so approveAccessRequest is ordered so that a failure at any step leaves the request untouched and retryable. The shape is: reversible external step first, then ONE atomic transaction, with compensation on failure.
approveAccessRequest(requestId, role, company):
1. load request; guard isActionableStatus(status) and a valid email domain
2. parseGrant({ role, companyMode, orgId, companyName }, email) // refuse before touching Clerk
3. REVERSIBLE external Clerk step, done FIRST
existing + clerk_user_id → addUserToOrg(orgId, userId, "org:member") // direct membership
existing + no clerk_user_id → inviteToExistingOrg(...) // legacy invite path
new + clerk_user_id → createOrganizationForUser(name, userId) // creator becomes org:admin
new + no clerk_user_id → createOrgWithAdminInvite(...) // legacy invite path
└─ on failure → return error; NOTHING committed; request stays actionable
4. db().transaction(tx => { // ATOMIC
update status → approved, reviewed_by, granted_account_type, granted_org_id,
decided_at, clerk_invite_id WHERE actionableRequestWhere(id)
// 0 rows ⇒ AlreadyActioned ⇒ rollback
provisionPartnerAccount(domain) // domain becomes an active partner_accounts row
assignTypeByEmailInTx(role) // account_type = partner | prospect (source: assigned)
recordActivity("access_request.approved")
recordActivity("account_type.changed")
})
└─ on failure → COMPENSATE the Clerk step (below); request stays actionable
5. best-effort after commit: Salesforce write-back, approval email
The old approval called createOrgWithAdminInvite, which emailed an invitation the applicant had to find and accept, because they had no Clerk account at approval time. In the new model they signed up first, so the request row carries their clerk_user_id and approval adds them to the org directly. That is what makes access instant rather than aspirational: an invite round-trip would place a second dead end exactly where the first was removed. The grant is already live in Clerk and Postgres by the time the poll sees approved, so the next request passes admission with no further step.
If the transaction throws after the Clerk step succeeded, the saga undoes the Clerk step so a retry starts clean:
| Path | What was done externally | Undo |
|---|---|---|
Legacy invite (clerk_user_id IS NULL), either mode | An invitation was created | revokeOrgInvite |
Legacy new path where the invitee already had a Clerk account | createOrgWithAdminInvite added them directly (invitationId is null) and reports the user as addedMembershipUserId | removeUserFromOrg |
existing + clerk_user_id | A membership was added | removeUserFromOrg — only if this call created it |
new + clerk_user_id | A new org was created with the applicant as creator | No membership removal (evicting someone from the org they own is not a meaningful undo). The org is logged as orphaned and deliberately not deleted: a concurrent approval may have populated it, and deleting a populated org is far worse than leaving an empty one for manual cleanup. |
The "only if this call created it" rule matters. addUserToOrg is idempotent and returns false when the user was already a member, and the saga takes addedMembershipUserId from that return value, never from a flag set around the call. A super-admin double-clicking Approve sends a second call whose transaction fails AlreadyActioned; a flag-based compensation would then delete the membership the first call just committed, leaving the row approved, Clerk empty, and no retry possible because the request is no longer actionable. Re-approving someone already in the org can likewise never evict them.
A transaction that fails because another admin got there first returns "This request has already been actioned." and compensates only what this call itself added.
clerk_user_id IS NULL path#Rows filed by the old anonymous form were backfilled with clerk_user_id = NULL. They still work: with no Clerk user to add directly, the saga takes the invite branches above (inviteToExistingOrg / createOrgWithAdminInvite), the applicant receives an email invitation landing on /accept-invite, and assignTypeByEmailInTx writes the account type under a pending:<email> placeholder that resolveAccountType adopts on first login. Nothing in the admin queue breaks on deploy. New rows always carry a clerk_user_id, so over time this path only drains.
Reject is DB-only (no external side effects), so it's a single atomic transaction: flip status → rejected (re-asserting the row is still actionable via actionableRequestWhere()), set account_type = rejected, write access_request.rejected + account_type.changed audit rows, then best-effort send the rejection email (which includes the reviewer's note if one was given). The applicant's /approval screen flips to rejected on its next poll and shows the reviewer's note; they may re-apply (a new request row is allowed because the one-open-request index only covers pending / auto_approved). Rejected users also appear in the Rejected list on /admin/accounts with a "Move to Pending" action to reconsider.
buildAccessStatusEmail (lib/email-templates.ts) is one builder with an approved boolean, rendered through the shared Email Design System: approvals get a "Go to the Partner Portal" flyer button; rejections get no button and a "Reason" block carrying the optional rejection reason. Sent via Resend (RESEND_API_KEY, RESEND_FROM_EMAIL=partners@matters.ai). Email sending is after the DB commit and best-effort (.catch() logs failure) — a mail hiccup never rolls back an approval that already happened. See Operations for Resend setup.
| Artifact | Where |
|---|---|
| Clerk organization membership (existing org) or a new organization with the applicant as admin | Clerk (addUserToOrg / createOrganizationForUser; legacy rows: inviteToExistingOrg / createOrgWithAdminInvite) |
| Clerk invitation (legacy rows only) | Clerk → email → /accept-invite |
partner_accounts row for the email domain (status active) | Neon |
account_type = partner | prospect (assigned) | partner_sessions |
granted_account_type, granted_org_id, decided_at on the request | partner_access_requests |
access_request.approved + account_type.changed events | activity_log (Audit Log) |
| Approval email | Resend |
/approvalpartner_access_requests columns and indexespartner_accounts drives auto-classification