Skip to content

Write an auth adapter

VexCMS ships one auth integration, @vexcms/better-auth. An app that signs people in with something else, such as Clerk or Convex Auth, connects it by providing the same seven pieces @vexcms/better-auth provides. This page lists each piece, what it has to do, and how the Better Auth integration does it. The examples are the files a new project gets from create-vexcms, rendered from the installer when these docs were built.

No adapter for another provider has been written or tested yet. Treat this page as the contract to build against, not a recipe. If you build one, please open a discussion about it.

  1. A server auth adapter registered on vex.config.server.ts.
  2. Matching client auth collections on vex.config.ts.
  3. A user document carrying roles.
  4. A Convex getAuth that resolves the caller in every query and mutation.
  5. A Convex client that sends the user’s token.
  6. Admin route session and sign-in/out.
  7. A first-admin bootstrap.

defineServerConfig({ server: { auth: { adapter } } }) takes a VexAuthAdapter:

  • name — a provider id, used in errors and telemetry.
  • collections — the auth provider’s tables as VexCMS collections (AuthCollectionConfig[]). VexCMS generates their schema, lists them in the admin, and merges them with your own collections. Mark fields the provider owns locked, and set protected on tables users must not redefine (see Authentication).
  • userCollection — the slug of the collection holding user documents.
  • clientWritableUserFields — fields a person can set through the provider’s own public endpoints, such as sign-up. defineServerConfig throws when the roles field is in this list. Leave it unset only if you can’t tell.

Better Auth builds all four from its options with betterAuthAdapter:

src/vex.config.server.ts
import { betterAuthAdapter } from "@vexcms/better-auth"
import { defineServerConfig } from "@vexcms/core"
import { convexFileStorage } from "@vexcms/file-storage-convex"
import { authOptions } from "@convex/auth/options"
import vexConfig from "./vex.config"
/**
* VexCMS server-only configuration for this project.
*
* Layers the Better Auth adapter and Convex file storage onto the
* client-safe `vexConfig`. You write this file once at scaffold time and
* rarely revisit it — day-to-day settings live in `vex.config.ts`.
*
* @see defineServerConfig in @vexcms/core
* @see betterAuthAdapter in @vexcms/better-auth
* @see ./vex.config for the client-safe half this layers onto
*/
const config = defineServerConfig({
config: vexConfig,
server: {
auth: { adapter: betterAuthAdapter({ config: authOptions }) },
storage: {
adapters: [convexFileStorage()],
},
},
})
export default config

The admin also runs in the browser, where the server adapter, with its secrets and plugin code, must not go. vex.config.ts therefore gets the same collections from a client-safe description through defineConfig({ authCollections }), and defineServerConfig throws when the two disagree. Better Auth builds them with betterAuthCollections from @vexcms/better-auth/client, from convex/auth/schema.ts, a module with no server imports:

src/vex.config.ts
import { authSchema } from "@convex/auth/schema"
import { betterAuthCollections } from "@vexcms/better-auth/client"
import { defineConfig } from "@vexcms/core"
import { uploadFile } from "@vexcms/file-storage-convex/client"
import { plateEditor } from "@vexcms/richtext-plate"
import { access } from "~/auth/access"
import {
images,
posts, // Example: posts
users,
} from "~/vexcms/collections"
/**
* VexCMS client-safe configuration for this project.
*
* Registers the admin sidebar layout and every collection, global, and
* media collection. Add collections/globals here as you define them —
* `vex dev` / `vex generate` derive the Convex schema and TypeScript types
* from this file, and the browser imports it directly via
* `VexConfigProvider`, so nothing here may reach a server SDK or an
* environment variable.
*
* @see defineConfig in @vexcms/core
* @see ./vex.config.server for the auth adapter and storage adapter wiring
*/
const vexConfig = defineConfig({
access,
authCollections: betterAuthCollections(authSchema),
// Editor for every `richtext()` field. Without one, a richtext field shows a config error in the admin.
editor: plateEditor(),
admin: {
sidebar: {
side: "right",
},
},
storage: {
clientUploads: { convex: uploadFile },
},
collections: [
users,
posts, // Example: posts
],
mediaCollections: [images],
})
export default vexConfig
convex/auth/schema.ts
import type { BetterAuthSchemaInput } from "@vexcms/better-auth/client"
import {
TABLE_SLUG_ACCOUNTS,
TABLE_SLUG_SESSIONS,
TABLE_SLUG_USERS,
TABLE_SLUG_VERIFICATIONS,
USER_ROLES,
} from "~/db/constants"
/**
* Everything about your Better Auth setup that determines which collections
* exist and which fields they carry — and nothing else.
*
* This is the one auth module the browser reads: `src/vex.config.ts` passes it
* to `betterAuthCollections()` to build the admin panel's auth collections,
* and `./options` spreads it so the same model names and fields reach the
* database. Add a `user.additionalFields` entry here and it shows up in both.
*
* Keep it inert. `./options` reads `process.env` and `./plugins` pulls
* `better-auth/next-js` (→ `next/headers`), which is why they are separate
* files — importing either from the client config would drag the server into
* your browser bundle. Runtime plugin options (admin roles, mailers, OAuth
* secrets) belong on the real plugin instances in `./plugins`; only options
* that change which TABLES exist belong here.
*
* @see betterAuthCollections in @vexcms/better-auth/client
* @see ./options for the server-side options that spread this
*/
export const authSchema = {
account: { modelName: TABLE_SLUG_ACCOUNTS },
session: { modelName: TABLE_SLUG_SESSIONS },
user: {
modelName: TABLE_SLUG_USERS,
additionalFields: {
roles: {
type: "string[]",
defaultValue: [USER_ROLES.user],
required: true,
input: false,
},
},
},
verification: { modelName: TABLE_SLUG_VERIFICATIONS },
plugins: {
admin: true,
anonymous: true,
apiKey: true,
convex: true,
},
} satisfies BetterAuthSchemaInput

Your adapter needs the same split: one function that both the server adapter and the client config call, so the collections match by construction.

Every permission check reads the caller’s roles from the user document, from the field access.userRolesField names (a string or a string array). A user without that field gets no roles, and every check denies. Only trusted server code may write it. Better Auth declares it as an additional field with input: false, so sign-up can’t set it, and the template’s anonRoleDatabaseHook gives anonymous users the anonymous role. See Access control.

src/auth/access.ts
import { defineAccess } from "@vexcms/core"
import { TABLE_SLUG_USERS, USER_ROLES } from "~/db/constants"
import {
images,
posts, // Example: posts
users,
} from "~/vexcms/collections"
/**
* Access control (RBAC) for the admin panel and every registered collection.
*
* Roles (`~/db/constants/auth.ts`):
* - `admin` — unrestricted.
* - `editor` — admin panel; full control of posts and images.
* - `viewer` — admin panel, read-only.
* - `user` — every new sign-up. Own profile and `images` read; no admin panel.
* An admin promotes people to `editor`/`viewer` from the Users list.
*
* Each subject (collection, global, `adminPanel`) takes `true`/`false` or a
* per-action map; `"*"` sets the default for whatever isn't named. A check can
* also be a constraint (`where`/`withIndex`) or a function returning a
* field map, which allows or denies individual fields. Add a resource here
* whenever you register a new collection in `vex.config.ts`.
*
* `anonRole: user` also covers every unauthenticated public-site request,
* including the build-time metadata fetch. `images.read` is what lets the
* public site show uploaded media at all: `MediaImage` and
* `src/lib/metadata.ts` resolve uploads through the RBAC-gated
* `vex/media:getUrl`, so without it anonymous visitors get no images and the
* page ships no `og:image`. Narrow it with a `constraints` rule if some media
* must stay private; do not remove it. To render posts on the public site,
* give `user` `posts: { "*": false, read: true }` (published posts only;
* drafts need `readDrafts`).
*
* @see https://docs.vexcms.dev/guides/access-control/
*/
export const access = defineAccess({
anonRole: USER_ROLES.user,
roles: Object.values(USER_ROLES),
userRolesField: "roles",
userCollectionSlug: TABLE_SLUG_USERS,
resources: [
images,
users,
posts, // Example: posts
],
permissions: {
[USER_ROLES.admin]: {
"*": true,
},
[USER_ROLES.editor]: {
"*": false,
adminPanel: {
access: true,
},
images: true,
// Example: posts
posts: {
"*": true,
// Field-level rule: editors can change every field except `author`.
// Only `update`/`saveDraft` carry it; a create (including Duplicate) may
// set `author`, and the `beforeChange` hook fills it in when empty.
// A changed value is what gets denied: the admin form sends only edited
// fields, but an API call sending `author: []` for an empty author counts
// as a change and is rejected.
update: () => ({ "*": true, author: false }),
saveDraft: () => ({ "*": true, author: false }),
},
user: {
"*": false,
// Field-level rule: their own row in full, other users' names only
// (enough to show a post's author).
read: ({ user, data }) => (data?.email === user.email ? { "*": true } : { "*": false, name: true }),
update: {
where: ({ user, q }) => q.eq("email", user.email),
},
},
},
[USER_ROLES.viewer]: {
"*": false,
adminPanel: {
access: true,
},
images: {
"*": false,
read: true,
},
// Example: posts
posts: {
"*": false,
read: true,
readDrafts: true,
readViews: true,
},
user: {
"*": false,
read: ({ user, data }) => (data?.email === user.email ? { "*": true } : { "*": false, name: true }),
update: {
where: ({ user, q }) => q.eq("email", user.email),
},
},
},
[USER_ROLES.user]: {
"*": false,
adminPanel: {
access: false,
},
images: {
"*": false,
read: true,
},
user: {
"*": false,
read: {
withIndex: ({ user }) => ({ name: "by_email", range: (ix) => ix.eq("email", user.email) }),
},
update: {
where: ({ user, q }) => q.eq("email", user.email),
},
},
},
},
})

Every Convex function VexCMS builds (collectionsApi, globals, media, versions, vexServerApi) takes a getAuth(ctx) that returns { user, organization? } (VexApiAuth). user is the caller’s user document, or null when signed out; organization is needed only when access has an orgCollectionSlug.

Better Auth’s createGetAuth reads ctx.auth.getUserIdentity(), loads the user document by identity.subject, and, with organizations on, follows identity.sessionId to the session’s active organization. It reads the documents on every call and uses token claims only as ids, so role changes apply at once. A Clerk or Convex Auth adapter does the same from its own identity: find the user document for the token’s subject and return it.

convex/vex.ts
import { createGetAuth } from "@vexcms/better-auth";
import { collectionsApi, createVexMutations } from "@vexcms/core/server";
import { TABLE_SLUG_SESSIONS, TABLE_SLUG_USERS } from "~/db/constants";
import config from "~/vex.config.server";
import { internalMutation, mutation, query } from "./_generated/server";
/**
* Trigger-wrapped `mutation`/`internalMutation` builders — every write made
* through them fires the written collection's `afterChange`/`afterDelete`
* hooks (`@vexcms/core`'s `createVexMutations`). Used, not exported: this
* file's own `create`/`update`/`remove` (below) and `globals.ts`/`media.ts`
* build their mutations on `vexMutation`, never the raw builder above.
*/
export const { mutation: vexMutation, internalMutation: vexInternalMutation } = createVexMutations({
config,
mutation,
internalMutation,
});
/**
* `getAuth` resolver for this file's own `collectionsApi` call below, and
* exported for `versions.ts` (the only other `convex/vex/*` module that needs
* it — `globals.ts`/`media.ts` each build their own identical call instead of
* importing this one, so the installer's `--orgs`-declined step can strip
* organization wiring from each file independently).
*/
export const getAuth = createGetAuth({
userCollectionSlug: TABLE_SLUG_USERS,
sessionCollectionSlug: TABLE_SLUG_SESSIONS,
resolveOrgs: false,
});
export const {
find,
get,
search,
create,
update,
remove,
livePreviewUrl,
listViews,
saveView,
removeView,
} = collectionsApi({
config,
query,
mutation: vexMutation,
getAuth,
});

getAuth only sees a caller when the Convex client sends their token. Better Auth uses ConvexBetterAuthProvider from @convex-dev/better-auth/react. Other providers have their own (ConvexProviderWithClerk, ConvexAuthProvider), or you call ConvexReactClient.setAuth. The same file wraps the tree in VexCMS’s AuthTransitionProvider, which keeps lists from flashing another identity’s data while a sign-in or sign-out settles:

src/components/providers/convex.tsx
"use client";
import { useEffect, useLayoutEffect, useRef, type ReactNode } from "react";
import { ConvexBetterAuthProvider } from "@convex-dev/better-auth/react";
import { ConvexQueryClient } from "@convex-dev/react-query";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ConvexReactClient } from "convex/react";
import { AuthTransitionProvider, useAuthTransition } from "@vexcms/react";
import { authClient } from "~/auth/client";
import { env } from "~/env.mjs";
/**
* Whether this request's SSR HTML already told us a Better Auth session
* exists, via the `<meta name="vex-session" content="1" />` tag a signed-in
* server render emits (`(vexcms)/admin/layout.tsx`, and the site's
* `posts/[slug]`/`[slug]` pages while Draft Mode is active). A synchronous
* DOM check, not a session fetch: it only needs to be right about "a
* session might exist," not decode or validate anything.
*
* Replaces a `document.cookie` read for `<prefix>.session_token`: Better
* Auth sets that cookie `httpOnly`, so it was never actually visible to
* `document.cookie` — the old check always returned `false`, even for a
* signed-in admin, letting this module's Convex socket start unpaused and
* send its first `ModifyQuerySet` anonymously, well before `setAuth()` ever
* ran.
*
* SECURITY: the hint is a timing hint only, never an auth signal. Its sole
* effect is `expectAuth` (hold queries until the auth handshake). It carries
* no token, user or role, and anyone able to put markup in the page can forge
* it; a forged hint just delays queries until `useResumeIfStaleSessionHint`
* releases the socket anonymously. Never use it to show signed-in UI, gate a
* route, or decide access: read the session (`authClient.useSession()` /
* server `getToken()`) for that. Every Convex query is authorized from the
* JWT sent in `Authenticate`, independent of this hint.
*/
export function hasSessionHint() {
if (typeof document === "undefined") {
return false;
}
return document.querySelector('meta[name="vex-session"]') !== null;
}
/**
* Releases an `expectAuth`-paused socket for a visitor whose SSR session
* hint turned out to be stale — Better Auth resolves to no session by the
* time this hook runs, even though the server render that produced the
* `vex-session` meta tag saw one (e.g. a sign-out in another tab, or a
* session the proxy hasn't invalidated server-side yet but Better Auth no
* longer honors). `ConvexProviderWithAuth` (convex/react) only ever calls
* `client.setAuth()` — the only thing that calls the sync layer's
* `resumeSocket()` — when it resolves an AUTHENTICATED session; for "Better
* Auth has definitively resolved: no session," it never calls anything, so
* an `expectAuth`-paused socket stays paused forever (same hang
* `hasSessionHint` exists to avoid for the common no-hint-at-all case,
* reached here instead via a hint that doesn't resolve).
*
* `client.setAuth(fetchToken, onChange)` → convex's
* `AuthenticationManager.setConfig()` calls `resumeSocket()` unconditionally
* at the end, even when `fetchToken` resolves `null` — so a fetcher that
* always resolves `null` releases the pause without claiming a real
* identity. `onChange` must be a real function: the null-token path calls
* `setAndReportAuthFailed(onAuthChange)`, which invokes it unconditionally.
*
* Fires at most once per client (`resumed` ref): if a REAL session later
* appears (the hint wasn't stale after all, or the visitor signs in),
* `ConvexProviderWithAuth` calls `client.setAuth(realFetchAccessToken, ...)`
* itself — a fresh `setConfig()` call `resetAuthState()`s and bumps
* convex's internal `configVersion`, which supersedes this call's
* already-finished null-token config exactly like a normal token refresh.
* Without the ref guard this would also re-fire on every later sign-out,
* needlessly pausing+resuming an already-unpaused, already-live socket.
*/
function useResumeIfStaleSessionHint(convex: ConvexReactClient, startedPaused: boolean) {
const { data: session, isPending } = authClient.useSession();
const resumed = useRef(false);
useEffect(() => {
if (startedPaused && !resumed.current && !isPending && !session) {
resumed.current = true;
void convex.setAuth(
() => Promise.resolve(null),
() => undefined,
);
}
}, [convex, isPending, session, startedPaused]);
}
/**
* Reactively sets the shared auth-transition marker (`@vexcms/react`'s
* `useAuthTransition`) the moment this browser's `authClient.useSession()`
* identity changes — covers every way a session can start or end (credential
* sign-in, magic link, OAuth, a tab regaining an updated session, …) through
* ONE call site, rather than needing one at each entry point. Paired with the
* `signOut` wrapper's own explicit, even-earlier `beginTransition(null)` call
* (`~/auth/client.tsx`) for the one case that can be told synchronously, with
* zero network latency, ahead of this hook ever re-running.
*
* `useLayoutEffect`, not a render-phase call: `beginTransition` updates
* `AuthTransitionProvider`'s OWN state, an ANCESTOR of this hook's caller —
* React only supports the "set state conditionally during render" pattern
* (`usePaginatedQuery.ts`'s own `resetKey` block) for a component's OWN
* state, never a different component's (React warns: "Cannot update a
* component while rendering a different component"). `useLayoutEffect`
* (not `useEffect`) still fires synchronously after this render commits,
* before the browser paints — the earliest point updating someone ELSE's
* state is actually supported.
*/
function useBeginAuthTransitionOnSessionChange() {
const { beginTransition } = useAuthTransition();
const { data: session } = authClient.useSession();
const identity = session?.user?.id ?? null;
const lastIdentityRef = useRef(identity);
useLayoutEffect(() => {
if (identity !== lastIdentityRef.current) {
lastIdentityRef.current = identity;
beginTransition(identity);
}
}, [identity, beginTransition]);
}
function makeClients() {
// `expectAuth` pauses the Convex WebSocket at construction until
// `client.setAuth()` is called; `ConvexProviderWithAuth` (convex/react)
// only calls it when the auth provider reports an authenticated session.
// The public site's own `anonRole` fallback means most visitors carry NO
// Better Auth session at all, so for them that never becomes true and the
// socket would stay paused forever — every live client query (including
// public-site live-preview subscriptions like `ThemeLive`) sits at
// `status: "pending"` indefinitely.
//
// `hasSessionHint()` is checked synchronously (not a session fetch, and
// never server-side — SSR here always gets a fresh client whose websocket
// is never used for live queries anyway) so a visitor whose signed-in
// server render emitted the `vex-session` meta tag keeps the pre-auth
// pause — avoiding a flash of anon-role query results before `setAuth`
// re-subscribes with their real identity (zero-layout-shift) — while a
// visitor with no hint at all starts unpaused and gets live queries
// immediately.
const startedPaused = hasSessionHint();
const convex = new ConvexReactClient(env.NEXT_PUBLIC_CONVEX_URL, {
expectAuth: startedPaused,
});
const convexQueryClient = new ConvexQueryClient(convex);
const queryClient = new QueryClient({
defaultOptions: {
queries: {
queryFn: convexQueryClient.queryFn(),
queryKeyHashFn: convexQueryClient.hashFn(),
// Deterministic: a thrown ConvexError re-fails identically, so retrying
// only delays the error reaching `error` (it sits in `failureReason`
// while retrying).
retry: false,
// Convex queries ride the Convex WebSocket, not `fetch`, so TanStack's
// `onlineManager` must never gate them: a paused query stays
// `status: "pending"` / `error: null` forever and ignores `retry`.
networkMode: "always",
},
},
});
convexQueryClient.connect(queryClient);
return { convex, queryClient, startedPaused };
}
let browserClients: ReturnType<typeof makeClients> | undefined;
/**
* Wires Convex, TanStack Query, and Better Auth together for the app.
*
* Clients are module-level singletons connected synchronously so Convex
* reactive subscriptions are established before any query is added to the
* TanStack Query cache. See module-level comment above.
*
* @param props.children - The subtree that needs Convex and query access.
*/
export default function ConvexClientProvider({ children }: { children: ReactNode }) {
const { convex, queryClient, startedPaused } = getClients();
useResumeIfStaleSessionHint(convex, startedPaused);
return (
<AuthTransitionProvider>
<ConvexBetterAuthProvider authClient={authClient} client={convex}>
<QueryClientProvider client={queryClient}>
<AuthTransitionSessionWatcher>{children}</AuthTransitionSessionWatcher>
</QueryClientProvider>
</ConvexBetterAuthProvider>
</AuthTransitionProvider>
);
}
/** Mounts {@link useBeginAuthTransitionOnSessionChange} — needs an `AuthTransitionProvider`
* ancestor, which `ConvexClientProvider` only establishes one level up. */
function AuthTransitionSessionWatcher({ children }: { children: ReactNode }) {
useBeginAuthTransitionOnSessionChange();
return <>{children}</>;
}
function getClients() {
if (typeof window === "undefined") {
// Server: brand-new clients every request → no cross-request cache leak
return makeClients();
}
// Browser: singleton → preserves Convex WebSocket reactivity
browserClients ??= makeClients();
return browserClients;
}

Three things connect the Next.js side:

  • The admin route resolves the caller on the server and passes it to NextAdminPage and NextAdminLayout as authPromise (a VexApiAuth), along with the Convex token as tokenPromise. It checks canAccessAdminPanel before rendering and redirects signed-out callers to sign-in.
  • VexAdminAuthAdapterProvider from @vexcms/next/auth gives the admin’s top bar signInHref(redirectTo) and signOut(). signOut must finish with window.location.reload(), never a client-side navigation. The framework adapters guide explains why.
  • VexSessionAdapterProvider from @vexcms/react gives public pages a useSession() returning { user, organization?, isPending }, so useCanAccessAdminPanel can show an “Admin” link outside /admin.
src/app/(vexcms)/admin/[[...path]]/page.tsx
import { canAccessAdminPanel, loadVexConfigModule } from "@vexcms/core";
import { VexConfigErrorBanner } from "@vexcms/react";
import { NextAdminPage } from "@vexcms/next/server";
import { redirect } from "next/navigation";
import { getToken, getUserOrgForVexApi } from "~/auth/server";
export const dynamic = "force-dynamic";
/**
* Admin panel route. Gates on two separate things, both resolved BEFORE anything streams:
*
* 1. **Authentication** — `getToken()` is a local jwtCache decode (the `cookiePrefix`
* fix — ~0-1ms, not a network round trip), so awaiting it here costs nothing
* material. A missing token no longer redirects on its own: `getUserOrg()` is itself
* `cache()`-wrapped and safe to call with no session (`{ user: null, organization:
* undefined }`, never throws), so authorization is checked regardless — an app whose
* `anonRole` grants `adminPanel.access` lets an anonymous caller straight through, no
* sign-in detour. An app that hasn't configured that (the default) gets the exact
* same redirect as before, just one step later.
* 2. **Authorization** — the caller must satisfy `adminPanel.access` in the access
* matrix. `canAccessAdminPanel` is awaited sequentially — nothing streams until it
* resolves. `getUserOrg()` is `cache()`-wrapped (React's per-request dedupe), so this
* costs no extra round trip when something upstream already resolved the same caller
* this request.
*
* Denied redirects to `/auth/sign-in` when there was genuinely no token, else
* `/unauthorized` (a signed-in caller whose role doesn't pass).
*
* This is now the ONLY gate for `/admin/*`:
* `src/proxy.ts`'s general session gate used to also run on `/admin/*`, and no
* longer does — `/admin/*` is excluded from its matcher entirely, so the admin
* panel never imports `~/vex.config` (and the client components it drags in) on
* the edge. Two things here now reproduce what that proxy pass used to do for
* this route:
* - `redirectTo` carries the FULL requested path + query (rebuilt from `params`
* and `searchParams`, URL-encoded below), not a hard-coded `/admin` — so
* sign-in lands the caller back where they were headed.
* - `getToken()`/`getUserOrg()` are awaited inside a `try`/`catch`: a session
* **verification** failure (Convex unreachable, a lookup timeout) redirects to
* `/unauthorized` — fail closed, mirroring the proxy's own fail-closed
* behavior — instead of surfacing as a 500. `redirect()` throws its own
* control-flow error to unwind to the nearest segment, so it is only ever
* called from the `catch` block, never awaited inside the `try`.
*
* `NextAdminPage` streams its own real chrome immediately once rendered and wraps only
* its own data-dependent regions in their own `<Suspense>` boundaries — see its own doc
* comment.
*
* Both configs load through `loadVexConfigModule`, never a static import: a config that throws
* while its module evaluates would otherwise fail this route before anything renders. The gate
* reads `access` from the client config (the server config spreads that same object), so a
* server-only failure — an unregistered storage adapter, auth collections that disagree with the
* adapter — still redirects signed-out callers as usual, and only admitted callers see its
* `VexConfigErrorBanner` inside the admin chrome. A client-config failure has nothing to gate
* with; the root layout already renders its banner in place of the whole app.
*/
export default async function AdminPage({
params,
searchParams,
}: {
params: Promise<{ path?: string[] }>;
searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
const [resolvedParams, resolvedSearchParams] = await Promise.all([params, searchParams]);
const clientConfig = await loadVexConfigModule({ load: () => import("~/vex.config") });
if (clientConfig.status === "invalid") {
return <VexConfigErrorBanner error={clientConfig.error} />;
}
const session = await loadAdminSession();
if (!session) {
redirect("/unauthorized");
}
const { token, auth } = session;
if (
!canAccessAdminPanel({
access: clientConfig.config.access,
user: auth.user,
organization: auth.organization,
})
) {
redirect(
token
? "/unauthorized"
: `/auth/sign-in?redirectTo=${encodeURIComponent(
buildAdminRequestPath(resolvedParams.path, resolvedSearchParams),
)}`,
);
}
const serverConfig = await loadVexConfigModule({ load: () => import("~/vex.config.server") });
if (serverConfig.status === "invalid") {
return <VexConfigErrorBanner error={serverConfig.error} />;
}
return (
<NextAdminPage
config={serverConfig.config}
params={params}
searchParams={searchParams}
tokenPromise={Promise.resolve(token)}
authPromise={Promise.resolve(auth)}
/>
);
}
/**
* Resolves the session, failing closed: a `getToken()`/`getUserOrg()` throw
* (Convex unreachable, a lookup timeout) returns `null` rather than letting
* the error surface as a 500 — the caller redirects to `/unauthorized`.
*/
async function loadAdminSession() {
try {
const token = await getToken();
const auth = await getUserOrgForVexApi();
return { token, auth };
} catch {
return null;
}
}
/**
* Rebuilds the full requested admin path (segments + query) from the route's
* own `params`/`searchParams`, for the sign-in `redirectTo`. The result is
* passed through `encodeURIComponent` by the caller as a single opaque blob,
* so values here are joined raw rather than individually encoded.
*/
function buildAdminRequestPath(
path: string[] | undefined,
searchParams: Record<string, string | string[] | undefined>,
): string {
const segments = path?.length ? `/${path.join("/")}` : "";
const query = Object.entries(searchParams).flatMap(([key, value]) =>
value === undefined ? [] : (Array.isArray(value) ? value : [value]).map((v) => `${key}=${v}`),
);
return `/admin${segments}${query.length ? `?${query.join("&")}` : ""}`;
}
src/app/(vexcms)/admin/layout.tsx
import type { ReactNode } from "react"
import { NextAdminLayout } from "@vexcms/next/client"
import { getToken, getUserOrgForVexApi } from "~/auth/server"
/**
* `AuthServerProvider` (`~/components/providers/auth`) used to wrap `{children}` here —
* removed (perf fix, measured): it `await`s `getToken()`/`getUserOrg()` BEFORE
* returning its own `{children}`, so React cannot begin streaming ANYTHING inside it
* until that resolves, regardless of `NextAdminLayout`'s own `authPromise` plumbing.
* Safe to remove: its own `AuthContext` (`useAuth()`) has zero consumers inside the
* admin tree.
*/
export default async function AdminLayout({ children }: { children: ReactNode }) {
// Not awaited — `NextAdminLayout` resolves it inside the sidebar's OWN `<Suspense>`
// boundary (`@vexcms/react`'s `AdminLayout`), so `{children}` and this layout's own
// static chrome stream immediately instead of waiting on a Convex round trip.
const authPromise = getUserOrgForVexApi()
// Awaited, unlike `authPromise` above: `getToken()` is `cache()`-memoized AND, when a
// valid JWT cookie is present, resolves from a local decode (no network round trip —
// see `auth/server.ts`'s `jwtCache` comment), so this costs far less than `getUserOrg()`
// would. It must be awaited (not streamed via Suspense): the `<meta name="vex-session">`
// it gates below needs to land in the INITIAL, non-deferred SSR HTML — before any
// client script hydrates — for `convex.tsx`'s `hasSessionHint()` to see it synchronously
// at hydration time (see that module's own doc comment).
const sessionToken = await getToken()
return (
// `VexConfigProvider` is mounted once by the root layout's
// `ClientProviders`, for the admin and the public site alike.
<>
{/* Tells `components/providers/convex.tsx`'s `hasSessionHint()` that a Better Auth
session exists for this request, synchronously and before hydration — Better Auth's
own `session_token` cookie is `httpOnly`, so `document.cookie` can never see it
client-side. Never the token itself: just a presence marker. */}
{sessionToken ? <meta name="vex-session" content="1" /> : null}
<NextAdminLayout authPromise={authPromise}>{children}</NextAdminLayout>
</>
)
}
src/auth/client.tsx
import type { ReactNode } from "react"
import { apiKeyClient } from "@better-auth/api-key/client"
import { convexClient } from "@convex-dev/better-auth/client/plugins"
import { VexAdminAuthAdapterProvider } from "@vexcms/next/auth"
import { disableLivePreview } from "@vexcms/next/livePreview/client"
import { clearEditScrollStorage, useAuthTransition } from "@vexcms/react"
import { adminClient, anonymousClient } from "better-auth/client/plugins"
import { createAuthClient } from "better-auth/react"
import { env } from "~/env.mjs"
/**
* Global Better Auth client for this project.
*
* Configured with the site's auth base URL and plugins for admin roles,
* anonymous access, API key auth, and Convex session storage. Add
* `organizationClient()` from `better-auth/client/plugins` here if you enable
* organizations (`--orgs`, or by hand later) — the server-side `organization()`
* plugin alone does not surface org UI on the client.
*
* @see signIn, signOut, useSession — destructured from this client
* @see BetterAuthClientProvider — wraps the app with this client
*/
export const authClient = createAuthClient({
basePath: "/api/auth",
// Same-origin in the browser: a Vercel deployment's own URL (`….vercel.app`)
// differs from `NEXT_PUBLIC_SITE_URL`, and a cross-origin call is blocked by
// the CSP's `connect-src 'self'`. The env value only serves server renders,
// where there is no window.
baseURL: typeof window === "undefined" ? env.NEXT_PUBLIC_SITE_URL : window.location.origin,
plugins: [adminClient(), anonymousClient(), apiKeyClient(), convexClient()],
})
export const { signIn, signOut, useSession } = authClient
// eslint-disable-next-line @typescript-eslint/no-empty-function
authClient.$store.listen("$sessionSignal", () => {})
/**
* Mounts `VexAdminAuthAdapterProvider` (`@vexcms/next/auth`) so the admin
* panel's top-bar sign-in/out control (`AdminTopNav`) has a `signInHref`/`signOut`
* to call. `signOut` signs out, then full-reloads the current page
* (`window.location.reload()`, NOT `router.refresh()`/`router.push()`/a
* navigation to a different destination) — the admin shell must never
* re-render in a signed-out state, and a client-side refresh instead keeps
* it mounted while queries re-run anonymously and the route guard redirects
* underneath it (the multi-second "sidebar lingers, then a sign-in flash"
* sequence this full reload avoids). The reload re-requests the current
* URL, so the app's own server-side access guards decide what it shows
* signed out.
*/
export default function BetterAuthClientProvider({ children }: { children: ReactNode }) {
// Needs an `AuthTransitionProvider` ancestor — `ConvexClientProvider`
// (`~/components/providers/convex.tsx`) mounts it one level up from this
// component, same as `~/components/providers/client.tsx`'s nesting order.
const { beginTransition } = useAuthTransition()
return (
<VexAdminAuthAdapterProvider
value={{
// `modal=1` is the signal `app/@auth/(.)auth/[pathname]/view.tsx`
// uses to tell this deliberate "Sign in" click apart from a server
// GUARD redirect (middleware, or `/admin`'s own `redirect(...)`)
// that also carries `redirectTo` — both would otherwise collapse
// onto the same `isGuardRedirect` branch and render the full-screen
// card instead of the dialog `AdminTopNav`'s control expects.
signInHref: (redirectTo) =>
`/auth/sign-in?redirectTo=${encodeURIComponent(redirectTo)}&modal=1`,
signOut: () => {
// Set BEFORE the network call starts, not after it resolves — the
// one case the identity is known with zero ambiguity ahead of
// time (always `null`), so list hooks start ignoring stale pages
// as early as possible (`@vexcms/react`'s `useAuthTransition`).
// `skipRefresh: true` — this `signOut` already full-reloads below,
// so `useNextAuthTransitionRefresh`'s OWN `router.refresh()` for
// this same transition would only race that reload (see that
// hook's own doc comment, `@vexcms/next`).
// `useBeginAuthTransitionOnSessionChange` (`~/components/providers/convex.tsx`)
// also reactively catches this once `authClient.useSession()`
// updates, so this call is a latency optimization, not the only path.
beginTransition(null, { skipRefresh: true })
// Clears any stale live-preview cookies left over from this tab or
// the pop-out preview tab — see `disableLivePreview`'s own doc
// comment. Fire-and-forget: it never throws, so it cannot block
// sign-out either way.
void disableLivePreview()
// Clears every persisted edit-view scroll offset, so a different
// identity signing in on this same tab never inherits this one's
// remembered scroll positions.
clearEditScrollStorage()
const reloadPage = () => {
window.location.reload()
}
// Reload either way (success or failure) — a stale client cache
// after a failed sign-out is worse than a redundant reload, and a
// full document load re-resolves auth state fresh regardless,
// through the app's own server-side access guards for this page.
return signOut().then(reloadPage).catch(reloadPage)
},
}}
>
{children}
</VexAdminAuthAdapterProvider>
)
}
src/components/providers/client.tsx
"use client"
// First, so Zod is jitless before any import below can run a parse.
import "~/lib/zodJitless"
import { VexConfigProvider, VexSessionAdapterProvider } from "@vexcms/react"
import { type PropsWithChildren } from "react"
import BetterAuthClientProvider, { useSession } from "~/auth/client"
import ConvexClientProvider from "~/components/providers/convex"
import config from "~/vex.config"
/**
* Mounts the app-wide client providers, including the single
* `VexConfigProvider` for the WHOLE app — admin and public site alike.
*
* One mount, at the root, because both trees need the config now: the admin
* views always did, and `LivePreviewProvider` reads its collections, globals,
* and allowed origins from the same context rather than from props. Two mounts
* would be two provenances for one config.
*
* `"use client"` so `vex.config` is imported and owned on the client — it never
* crosses the RSC boundary as a prop, which React would refuse: the config
* carries functions (field validators, `admin.livePreview.url` resolvers).
*
* Also mounts `VexSessionAdapterProvider`, wrapping Better Auth's own
* `useSession()` — the bridge `useCanAccessAdminPanel()` needs to resolve the
* caller on a PUBLIC page, where no `VexAuthProvider` (server-resolved,
* `/admin`-only) is ever mounted. `isPending` passes straight through:
* `useCanAccessAdminPanel()` never claims `canAccess` until the session
* settles, matching `SessionButton`'s own "reserve the slot" hydration
* contract — no `organization` here, since neither template's public-page
* admin-panel gating needs it.
*/
export default function ClientProviders({ children }: PropsWithChildren) {
return (
<ConvexClientProvider>
<BetterAuthClientProvider>
<VexSessionAdapterProvider
value={{
useSession: () => {
const { data, isPending } = useSession()
return { user: data?.user ?? null, isPending }
},
}}
>
<VexConfigProvider config={config}>{children}</VexConfigProvider>
</VexSessionAdapterProvider>
</BetterAuthClientProvider>
</ConvexClientProvider>
)
}

A new deployment has no admin, so nobody can open /admin to grant the role. The template promotes the first account that signs up, inside one Convex mutation so two sign-ups can’t both win. It finds the caller by identity.email; an adapter whose tokens carry no email looks the user up by identity.subject instead.

convex/vex/firstUser.ts
import { ConvexError } from "convex/values"
import { TABLE_SLUG_USERS } from "~/db/constants"
import { USER_ROLES } from "~/db/constants/auth"
import { find, update } from "~/vexcms/api"
import { query } from "../_generated/server"
import { vexMutation as mutation } from "../vex"
/**
* Check whether the admin panel has been bootstrapped (at least one admin
* exists). Used by `WelcomePage` to decide between "Sign Up" and "Sign In".
*/
export const isBootstrapped = query({
args: {},
handler: async (ctx) => {
const allUsers = await find({ ctx, collection: TABLE_SLUG_USERS, access: { bypass: true } })
return allUsers.some((user) => user.roles?.includes(USER_ROLES.admin))
},
})
/**
* Promote the current user to admin if no admin exists yet. Called after the
* first user signs up.
*
* Convex mutations are serialized, so two simultaneous signups cannot both
* become admin — the second observes the first's promotion and no-ops.
*/
export const promoteFirstAdmin = mutation({
args: {},
handler: async (ctx) => {
const identity = await ctx.auth.getUserIdentity()
if (!identity?.email) {
throw new ConvexError("Not authenticated")
}
const [currentUser] = await find({
ctx,
collection: TABLE_SLUG_USERS,
withIndex: { name: "by_email", range: (q) => q.eq("email", identity.email!) },
limit: 1,
access: { bypass: true },
})
if (!currentUser) {
throw new ConvexError("User not found")
}
const allUsers = await find({ ctx, collection: TABLE_SLUG_USERS, access: { bypass: true } })
const hasAdmin = allUsers.some((user) => user.roles?.includes(USER_ROLES.admin))
if (hasAdmin) {
return { promoted: false }
}
const currentRoles = currentUser.roles ?? []
if (!currentRoles.includes(USER_ROLES.admin)) {
await update({
ctx,
collection: TABLE_SLUG_USERS,
id: currentUser._id,
data: { roles: [...currentRoles, USER_ROLES.admin] },
access: { bypass: true },
})
}
return { promoted: true }
},
})