Add VexCMS to an existing Next.js app
This guide adds the VexCMS admin panel, its Better Auth sign-in and its Convex functions to a
Next.js app that already runs on Convex. Every file below is what create-vexcms writes for a new
project, rendered from the installer when these docs were built, so it matches the version you
install. Nothing here changes your existing Convex tables. When you want VexCMS to manage a table
you already have, follow Adopt an existing Convex table once the
admin panel runs.
After each step, vex doctor reports what’s still missing and links back to the step:
npx vex doctorpnpm vex doctoryarn vex doctorbunx vex doctordeno x vex doctorIt changes nothing, exits 1 while a required step is missing, and prints JSON with --json
(see Check your setup with vex doctor).
Paths. The files below show a src/ folder. If your app keeps app/ at the project root
(create-next-app’s default), drop the src/ prefix everywhere: src/auth/client.tsx becomes
auth/client.tsx. Route groups such as (vexcms) and (frontend) are only folders for
organizing routes; use your own groups or none.
Organizations. Files that change when you enable multi-tenant organizations show two tabs.
Default is a single-tenant app. With organizations is what create-vexcms --orgs writes.
Choosing a tab switches every file on the page.
Before you start
Section titled “Before you start”vex doctor checks all of these:
- Node.js 22 or later.
- Next.js 16 with the App Router. Next.js 15.1 and later works with a warning: it isn’t
tested, and Next.js 15 calls the proxy file
middleware.ts. A Pages Router app can add anapp/folder besidepages/. - Convex 1.44 or later, below 2.
- Better Auth 1.7.16 or later, below 1.8. The install step adds it.
- Tailwind CSS 4. The admin’s styles use Tailwind 4’s
@importand@source. - Cache Components off. VexCMS’s routes use route segment config (
export const dynamic), which Next.js rejects whencacheComponents: trueis set. If yournext.config.tsturns it on, remove it or set it tofalse. - Convex functions in the same package as the Next.js app.
vex devruns from the folder that holds bothapp/andconvex/. An app inside a monorepo works as long asconvex/sits in the app’s own package. Convex in a separate workspace package isn’t supported yet.
Apps that already have auth
Section titled “Apps that already have auth”VexCMS signs people in with Better Auth, and keeps Better Auth’s tables (user, session,
account, verification, jwks, apikey) in your app’s own Convex schema.
| Your app uses | What to do |
|---|---|
| No auth | Follow this guide. |
A users table of its own |
Follow this guide. VexCMS’s user table is user, so the two don’t collide. |
A table named user |
Follow this guide, then adopt the table so the user collection describes it. |
Better Auth through the @convex-dev/better-auth component |
Migrate to app-schema tables first, then follow this guide. |
| Clerk, Convex Auth or another provider | Not supported out of the box. Write an auth adapter for it. |
Install dependencies
Section titled “Install dependencies”Install the packages a new VexCMS project gets. create-next-app already installed Next.js,
React, TypeScript, ESLint and Tailwind.
npm i @base-ui/react@1.9.0 @better-auth/api-key@1.7.18 @better-auth/core@1.7.18 @better-auth/passkey@1.7.18 @captchafox/react@1.13.0 @convex-dev/better-auth@0.13.0 @convex-dev/react-query@0.1.0 @daveyplate/better-auth-ui@3.4.0 @hookform/resolvers@5.4.0 @marsidev/react-turnstile@1.5.3 @radix-ui/react-avatar@1.2.2 @radix-ui/react-checkbox@1.3.7 @radix-ui/react-dropdown-menu@2.1.20 @radix-ui/react-label@2.1.11 @radix-ui/react-select@2.3.3 @radix-ui/react-separator@1.1.11 @radix-ui/react-tooltip@1.2.12 @t3-oss/env-nextjs@0.13.11 @tanstack/react-form@1.33.5 @tanstack/react-query@5.106.1 @vexcms/better-auth@~0.1.0-alpha.44 @vexcms/core@~0.1.0-alpha.44 @vexcms/file-storage-convex@~0.1.0-alpha.44 @vexcms/next@~0.1.0-alpha.44 @vexcms/react@~0.1.0-alpha.44 @vexcms/richtext-plate@~0.1.0-alpha.44 better-auth@1.7.18 better-call@1.4.5 class-variance-authority@0.7.1 clsx@2.1.1 convex@1.49.0 convex-helpers@0.1.134 input-otp@1.4.2 lucide-react@0.577.0 nuqs@2.10.2 react-hook-form@7.81.0 sonner@2.0.8 tailwind-merge@3.7.0 zod@4.6.7pnpm add @base-ui/react@1.9.0 @better-auth/api-key@1.7.18 @better-auth/core@1.7.18 @better-auth/passkey@1.7.18 @captchafox/react@1.13.0 @convex-dev/better-auth@0.13.0 @convex-dev/react-query@0.1.0 @daveyplate/better-auth-ui@3.4.0 @hookform/resolvers@5.4.0 @marsidev/react-turnstile@1.5.3 @radix-ui/react-avatar@1.2.2 @radix-ui/react-checkbox@1.3.7 @radix-ui/react-dropdown-menu@2.1.20 @radix-ui/react-label@2.1.11 @radix-ui/react-select@2.3.3 @radix-ui/react-separator@1.1.11 @radix-ui/react-tooltip@1.2.12 @t3-oss/env-nextjs@0.13.11 @tanstack/react-form@1.33.5 @tanstack/react-query@5.106.1 @vexcms/better-auth@~0.1.0-alpha.44 @vexcms/core@~0.1.0-alpha.44 @vexcms/file-storage-convex@~0.1.0-alpha.44 @vexcms/next@~0.1.0-alpha.44 @vexcms/react@~0.1.0-alpha.44 @vexcms/richtext-plate@~0.1.0-alpha.44 better-auth@1.7.18 better-call@1.4.5 class-variance-authority@0.7.1 clsx@2.1.1 convex@1.49.0 convex-helpers@0.1.134 input-otp@1.4.2 lucide-react@0.577.0 nuqs@2.10.2 react-hook-form@7.81.0 sonner@2.0.8 tailwind-merge@3.7.0 zod@4.6.7yarn add @base-ui/react@1.9.0 @better-auth/api-key@1.7.18 @better-auth/core@1.7.18 @better-auth/passkey@1.7.18 @captchafox/react@1.13.0 @convex-dev/better-auth@0.13.0 @convex-dev/react-query@0.1.0 @daveyplate/better-auth-ui@3.4.0 @hookform/resolvers@5.4.0 @marsidev/react-turnstile@1.5.3 @radix-ui/react-avatar@1.2.2 @radix-ui/react-checkbox@1.3.7 @radix-ui/react-dropdown-menu@2.1.20 @radix-ui/react-label@2.1.11 @radix-ui/react-select@2.3.3 @radix-ui/react-separator@1.1.11 @radix-ui/react-tooltip@1.2.12 @t3-oss/env-nextjs@0.13.11 @tanstack/react-form@1.33.5 @tanstack/react-query@5.106.1 @vexcms/better-auth@~0.1.0-alpha.44 @vexcms/core@~0.1.0-alpha.44 @vexcms/file-storage-convex@~0.1.0-alpha.44 @vexcms/next@~0.1.0-alpha.44 @vexcms/react@~0.1.0-alpha.44 @vexcms/richtext-plate@~0.1.0-alpha.44 better-auth@1.7.18 better-call@1.4.5 class-variance-authority@0.7.1 clsx@2.1.1 convex@1.49.0 convex-helpers@0.1.134 input-otp@1.4.2 lucide-react@0.577.0 nuqs@2.10.2 react-hook-form@7.81.0 sonner@2.0.8 tailwind-merge@3.7.0 zod@4.6.7bun add @base-ui/react@1.9.0 @better-auth/api-key@1.7.18 @better-auth/core@1.7.18 @better-auth/passkey@1.7.18 @captchafox/react@1.13.0 @convex-dev/better-auth@0.13.0 @convex-dev/react-query@0.1.0 @daveyplate/better-auth-ui@3.4.0 @hookform/resolvers@5.4.0 @marsidev/react-turnstile@1.5.3 @radix-ui/react-avatar@1.2.2 @radix-ui/react-checkbox@1.3.7 @radix-ui/react-dropdown-menu@2.1.20 @radix-ui/react-label@2.1.11 @radix-ui/react-select@2.3.3 @radix-ui/react-separator@1.1.11 @radix-ui/react-tooltip@1.2.12 @t3-oss/env-nextjs@0.13.11 @tanstack/react-form@1.33.5 @tanstack/react-query@5.106.1 @vexcms/better-auth@~0.1.0-alpha.44 @vexcms/core@~0.1.0-alpha.44 @vexcms/file-storage-convex@~0.1.0-alpha.44 @vexcms/next@~0.1.0-alpha.44 @vexcms/react@~0.1.0-alpha.44 @vexcms/richtext-plate@~0.1.0-alpha.44 better-auth@1.7.18 better-call@1.4.5 class-variance-authority@0.7.1 clsx@2.1.1 convex@1.49.0 convex-helpers@0.1.134 input-otp@1.4.2 lucide-react@0.577.0 nuqs@2.10.2 react-hook-form@7.81.0 sonner@2.0.8 tailwind-merge@3.7.0 zod@4.6.7deno add @base-ui/react@1.9.0 @better-auth/api-key@1.7.18 @better-auth/core@1.7.18 @better-auth/passkey@1.7.18 @captchafox/react@1.13.0 @convex-dev/better-auth@0.13.0 @convex-dev/react-query@0.1.0 @daveyplate/better-auth-ui@3.4.0 @hookform/resolvers@5.4.0 @marsidev/react-turnstile@1.5.3 @radix-ui/react-avatar@1.2.2 @radix-ui/react-checkbox@1.3.7 @radix-ui/react-dropdown-menu@2.1.20 @radix-ui/react-label@2.1.11 @radix-ui/react-select@2.3.3 @radix-ui/react-separator@1.1.11 @radix-ui/react-tooltip@1.2.12 @t3-oss/env-nextjs@0.13.11 @tanstack/react-form@1.33.5 @tanstack/react-query@5.106.1 @vexcms/better-auth@~0.1.0-alpha.44 @vexcms/core@~0.1.0-alpha.44 @vexcms/file-storage-convex@~0.1.0-alpha.44 @vexcms/next@~0.1.0-alpha.44 @vexcms/react@~0.1.0-alpha.44 @vexcms/richtext-plate@~0.1.0-alpha.44 better-auth@1.7.18 better-call@1.4.5 class-variance-authority@0.7.1 clsx@2.1.1 convex@1.49.0 convex-helpers@0.1.134 input-otp@1.4.2 lucide-react@0.577.0 nuqs@2.10.2 react-hook-form@7.81.0 sonner@2.0.8 tailwind-merge@3.7.0 zod@4.6.7npm i -D @vexcms/cli@~0.1.0-alpha.44 shadcn@4.23.0 tw-animate-css@1.4.0pnpm add -D @vexcms/cli@~0.1.0-alpha.44 shadcn@4.23.0 tw-animate-css@1.4.0yarn add -D @vexcms/cli@~0.1.0-alpha.44 shadcn@4.23.0 tw-animate-css@1.4.0bun add -d @vexcms/cli@~0.1.0-alpha.44 shadcn@4.23.0 tw-animate-css@1.4.0deno add -D @vexcms/cli@~0.1.0-alpha.44 shadcn@4.23.0 tw-animate-css@1.4.0With pnpm, also merge the scaffold’s install settings into pnpm-workspace.yaml, beside anything
already there (create-next-app writes one too). They pin Better Auth’s passkey plugin and allow
two peer ranges the auth UI declares narrowly:
overrides: "@better-auth/passkey": 1.7.18 "@typescript-eslint/eslint-plugin": 8.72.1 "@typescript-eslint/parser": 8.72.1 "@typescript-eslint/project-service": 8.72.1 "@typescript-eslint/scope-manager": 8.72.1 "@typescript-eslint/tsconfig-utils": 8.72.1 "@typescript-eslint/type-utils": 8.72.1 "@typescript-eslint/types": 8.72.1 "@typescript-eslint/typescript-estree": 8.72.1 "@typescript-eslint/utils": 8.72.1 "@typescript-eslint/visitor-keys": 8.72.1 typescript-eslint: 8.72.1allowBuilds: core-js: false esbuild: falsepeerDependencyRules: allowedVersions: better-call: "2" typescript: "6"packageExtensions: "@hookform/resolvers@5": peerDependencies: zod: ">=3.25.0"Add the scripts the rest of this guide uses to package.json:
{ "scripts": { "vex:dev": "vex dev", "vex:generate": "vex dev --once", "vex:deploy": "vex deploy" }}Path aliases
Section titled “Path aliases”The files below import through two aliases. Add them to compilerOptions.paths in your root
tsconfig.json, beside any alias you already have (such as @/*):
{ "compilerOptions": { "paths": { "~/*": ["./src/*"], "@convex/*": ["./convex/*"] } }}Without a src/ folder, map "~/*" to ["./*"]. vex dev adds the same aliases to
convex/tsconfig.json for you, based on this file.
Shared modules
Section titled “Shared modules”Table names, the auth cookie prefix, typed environment variables and two small helpers. In
src/db/constants/auth.ts, set AUTH_COOKIE_PREFIX to a name unique to your app: browsers share
cookies across every localhost port.
import { type Doc, type Id } from "@convex/_generated/dataModel"
export * from "./auth"
// Better Authexport const TABLE_SLUG_USERS = "user" as constexport type UserDoc = Doc<typeof TABLE_SLUG_USERS>export type UserID = Id<typeof TABLE_SLUG_USERS>
export const TABLE_SLUG_ACCOUNTS = "account" as const
export const TABLE_SLUG_SESSIONS = "session" as constexport type Session = Doc<typeof TABLE_SLUG_SESSIONS>export type SessionID = Id<typeof TABLE_SLUG_SESSIONS>
export const TABLE_SLUG_VERIFICATIONS = "verification" as constexport const TABLE_SLUG_JWKS = "jwks" as constexport const TABLE_SLUG_API_KEYS = "apikey" as const
export const TABLE_SLUG_IMAGES = "images" as const
// Example collection (`src/vexcms/collections/posts.ts`)export const TABLE_SLUG_POSTS = "posts" as const
// Site content (marketing-site overlay)export const TABLE_SLUG_PAGES = "pages" as constexport const TABLE_SLUG_HEADERS = "headers" as constexport const TABLE_SLUG_FOOTERS = "footers" as constexport const TABLE_SLUG_THEMES = "themes" as constexport const GLOBAL_SLUG_SITE_SETTINGS = "siteSettings" as constimport { type Doc, type Id } from "@convex/_generated/dataModel"
export * from "./auth"
// Better Authexport const TABLE_SLUG_USERS = "user" as constexport type UserDoc = Doc<typeof TABLE_SLUG_USERS>export type UserID = Id<typeof TABLE_SLUG_USERS>
export const TABLE_SLUG_ORGANIZATIONS = "organization" as constexport type OrganizationDoc = Doc<typeof TABLE_SLUG_ORGANIZATIONS>export type OrganizationID = Id<typeof TABLE_SLUG_ORGANIZATIONS>
export const TABLE_SLUG_ACCOUNTS = "account" as const
export const TABLE_SLUG_SESSIONS = "session" as constexport type Session = Doc<typeof TABLE_SLUG_SESSIONS>export type SessionID = Id<typeof TABLE_SLUG_SESSIONS>
export const TABLE_SLUG_VERIFICATIONS = "verification" as constexport const TABLE_SLUG_JWKS = "jwks" as constexport const TABLE_SLUG_API_KEYS = "apikey" as const
export const TABLE_SLUG_IMAGES = "images" as const
// Example collection (`src/vexcms/collections/posts.ts`)export const TABLE_SLUG_POSTS = "posts" as const
// Site content (marketing-site overlay)export const TABLE_SLUG_PAGES = "pages" as constexport const TABLE_SLUG_HEADERS = "headers" as constexport const TABLE_SLUG_FOOTERS = "footers" as constexport const TABLE_SLUG_THEMES = "themes" as constexport const GLOBAL_SLUG_SITE_SETTINGS = "siteSettings" as constexport const USER_ROLES = { /** Unrestricted. The first account to sign up is promoted to this (`convex/vex/firstUser.ts`). */ admin: "admin", /** * Every new sign-up and every signed-out visitor (`access.anonRole`). Own * profile and public media only; no admin panel. Promote people from here. */ user: "user", /** Admin panel; creates, edits and publishes content. Assigned by an admin. */ editor: "editor", /** Admin panel, read-only. Assigned by an admin. */ viewer: "viewer",} as constexport type UserRole = (typeof USER_ROLES)[keyof typeof USER_ROLES]
/** * Prefix for every Better Auth cookie this app sets (`<prefix>.session_token`, * or `__Secure-<prefix>.session_token` over https). * * Browsers do not isolate cookies by port, so every app on `localhost` shares * one cookie jar. With Better Auth's default `better-auth` prefix, another * Better Auth app on a different port overwrites — or, if it issues * `__Secure-` cookies, permanently shadows — this app's session. Keep this * unique per app. Read by `convex/auth/options.ts` (issuing) and by * `src/proxy.ts` / `src/auth/serverUtils.ts` (reading). */export const AUTH_COOKIE_PREFIX = "my-app"import { createEnv } from "@t3-oss/env-nextjs"import { z } from "zod"
export const env = createEnv({ /** * Specify your client-side environment variables schema here. This way you can ensure the app * isn't built with invalid env vars. To expose them to the client, prefix them with * `NEXT_PUBLIC_`. */ client: { NEXT_PUBLIC_CONVEX_SITE_URL: z.string(), NEXT_PUBLIC_CONVEX_URL: z.string(), NEXT_PUBLIC_SITE_URL: z.string(), },
/** * Makes it so that empty strings are treated as undefined. `SOME_VAR: z.string()` and * `SOME_VAR=''` will throw an error. */ emptyStringAsUndefined: true,
/** * You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g. * middlewares) or client-side so we need to destruct manually. */ runtimeEnv: { BETTER_AUTH_SECRET: process.env.BETTER_AUTH_SECRET, NEXT_PUBLIC_CONVEX_SITE_URL: process.env.NEXT_PUBLIC_CONVEX_SITE_URL, NEXT_PUBLIC_CONVEX_URL: process.env.NEXT_PUBLIC_CONVEX_URL, NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL, NODE_ENV: process.env.NODE_ENV, }, /** * Specify your server-side environment variables schema here. This way you can ensure the app * isn't built with invalid env vars. */ server: { BETTER_AUTH_SECRET: z.string(), NODE_ENV: z.enum(["development", "test", "production"]), }, /** * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially * useful for Docker builds. * * Also skipped inside the Convex runtime: `convex/vex.ts` imports the admin config, which * can reach this module through registered admin components, and a Convex push never sets * `NEXT_PUBLIC_*` (only Next does). `CONVEX_CLOUD_URL` is set by Convex and never by Next, so * its presence is a reliable signal we are inside a Convex function/push, not a Next process. */ skipValidation: !!process.env.SKIP_ENV_VALIDATION || !!process.env.CONVEX_CLOUD_URL,})import { z } from "zod"
/** * Turns off Zod 4's JIT probe in the browser. * * On its first object parse, Zod runs `new Function("")` inside a try/catch * to find out whether it may compile parsers. The production CSP has no * `'unsafe-eval'`, so the browser blocks it. The throw is caught, but the * browser still records a CSP violation, and Lighthouse fails it as an * `inspector-issues` entry on every page with an auth form. `jitless` skips * the probe. * * Zod keeps this setting on `globalThis.__zod_globalConfig`, so it covers * every Zod 4 copy in the bundle (Better Auth ships its own). Browser-only, * so the server keeps compiled parsers. * * Imported first in `components/providers/client.tsx`, before any module * that might parse. */if (typeof window !== "undefined") { z.config({ jitless: true })}const AUTH_PAGE_TITLES: Record<string, string> = { "forgot-password": "Forgot password", "reset-password": "Reset password", "sign-in": "Sign in", "sign-up": "Sign up",}
/** * Resolves the human-readable title for a better-auth-ui route segment. * * @param pathname - The `[pathname]` route param (e.g. `"sign-in"`). * @returns The matching label, or `"Account"` for any unmapped segment. */export function resolveAuthPageTitle(pathname: string): string { return AUTH_PAGE_TITLES[pathname] ?? "Account"}Convex auth
Section titled “Convex auth”Better Auth runs inside your Convex deployment. These files create it, store its data in your app’s tables, and let Convex verify its tokens.
import type { AuthConfig } from "convex/server"
import { getAuthConfigProvider } from "@convex-dev/better-auth/auth-config"
export default { providers: [getAuthConfigProvider()],} satisfies AuthConfigimport type { GenericActionCtx } from "convex/server"
import { createBetterAuthAdapter } from "@vexcms/better-auth"import { betterAuth } from "better-auth"
import type { DataModel } from "../_generated/dataModel"
import { authOptions } from "./options"
export const createAuth = (ctx: GenericActionCtx<DataModel>, { optionsOnly } = { optionsOnly: false }) => { return betterAuth({ database: createBetterAuthAdapter(ctx), logger: { disabled: optionsOnly, }, ...authOptions, })}import type { BetterAuthOptions } from "better-auth"
import { anonRoleDatabaseHook } from "@vexcms/better-auth"
import { AUTH_COOKIE_PREFIX, USER_ROLES } from "~/db/constants"
import { createPlugins } from "./plugins"import { authSchema } from "./schema"
// `plugins` on the shared schema is a descriptor map for// `betterAuthCollections`, not Better Auth plugin instances — dropped by name// so the intent survives a reordering of the object literal below.const { plugins: _pluginDescriptors, ...schemaOptions } = authSchema
/** * Better Auth options for this project. * * Model names and `user.additionalFields` come from `./schema`, the one module * both this file and `src/vex.config.ts` read, so a field added there reaches * the database and the admin panel without being written twice. Everything * below the spread is server-only. * * @see ./schema for the shared, client-safe half */export const authOptions: BetterAuthOptions = { ...schemaOptions, // Unique per app so another Better Auth app on localhost cannot share or // shadow this session cookie — see AUTH_COOKIE_PREFIX. advanced: { cookiePrefix: AUTH_COOKIE_PREFIX }, baseURL: process.env.SITE_URL, databaseHooks: { // Ties Better Auth's anonymous-plugin users to `access.anonRole` (see // `~/auth/access.ts`) by stamping the same role explicitly, rather than // relying solely on `roles`' `defaultValue` below — which every new user // gets regardless of `isAnonymous`, anon-plugin or not. user: anonRoleDatabaseHook(USER_ROLES.user), }, emailAndPassword: { enabled: true }, plugins: createPlugins(), secret: process.env.BETTER_AUTH_SECRET, trustedOrigins: [process.env.SITE_URL!],}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 BetterAuthSchemaInputimport 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, organization: true, },} satisfies BetterAuthSchemaInputimport { apiKey } from "@better-auth/api-key"import { convex } from "@convex-dev/better-auth/plugins"import authConfig from "@convex/auth.config"import { nextCookies } from "better-auth/next-js"import { admin, anonymous } from "better-auth/plugins"
import { USER_ROLES } from "~/db/constants"
/** * Returns a fresh array of Better Auth plugins for each VexCMS auth session. */export const createPlugins = () => [ admin({ adminRoles: [USER_ROLES.admin], defaultRole: USER_ROLES.user, }), anonymous(), apiKey(), convex({ authConfig }), // this plugin must be last, per the convex dev CLI's own warnings nextCookies(),]import { apiKey } from "@better-auth/api-key"import { convex } from "@convex-dev/better-auth/plugins"import authConfig from "@convex/auth.config"import { nextCookies } from "better-auth/next-js"import { admin, anonymous } from "better-auth/plugins"import { organization } from "better-auth/plugins"
import { USER_ROLES } from "~/db/constants"
/** * Returns a fresh array of Better Auth plugins for each VexCMS auth session. */export const createPlugins = () => [ admin({ adminRoles: [USER_ROLES.admin], defaultRole: USER_ROLES.user, }), anonymous(), apiKey(), convex({ authConfig }), organization(), // this plugin must be last, per the convex dev CLI's own warnings nextCookies(),]import { internalMutation, internalQuery } from "@convex/_generated/server"import { authDbApi } from "@vexcms/better-auth"
import schema from "../schema"
/** * Convex internal mutations and queries that implement Better Auth's DB interface. * * Wire these into your Convex schema so `@vexcms/better-auth` can call them * via `ctx.runMutation(anyApi.auth.db.dbCreate, ...)`: * * ```ts * // convex/schema.ts * import { dbCreate, dbFindOne, ... } from "./auth/db"; * * // register as internal (visibility: internal) in your schema tables: * export default defineSchema({ * users: defineTable(...).index("by_email", ["email"]), * sessions: defineTable(...).index("by_token", ["token"]), * }, { * internal: { * dbCreate, * dbFindOne, * dbFindMany, * dbCount, * dbUpdate, * dbUpdateMany, * dbDelete, * dbDeleteMany, * }, * }); * ``` * * @see {@link authDbApi} for the factory that produces these functions */export const { dbCreate, dbFindOne, dbFindMany, dbCount, dbUpdate, dbUpdateMany, dbDelete, dbDeleteMany,} = authDbApi({ schema, internalQuery, internalMutation })import { get } from "@vexcms/core/server";
import { type SessionID, TABLE_SLUG_SESSIONS, TABLE_SLUG_USERS, type UserID } from "~/db/constants";import config from "~/vex.config.server";
import { query } from "../_generated/server";
export const identifyCurrentUser = query({ args: {}, handler: async (ctx) => { return ctx.auth.getUserIdentity(); },});
export const getUserOrg = query({ args: {}, handler: async (ctx) => { const empty = { user: null, organization: undefined }; const identity = await ctx.auth.getUserIdentity(); if (!identity) { return empty; } const session = await get({ ctx, config, id: identity.sessionId as SessionID, collection: TABLE_SLUG_SESSIONS, access: { bypass: true }, }); if (!session) { return empty; } const user = await get({ ctx, config, id: identity.subject as UserID, collection: TABLE_SLUG_USERS, access: { bypass: true }, }); if (!user) { return empty; } return { user, organization: undefined }; },});import { get } from "@vexcms/core/server";import { v } from "convex/values";
import { type OrganizationID, type SessionID, TABLE_SLUG_ORGANIZATIONS, TABLE_SLUG_SESSIONS, TABLE_SLUG_USERS, type UserID,} from "~/db/constants";import config from "~/vex.config.server";
import { query } from "../_generated/server";
export const identifyCurrentUser = query({ args: {}, handler: async (ctx) => { return ctx.auth.getUserIdentity(); },});
export const getUserOrg = query({ args: { noOrgs: v.optional(v.boolean()), }, handler: async (ctx, args) => { const empty = { user: null, organization: undefined }; const identity = await ctx.auth.getUserIdentity(); if (!identity) { return empty; } const session = await get({ ctx, config, id: identity.sessionId as SessionID, collection: TABLE_SLUG_SESSIONS, access: { bypass: true }, }); if (!session) { return empty; } const user = await get({ ctx, config, id: identity.subject as UserID, collection: TABLE_SLUG_USERS, access: { bypass: true }, }); if (!user) { return empty; } if (!session.activeOrganizationId || args.noOrgs) { return { user, organization: undefined }; } const organization = await get({ ctx, config, id: session.activeOrganizationId as OrganizationID, collection: TABLE_SLUG_ORGANIZATIONS, access: { bypass: true }, }); return { user, organization: organization ?? undefined }; },});import { v } from "convex/values"
import { TABLE_SLUG_SESSIONS, TABLE_SLUG_USERS } from "~/db/constants"import { find, get, normalizeId } from "~/vexcms/api"
import { query } from "../_generated/server"
/** * Get session with user data by session token * Used for server-side authentication in Next.js */export const getSessionWithUser = query({ args: { sessionToken: v.string(), }, handler: async (ctx, args) => { const [session] = await find({ ctx, collection: TABLE_SLUG_SESSIONS, withIndex: { name: "by_token", range: (q) => q.eq("token", args.sessionToken) }, limit: 1, access: { bypass: true }, })
if (!session) {return null}
if (session.expiresAt < Date.now()) { console.error("[getSessionWithUser] Session Expired") return null }
const userId = normalizeId({ ctx, collection: TABLE_SLUG_USERS, id: session.userId ?? "" }) if (!userId) {return null}
const user = await get({ ctx, collection: TABLE_SLUG_USERS, id: userId, access: { bypass: true } }) if (!user) {return null}
return { session: { id: session._id, expiresAt: session.expiresAt, ipAddress: session.ipAddress, token: session.token, userAgent: session.userAgent, userId: session.userId, }, user: { id: user.userId ?? user._id, name: user.name, email: user.email, emailVerified: user.emailVerified, image: user.image, roles: user.roles, }, } },})Better Auth answers on /api/auth/ over Convex HTTP. If your app has no convex/http.ts, add this
one. If it has one, add the createAuth import and the two http.route calls to it:
import { httpRouter } from "convex/server"
import { httpAction } from "./_generated/server"import { createAuth } from "./auth"
const http = httpRouter()
// Auth request handler - basePath hardcoded to /api/auth for nowconst authRequestHandler = httpAction(async (ctx, request) => { // eslint-disable-next-line @typescript-eslint/no-unsafe-argument const auth = createAuth(ctx) return await auth.handler(request)})
// Register auth routes for GET and POSThttp.route({ handler: authRequestHandler, method: "GET", pathPrefix: "/api/auth/",})
http.route({ handler: authRequestHandler, method: "POST", pathPrefix: "/api/auth/",})
export default httpConvex schema
Section titled “Convex schema”vex dev writes the tables VexCMS generates to convex/vex.schema.ts and adds them to
convex/schema.ts for you. It adds imports and new entries only, and never changes a table you
wrote yourself.
You add the tables VexCMS doesn’t generate in every configuration: vex_globals, organization,
team, teamMember, member, invitation, and the account table. Copy those defineTable
entries from a new project’s convex/schema.ts into the defineSchema({ ... }) of yours, next
to your own tables. Also copy the defineTable, v and TABLE_SLUG_ACCOUNTS imports. The rest
of this file, the entries imported from ./vex.schema, is what vex dev adds:
import { defineSchema, defineTable } from "convex/server"import { v } from "convex/values"
import { TABLE_SLUG_ACCOUNTS } from "~/db/constants"
import { apikey, images, jwks, posts, // Example: posts session, user, verification, vex_versions, vex_views,} from "./vex.schema"
export default defineSchema({ vex_versions, vex_views, user, // `organization`/`team`/`teamMember`/`member`/`invitation`/`vex_globals` are // hand-written, not imported from `./vex.schema` — the generator only emits // them when the `organization()` plugin (`--orgs`) or a registered global is // actually present in `vex.config.ts`. `access.ts` and every `getAuth` // caller (`convex/vex.ts`, `convex/vex/media.ts`, `convex/vex/globals.ts`) // reference `orgCollectionSlug`/`resolveOrgs: true` unconditionally, so // these tables must exist in the schema from day one — enabling `--orgs` // or registering a global later needs no schema migration. vex_globals: defineTable({ slug: v.string(), data: v.any(), }).index("by_slug", ["slug"]), images, posts, // Example: posts team: defineTable({ name: v.string(), organizationId: v.string(), createdAt: v.number(), updatedAt: v.optional(v.number()), }).index("by_organizationId", ["organizationId"]), teamMember: defineTable({ teamId: v.string(), userId: v.string(), createdAt: v.optional(v.number()), }) .index("by_teamId", ["teamId"]) .index("by_userId", ["userId"]), organization: defineTable({ name: v.string(), slug: v.string(), logo: v.optional(v.string()), createdAt: v.number(), metadata: v.optional(v.string()), }).index("by_slug", ["slug"]), member: defineTable({ organizationId: v.string(), userId: v.string(), role: v.string(), createdAt: v.number(), }) .index("by_organizationId", ["organizationId"]) .index("by_userId", ["userId"]), invitation: defineTable({ organizationId: v.string(), email: v.string(), role: v.optional(v.string()), teamId: v.optional(v.string()), status: v.string(), expiresAt: v.number(), createdAt: v.number(), inviterId: v.string(), roles: v.array(v.string()), }) .index("by_organizationId", ["organizationId"]) .index("by_email", ["email"]), session, verification, apikey, jwks,
[TABLE_SLUG_ACCOUNTS]: defineTable({ accessToken: v.optional(v.string()), accessTokenExpiresAt: v.optional(v.number()), accountId: v.string(), createdAt: v.number(), idToken: v.optional(v.string()), password: v.optional(v.string()), providerId: v.string(), refreshToken: v.optional(v.string()), refreshTokenExpiresAt: v.optional(v.number()), scope: v.optional(v.string()), updatedAt: v.number(), userId: v.string(), }) .index("by_userId", ["userId"]) .index("by_accountId", ["accountId"]),})VexCMS config
Section titled “VexCMS config”vex.config.ts is the client-safe config that both the admin and your site import.
vex.config.server.ts adds the Better Auth adapter and Convex file storage. src/vexcms/ holds
the collections: users describes Better Auth’s user table, images is the media collection,
and posts is an example you can delete (remove it from collections in vex.config.ts too).
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 vexConfigimport { 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"server only"
import { type DataModel } from "@convex/_generated/dataModel"import { createGetAuth } from "@vexcms/better-auth"import { vexServerApi } from "@vexcms/core/server"
import { TABLE_SLUG_SESSIONS, TABLE_SLUG_USERS } from "~/db/constants"import config from "~/vex.config.server"
/** * Bound server API — `config`/`getAuth` are threaded once here so any * `convex/*.ts` function can import `find`/`get`/`create`/etc. directly * instead of repeating the wiring in every file. * * Mirrors `apps/test/src/vexcms/api.ts`'s `vexServerApi` binding. */export const { get, find, search, create, remove, replace, system, update, globals, normalizeId, publishedSlugs } = vexServerApi<DataModel>({ config, getAuth: createGetAuth({ userCollectionSlug: TABLE_SLUG_USERS, sessionCollectionSlug: TABLE_SLUG_SESSIONS, resolveOrgs: false, }), })"server only"
import { type DataModel } from "@convex/_generated/dataModel"import { createGetAuth } from "@vexcms/better-auth"import { vexServerApi } from "@vexcms/core/server"
import { TABLE_SLUG_ORGANIZATIONS, TABLE_SLUG_SESSIONS, TABLE_SLUG_USERS } from "~/db/constants"import config from "~/vex.config.server"
/** * Bound server API — `config`/`getAuth` are threaded once here so any * `convex/*.ts` function can import `find`/`get`/`create`/etc. directly * instead of repeating the wiring in every file. * * Mirrors `apps/test/src/vexcms/api.ts`'s `vexServerApi` binding. */export const { get, find, search, create, remove, replace, system, update, globals, normalizeId, publishedSlugs } = vexServerApi<DataModel>({ config, getAuth: createGetAuth({ orgCollectionSlug: TABLE_SLUG_ORGANIZATIONS, userCollectionSlug: TABLE_SLUG_USERS, sessionCollectionSlug: TABLE_SLUG_SESSIONS, resolveOrgs: true, }), })export * from "./images"export * from "./posts" // Example: postsexport * from "./users"import { defineCollection, text } from "@vexcms/core"
import { TABLE_SLUG_USERS } from "~/db/constants"
export const users = defineCollection({ slug: TABLE_SLUG_USERS, admin: { useAsTitle: "name", icon: "Users", }, labels: { singular: "User", plural: "Users", }, fields: { name: text({ label: "Name", required: true }), // Add custom user fields here — the auth adapter already contributes // name/email/roles/etc. from Better Auth's schema. },})import { defineMediaCollection } from "@vexcms/file-storage-convex/client";
import { TABLE_SLUG_IMAGES } from "~/db/constants";
export const images = defineMediaCollection({ slug: TABLE_SLUG_IMAGES, admin: { icon: "Image", }, labels: { singular: "Image", plural: "Images", }, interfaceName: "Image",});import type { DataModel } from "@convex/_generated/dataModel"
import { array, beforeChangeHook, checkbox, date, defineCollection, group, relationship, richtext, text, textarea, upload, url,} from "@vexcms/core"import { assertUniqueAmongPublished } from "@vexcms/core/server"
import { TABLE_SLUG_IMAGES, TABLE_SLUG_POSTS, TABLE_SLUG_USERS } from "~/db/constants"
/** * Example collection: a blog post that uses most collection and field options * once. Copy what you need into your own collections, then delete this one. * * To remove it, delete this file and every line marked `Example: posts`: * - `./index.ts` (the `export * from "./posts"` line) * - `src/vex.config.ts` (the `posts` import and its `collections` entry) * - `src/auth/access.ts` (the `posts` import, resource, and each role's `posts` block) * - `convex/schema.ts` (the `posts` import and table) * then run `vex dev` to regenerate the schema. `TABLE_SLUG_POSTS` and * `@vexcms/richtext-plate` can stay or go; nothing else depends on them. * * Who may do what with posts lives in `src/auth/access.ts`, not here. */export const posts = defineCollection({ slug: TABLE_SLUG_POSTS, // Name of the generated TypeScript type in `src/vex.types.ts`. interfaceName: "Post", labels: { singular: "Post", plural: "Posts" }, admin: { // The field shown as the document's title in lists, breadcrumbs and pickers. useAsTitle: "title", // Any lucide-react icon name. icon: "FilePen", view: { // List columns, in order. Fields not named here can still be shown from the column menu. columns: ["title", "slug", "author", "publishedAt", "featured"], // Default sort. A sortable field must lead an index (`publishedAt` declares one below). sort: { field: "publishedAt", order: "desc" }, // Fields the list search bar queries. Each needs its own `searchIndex`. searchFields: ["title", "slug"], }, }, // Drafts: edits save as a draft until someone with `publish` access publishes them. // Every save is also kept as a version you can restore. versions: { drafts: true, autosave: { enabled: true }, }, hooks: { // Runs on the server before every save (create, draft save, publish), before // validation. Return the document to write. Here: when `author` is empty, // set it to whoever is saving. `beforeChangeHook` types `ctx` against this // project's `DataModel`; an inline `beforeChange: async ({ doc }) => doc` works too. // // `vex` is the same read-only API a field's `validate()` and a live-preview // resolver receive — it reads another collection (here, `users`) without the // import-cycle a bound `~/vexcms/api` import would create from inside a // collection file, and without reaching into `ctx.db` directly (P-031). // `access: { bypass: true }` is needed here: the signed-in author has no // `read` access on `users` by default (`~/auth/access.ts`), only on their // own row through other rules, and this lookup is by `email`, not by id. beforeChange: beforeChangeHook<typeof TABLE_SLUG_POSTS, DataModel>( TABLE_SLUG_POSTS, async ({ doc, ctx, vex }) => { if (doc.author?.length) { return doc } const email = (await ctx.auth.getUserIdentity())?.email if (!email) { return doc } const author = await vex.find({ collection: TABLE_SLUG_USERS, withIndex: { name: "by_email", range: (q) => q.eq("email", email) }, unique: true, access: { bypass: true }, }) return author ? { ...doc, author: [author._id] } : doc }, ), }, fields: { title: text({ label: "Title", required: true, searchIndex: { name: "search_posts_title", filterFields: [] }, }), slug: text<typeof TABLE_SLUG_POSTS>({ label: "Slug", required: true, description: "URL path, e.g. hello-world. Unique among published posts.", index: "by_slug", searchIndex: { name: "search_posts_slug", filterFields: [] }, // There is no `unique: true`; uniqueness is a server-side check in `validate`. validate: async ({ value, doc, vex }) => { await assertUniqueAmongPublished({ vex, collection: TABLE_SLUG_POSTS, indexName: "by_slug", field: "slug", value, excludeId: doc._id, }) }, }), // Relationship to the Better Auth `user` collection. Set by the hook above when // empty; editors cannot change it afterwards (field-level rule in `access.ts`). author: relationship({ label: "Author", collection: { slug: TABLE_SLUG_USERS }, admin: { position: "sidebar" }, }), publishedAt: date({ label: "Published At", index: "by_publishedAt", admin: { position: "sidebar", enableSorting: true }, }), // Upload to the `images` media collection. cover: upload({ label: "Cover Image", to: TABLE_SLUG_IMAGES, admin: { position: "sidebar" }, }), featured: checkbox({ label: "Featured", admin: { position: "sidebar" }, }), // Conditional field: shown (and validated) only while `featured` is checked. // Hiding it does not clear it: a value saved earlier stays stored, so read // `featuredUntil` only when `featured` is true. featuredUntil: date({ label: "Featured Until", admin: { position: "sidebar", condition: ({ siblingData }) => siblingData.featured === true, }, }), excerpt: textarea({ label: "Excerpt", description: "One or two sentences for post lists and link previews.", }), // Rich text, edited with the Plate editor registered as `editor` in `src/vex.config.ts`. // `mediaCollectionSlug` enables inline images from that media collection. body: richtext({ label: "Body", mediaCollectionSlug: TABLE_SLUG_IMAGES, }), // Group: nested fields stored as one object (`seo.title`, `seo.description`). seo: group({ label: "SEO", fields: { title: text({ label: "Meta Title" }), description: textarea({ label: "Meta Description" }), }, }), // Array: a repeatable list; each item here is a group of two fields. sources: array({ label: "Sources", items: group({ label: "Source", fields: { label: text({ label: "Label", required: true }), url: url({ label: "URL", required: true }), }, }), }), },})Without a src/ folder, also set types: { outputPath: "/vex.types.ts" } in vex.config.ts.
Otherwise vex dev creates a src/ folder that holds only the generated types.
Convex functions
Section titled “Convex functions”The queries and mutations the admin panel calls. firstUser.ts makes the first account an
admin.
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,});import { createGetAuth } from "@vexcms/better-auth";import { collectionsApi, createVexMutations } from "@vexcms/core/server";
import { TABLE_SLUG_ORGANIZATIONS, 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({ orgCollectionSlug: TABLE_SLUG_ORGANIZATIONS, userCollectionSlug: TABLE_SLUG_USERS, sessionCollectionSlug: TABLE_SLUG_SESSIONS, resolveOrgs: true,});
export const { find, get, search, create, update, remove, livePreviewUrl, listViews, saveView, removeView,} = collectionsApi({ config, query, mutation: vexMutation, getAuth,});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 } },})import { createGetAuth } from "@vexcms/better-auth";import { globalsApi } from "@vexcms/core/server";
import { TABLE_SLUG_SESSIONS, TABLE_SLUG_USERS } from "~/db/constants";import config from "~/vex.config.server";
import { query } from "../_generated/server";import { vexMutation as mutation } from "../vex";
export const { get, find, upsert } = globalsApi({ config, query, mutation, getAuth: createGetAuth({ userCollectionSlug: TABLE_SLUG_USERS, sessionCollectionSlug: TABLE_SLUG_SESSIONS, resolveOrgs: false, }),});import { createGetAuth } from "@vexcms/better-auth";import { globalsApi } from "@vexcms/core/server";
import { TABLE_SLUG_ORGANIZATIONS, TABLE_SLUG_SESSIONS, TABLE_SLUG_USERS } from "~/db/constants";import config from "~/vex.config.server";
import { query } from "../_generated/server";import { vexMutation as mutation } from "../vex";
export const { get, find, upsert } = globalsApi({ config, query, mutation, getAuth: createGetAuth({ orgCollectionSlug: TABLE_SLUG_ORGANIZATIONS, userCollectionSlug: TABLE_SLUG_USERS, sessionCollectionSlug: TABLE_SLUG_SESSIONS, resolveOrgs: true, }),});import { createGetAuth } from "@vexcms/better-auth";import { mediaApi } from "@vexcms/core";
import { TABLE_SLUG_SESSIONS, TABLE_SLUG_USERS } from "~/db/constants";import config from "~/vex.config.server";
import { query } from "../_generated/server";import { vexMutation as mutation } from "../vex";
export const { getUrl, generateUploadUrl, createMediaDocument, deleteMedia } = mediaApi({ config, query, mutation, getAuth: createGetAuth({ userCollectionSlug: TABLE_SLUG_USERS, sessionCollectionSlug: TABLE_SLUG_SESSIONS, resolveOrgs: false, }),});import { createGetAuth } from "@vexcms/better-auth";import { mediaApi } from "@vexcms/core";
import { TABLE_SLUG_ORGANIZATIONS, TABLE_SLUG_SESSIONS, TABLE_SLUG_USERS } from "~/db/constants";import config from "~/vex.config.server";
import { query } from "../_generated/server";import { vexMutation as mutation } from "../vex";
export const { getUrl, generateUploadUrl, createMediaDocument, deleteMedia } = mediaApi({ config, query, mutation, getAuth: createGetAuth({ orgCollectionSlug: TABLE_SLUG_ORGANIZATIONS, userCollectionSlug: TABLE_SLUG_USERS, sessionCollectionSlug: TABLE_SLUG_SESSIONS, resolveOrgs: true, }),});import { versionsApi } from "@vexcms/core/server"
import config from "~/vex.config.server"
import { query } from "../_generated/server"import { getAuth, vexMutation as mutation } from "../vex"
export const { saveDraft, publish, unpublish, listVersions, getVersionSnapshot, deleteVersion } = versionsApi({ config, query, mutation, getAuth, })Next.js auth
Section titled “Next.js auth”The Better Auth client and server helpers, the /api/auth/* route that forwards to Convex, and
the sign-in and sign-up pages at /auth/sign-in and /auth/sign-up.
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-functionauthClient.$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> )}import { cache } from "react"
import { convexBetterAuthNextJs } from "@convex-dev/better-auth/nextjs"import type { VexApiAuth } from "@vexcms/core"
import { api } from "@convex/_generated/api"import { AUTH_COOKIE_PREFIX } from "~/db/constants"import { env } from "~/env.mjs"
/** * Whether a caught query error looks like it was rejected for a stale/invalid * token specifically — used only to decide whether `jwtCache` (below) should * force a real token refresh and retry once, never to classify errors for * any other purpose. */function isAuthTokenError(error: unknown): boolean { const message = error instanceof Error ? error.message : String(error) return /unauthenticated|not authenticated|invalid token|expired/i.test(message)}
export const { fetchAuthAction, fetchAuthMutation, fetchAuthQuery, getToken: getTokenUncached, handler, isAuthenticated, preloadAuthQuery,} = convexBetterAuthNextJs({ convexSiteUrl: env.NEXT_PUBLIC_CONVEX_SITE_URL, convexUrl: env.NEXT_PUBLIC_CONVEX_URL, // `getToken`'s own jwtCache path reads `opts.cookiePrefix` (a TOP-LEVEL // option, not nested under `jwtCache`) to find this app's own // `<prefix>.convex_jwt` cookie at all — without it, it looks for a // bare/`__Secure-` `convex_jwt` cookie that never exists here, so every // call would silently fall through to the network path despite // `jwtCache.enabled: true`. cookiePrefix: AUTH_COOKIE_PREFIX, // Trust a locally-decoded, non-expired JWT cookie instead of hitting // `/api/auth/convex/token` on every request — the single largest hop in // the admin panel's own reload waterfall. Keeps the library's own default // (short) JWT lifetime, not extended here. // // Tradeoff: an SSR permission change (a role edit, a ban, a revoked // session) can lag by up to the JWT's own lifetime before THIS cache // notices — the stale local decode is trusted until it expires or a query // call fails with what `isAuthTokenError` recognizes as an auth error, // which forces one real refresh+retry. This is a UX/latency tradeoff // only, not a security hole: Convex re-checks `hasPermission` against the // TOKEN'S OWN claims on every single query regardless of this cache, so a // revoked/stale token can still only ever read/write what its own // (possibly stale) claims allow — never more. jwtCache: { enabled: true, isAuthError: isAuthTokenError, },})
/** * Memoized per request (React `cache()`). `layout.tsx`, `page.tsx`, and * `AuthServerProvider` each independently need the session token — before * this, each called the uncached version, so one admin page load cost 2-3 * real cookie-verify round trips for identical data. `cache()` collapses * every call within one render pass into the FIRST one's promise; the rest * await it for free. */export const getToken = cache(getTokenUncached)
/** * Memoized per request (React `cache()`), for the same reason as `getToken` * above: `layout.tsx`, `page.tsx`, and `AuthServerProvider` each * independently fetched `{ user, organization }` via `getUserOrg` — 3 real * Convex round trips for identical data on one admin page load. Safe to call * unconditionally regardless of whether a session exists: an unauthenticated * caller resolves to `{ user: null, organization: undefined }`, never throws * (see `convex/auth/api.ts`'s own `getUserOrg` handler). */export const getUserOrg = cache(() => fetchAuthQuery(api.auth.api.getUserOrg, {}))
/** * `getUserOrg()`'s `user`/`organization`, widened to * `Record<string, unknown>` for callers that only need `VexApiAuth` (RBAC * checks, `NextAdminPage`'s `authPromise`, the revalidate route) — never * the concrete generated user/organization document shapes * `AuthServerProvider`'s `AuthProvider` needs. * * The cast is the documented bridge for a GENERIC-field-access consumer * (`VexApiAuth.user`'s own doc comment: "shape is caller-defined") reading * a generated document that is now deliberately closed (no index * signature) — see `VexDocumentShape` in `@vexcms/core`. */export async function getUserOrgForVexApi(): Promise<VexApiAuth> { const result = await getUserOrg() return { ...result, user: result.user as Record<string, unknown> | null, organization: result.organization as Record<string, unknown> | undefined, }}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), }, }, }, },})import { defineAccess } from "@vexcms/core"
import { TABLE_SLUG_ORGANIZATIONS, 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, orgCollectionSlug: TABLE_SLUG_ORGANIZATIONS, 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), }, }, }, },})"use client"
import type { ReactNode } from "react"
import { AuthUIProvider } from "@daveyplate/better-auth-ui"import Link from "next/link"
import { authClient } from "~/auth/client"
/** * Mounts `@daveyplate/better-auth-ui`'s `AuthUIProvider` around `AuthView` * only, at the two places it renders (`(frontend)/auth/[pathname]/view.tsx`, * the `@auth` intercepted sign-in modal) — not at the app root. `AuthView` * reads its form config (credentials, navigation) from this provider's context; * nothing else in the app needs it. * * `navigate`/`replace` hard-navigate (`window.location.href`/`.replace`, a full * document load) instead of `router.push`/`router.replace`. The library's own * `useOnSuccessTransition` (driving sign-in/sign-up success, among other auth * transitions) does `await refetchSession(); await onSessionChange?.(); * navigate(redirectTo)` — `onSessionChange` used to be `() => router.refresh()`, * a fire-and-forget call with no real promise to await (`router.refresh()` * returns `void`), so `navigate(redirectTo)` (`router.push`) fired immediately * after, while the refresh's own RSC re-fetch for the PRE-navigation route was * still in flight. When that refresh resolved after the push had already * started (worse under a slow first compile), Next's router reconciled the * stale pre-navigation tree over the pushed route — "credentials accepted, the * app compiled for a while, then nothing happened," landing back on the * sign-in page despite a real session (confirmed signed in on back/forward). * A hard navigation has no client-side router state to race: there is nothing * left for a stale `refresh()` to clobber, and the full load re-resolves every * server-rendered auth state fresh — `onSessionChange` is dropped entirely, it * no longer does anything a hard navigation doesn't already cover. */export default function AuthViewProvider({ children }: { children: ReactNode }) { return ( <AuthUIProvider authClient={authClient} credentials={true} Link={Link} navigate={(href) => { window.location.href = href }} replace={(href) => { window.location.replace(href) }} > {children} </AuthUIProvider> )}import { handler } from "~/auth/server"
export const dynamic = "force-dynamic"export const runtime = "nodejs"
export const { GET, POST } = handlerimport type { Metadata } from "next"
import { resolveAuthPageTitle } from "~/lib/authPageTitle"
import AuthView from "./view"
export const dynamic = "force-dynamic"
export async function generateMetadata({ params,}: { params: Promise<{ pathname: string }>}): Promise<Metadata> { const { pathname } = await params return { title: `${resolveAuthPageTitle(pathname)} | VexCMS` }}
export default async function AuthPage({ params }: { params: Promise<{ pathname: string }> }) { const { pathname } = await params
return <AuthView pathname={pathname} />}import { AuthView } from "@daveyplate/better-auth-ui";
import AuthViewProvider from "~/auth/AuthViewProvider";import { resolveAuthPageTitle } from "~/lib/authPageTitle";
export default function AuthCard({ pathname }: { pathname: string }) { return ( <AuthViewProvider> <main className="absolute inset-0 grid place-items-center"> <h1 className="sr-only">{resolveAuthPageTitle(pathname)}</h1> <AuthView path={pathname} /> </main> </AuthViewProvider> );}Admin route
Section titled “Admin route”/admin checks the session and the adminPanel.access rule itself. It doesn’t rely on your
proxy or middleware. Signed-in users without access go to /unauthorized.
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("&")}` : ""}`;}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> </> )}"use client"
import { isVexConfigError, summarizeVexConfigError } from "@vexcms/core"import { buttonVariants, cn, VexConfigErrorBanner } from "@vexcms/react"import { useEffect } from "react"
/** * Error boundary for every route under `/admin`. A Vex config error that got past the page's own * `loadVexConfigModule` check shows `VexConfigErrorBanner`; anything else shows a retry button. A * production server error arrives here as a digest only, so it falls through to the retry. * * @param props.error - The thrown error; logged to the console. * @param props.reset - Re-renders the failed segment. */export default function AdminError({ error, reset,}: { error: Error & { digest?: string } reset: () => void}) { useEffect(() => { console.error(error) }, [error])
if (isVexConfigError(error)) { return ( <VexConfigErrorBanner error={summarizeVexConfigError({ error, includeDetail: process.env.NODE_ENV === "development" })} /> ) }
return ( <div className="flex min-h-[50vh] flex-col items-center justify-center gap-4 p-8 text-center"> <h1 className="text-2xl font-semibold">Something went wrong</h1> <p className="max-w-[32rem] text-muted-foreground">The admin panel hit an error while rendering.</p> <button className={cn(buttonVariants({ variant: "default" }))} onClick={reset} type="button"> Try again </button> </div> )}import { UnauthorizedView } from "@vexcms/react";import Link from "next/link";
export const metadata = { title: "Access denied",};
/** * Landing page for callers who are signed in but fail the `adminPanel.access` * check in the access matrix. * * Deliberately lives OUTSIDE the `(vexcms)/admin` segment: that segment's layout * mounts the admin shell and redirects unauthorized callers here, so rendering * this inside it would loop. */export default function UnauthorizedPage() { return ( <UnauthorizedView> <Link className="text-primary underline" href="/"> Return to site </Link> </UnauthorizedView> );}Providers and styles
Section titled “Providers and styles”These providers wrap every page. ClientProviders holds the Convex client, Better Auth and the
VexCMS config. ServerProviders holds the theme and URL-state adapter.
"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> )}import { ThemeProvider } from "@vexcms/react";import { NuqsAdapter } from "nuqs/adapters/next/app";import { type PropsWithChildren } from "react";
/** * Server-side provider shell: theme context + the nuqs URL-state adapter. * * `AuthServerProvider` used to wrap `NuqsAdapter` here, putting a `getToken()` * cookie read on every route's render path. It now mounts directly in * `app/(vexcms)/admin/layout.tsx`, the only route group that needs it. * * Deliberately does **not** mount `ConvexClientProvider` — `ClientProviders` * renders it, and `ClientProviders` is nested inside this component, so its * copy is the one that actually reaches `children`. Mounting it here as well * built a second `ConvexReactClient` + `QueryClient` pair on every server * render (`providers/convex.tsx` intentionally creates fresh clients per call * server-side to avoid cross-request leaks) whose only consumer was the * discarded outer subtree. */export default function ServerProviders({ children }: PropsWithChildren) { return ( <ThemeProvider defaultTheme="system"> <NuqsAdapter>{children}</NuqsAdapter> </ThemeProvider> );}"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;}Wrap your root layout’s children in both, and add suppressHydrationWarning to <html> (the
theme sets a class on it before React loads):
import ClientProviders from "~/components/providers/client"import ServerProviders from "~/components/providers/server"
// ...your imports, fonts and metadata
export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="en" suppressHydrationWarning> <body> <ServerProviders> <ClientProviders>{children}</ClientProviders> </ServerProviders> </body> </html> )}This is the root layout of a new project, for reference. It also mounts the optional pieces below:
import type { Metadata } from "next"
import "./globals.css"
import { loadVexConfigModule } from "@vexcms/core"import { LivePreviewProvider, VexConfigErrorBanner } from "@vexcms/react"import { GeistMono } from "geist/font/mono"import { GeistSans } from "geist/font/sans"
import ClientProviders from "~/components/providers/client"import ServerProviders from "~/components/providers/server"import { ThemeScript } from "~/components/ThemeScript"import { ScrollRestoreScript } from "~/components/ScrollRestoreScript"
/* * Fonts come from the `geist` package's own `next/font/local` exports rather than * `next/font/google` (Google Fonts intermittently serves extensionless URLs that break * Turbopack builds, vercel/next.js#99114) and rather than a hand-written * `../../node_modules/geist/...` path, which breaks when an npm, yarn or bun workspace hoists * `geist` to the workspace root. `globals.css` maps `--font-sans` to `--font-geist-sans`. */
export const metadata: Metadata = { description: "Built with VexCMS", icons: { icon: "/favicons/favicon.ico" }, title: "VexCMS",}
/** * Root layout. Loads `~/vex.config` through `loadVexConfigModule` before mounting the client * providers: the config throws while its module evaluates, so a static import would take the * whole app down before any error boundary exists. When it fails, the body is the server-rendered * `VexConfigErrorBanner` instead (message in development only), and the providers that would * import the broken module never mount. * * Development only, and the production build strips it: importing the config into this server * component makes Next ship every `"use client"` module the config reaches (the rich-text * editor among them) to every route. A config that always throws already fails `next build`; * one that throws only at runtime falls to `global-error.tsx`. */export default async function RootLayout({ auth, children,}: Readonly<{ auth: React.ReactNode children: React.ReactNode}>) { const clientConfig = process.env.NODE_ENV === "development" ? await loadVexConfigModule({ load: () => import("~/vex.config") }) : undefined return ( <html className={`${GeistSans.variable} ${GeistMono.variable} antialiased`} lang="en" suppressHydrationWarning> <head> {/* Applies the persisted light/dark class before first paint — without it the admin flashes light before the saved mode lands. */} <ThemeScript /> {/* Restores the edit view's form scroll position before first paint on a hard reload. */} <ScrollRestoreScript /> </head> <body> {clientConfig?.status === "invalid" ? ( <VexConfigErrorBanner className="min-h-svh" error={clientConfig.error} /> ) : ( <ServerProviders> <ClientProviders> {/* Wraps the whole app: the overlay only reaches consumers inside the provider. It reads collections, globals and allowed origins from `VexConfigContext`, and gates itself on the session-verified cookie plus `?vexLivePreview=1` (or the preview window name it writes on first activation), so every public route stays prerenderable. Inert until a collection or global sets `admin.livePreview.url`. */} <LivePreviewProvider> {children} {/* `@auth` parallel slot (`app/@auth/`), sibling of this layout — covers both `(frontend)` and `(vexcms)` since both groups share this root. Rendered after `children` so the intercepted `/auth/[pathname]` dialog/full-screen card portals/paints over whichever page (site or admin) triggered it. */} {auth} </LivePreviewProvider> </ClientProviders> </ServerProviders> )} </body> </html> )}The admin’s components read shadcn-style theme variables (--primary, --card, …). Your global
CSS file needs the four imports at the top and the variables themselves. The VexCMS stylesheets
tell Tailwind where their own classes are, wherever the packages are installed, so no @source
line is needed. If your app already defines shadcn variables, keep yours: the admin uses them.
Otherwise copy the @custom-variant, @theme inline, :root, .dark and @layer base blocks
below. The --font-sans line in :root points at the Geist font the reference layout loads
(geist/font/sans and geist/font/mono). To use it, install the geist package and add
GeistSans.variable and GeistMono.variable to your <html> class. Otherwise leave the line
out to keep your own font.
/* ============================================================================ VexCMS · globals.css — Stark × Ember (shadcn-faithful translation) ---------------------------------------------------------------------------- Source of design intent: .agent/docs/design/claude-design/admin.css (Claude Design export). That file uses bespoke tokens (--page, --fg-muted, --line-bold, --accent / --accent-tint / --accent-ink, …); this file translates them into shadcn-named tokens so every React component in @vexcms/react keeps working with no per-component overrides.
Read .agent/docs/design/claude-design/README.md before editing.
Key semantic decisions (different from naive shadcn): - Brand CTA → --primary (admin.css `--accent`) ember solid - Highlight → --accent (admin.css `--accent-tint`) ember tint - Ink/active → --accent-fg (admin.css `--accent-ink`) deep ember - Default surfaces (--card, --popover) = SAME tone (admin.css `--surface`) - --muted / --raised = third elevation level (admin.css `--raised`) used for table headers, modal foots, hover bgs, badge.muted.
All values are oklch. ============================================================================ */
@import "tailwindcss";@import "tw-animate-css";@import "shadcn/tailwind.css";@import "@vexcms/next/styles";
/* `@vexcms/next/styles` and `@vexcms/react/styles` each declare an `@source` for their own `dist`, relative to wherever the package is installed — this app's `node_modules` or a hoisted workspace root — so the admin's utilities are generated without listing the packages here. */@source not "../../public";
@utility focus-ring { outline: 2px solid var(--color-ring); outline-offset: 2px;}
@custom-variant dark (&:is(.dark *));
@theme inline { /* ── Surfaces ─────────────────────────────────────────────────────────── */ --color-background: var(--background); --color-foreground: var(--foreground); --color-card: var(--card); --color-card-foreground: var(--card-foreground); --color-popover: var(--popover); --color-popover-foreground: var(--popover-foreground);
/* ── Brand / accents ──────────────────────────────────────────────────── */ --color-primary: var(--primary); /* ember solid */ --color-primary-foreground: var(--primary-foreground); --color-secondary: var(--secondary); --color-secondary-foreground: var(--secondary-foreground); --color-accent: var(--accent); /* ember tint */ --color-accent-foreground: var(--accent-foreground); /* ember ink */
/* ── Neutral hover & muted ────────────────────────────────────────────── */ --color-muted: var(--muted); /* = --raised */ --color-muted-foreground: var(--muted-foreground);
/* ── Borders & inputs ─────────────────────────────────────────────────── */ --color-border: var(--border); /* default separators */ --color-input: var(--input); /* input borders */ --color-ring: var(--ring); /* solid ember focus */
/* ── Status ───────────────────────────────────────────────────────────── */ --color-destructive: var(--destructive); --color-destructive-foreground: var(--destructive-foreground);
/* ── Sidebar ──────────────────────────────────────────────────────────── */ --color-sidebar: var(--sidebar); --color-sidebar-foreground: var(--sidebar-foreground); --color-sidebar-primary: var(--sidebar-primary); --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); --color-sidebar-accent: var(--sidebar-accent); --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); --color-sidebar-border: var(--sidebar-border); --color-sidebar-ring: var(--sidebar-ring);
/* ── Charts ───────────────────────────────────────────────────────────── */ --color-chart-1: var(--chart-1); --color-chart-2: var(--chart-2); --color-chart-3: var(--chart-3); --color-chart-4: var(--chart-4); --color-chart-5: var(--chart-5);
/* ── Fonts ────────────────────────────────────────────────────────────── */ --font-sans: var(--font-sans); --font-mono: var(--font-geist-mono);
/* ── Radii — Vex is sharp ─────────────────────────────────────────────── */ --radius-sm: 2px; /* controls: buttons, inputs, menu items, type chips */ --radius-md: 4px; /* cards, popovers, table wraps */ --radius-lg: 8px; /* modals, dialogs */ --radius-xl: 12px; --radius-2xl: 16px; --radius-3xl: 20px; --radius-4xl: 9999px; /* pill badges & avatars */
/* ── Shadows ──────────────────────────────────────────────────────────── */ --shadow-xs: var(--shadow-xs-val); --shadow-sm: var(--shadow-sm-val); --shadow-md: var(--shadow-md-val); --shadow-lg: var(--shadow-lg-val); --shadow-pop: var(--shadow-pop-val);
/* ── Motion ───────────────────────────────────────────────────────────── */ --ease-emphasized: cubic-bezier(.2, .8, .2, 1);}
/* ──────────────────────────────────────────────────────────────────────────── LIGHT — Stark × Ember page #F5F5F5 · surface #FFFFFF · raised #FAFAFA · fg #0A0A0A ──────────────────────────────────────────────────────────────────────────── */:root { --font-sans: var(--font-geist-sans); /* Surfaces — three elevation levels */ --background: oklch(96.1% 0 0); /* #F5F5F5 */ --foreground: oklch(13.7% 0 0); /* #0A0A0A */ --card: oklch(100% 0 0); /* #FFFFFF */ --card-foreground: oklch(13.7% 0 0); --popover: oklch(100% 0 0); /* same as card */ --popover-foreground: oklch(13.7% 0 0);
/* Brand — ember on --primary */ --primary: oklch(60.5% 0.175 42); /* #E8622A */ --primary-foreground: oklch(100% 0 0);
/* Neutral secondary */ --secondary: oklch(98% 0 0); /* #FAFAFA */ --secondary-foreground: oklch(13.7% 0 0);
/* Highlight = ember TINT (matches admin.css --accent-tint) */ --accent: oklch(96% 0.025 42); /* #FEF0E8 */ --accent-foreground: oklch(52% 0.180 40); /* ember ink */
/* Neutral hover & muted (= admin.css --hover / --raised) */ --muted: oklch(98% 0 0); /* #FAFAFA = raised */ --muted-foreground: oklch(50.5% 0 0); /* #717171 */
/* Borders */ --border: oklch(85% 0 0); /* #D4D4D4 — default */ --input: oklch(54.6% 0 0); /* #6B6B6B — inputs */ --ring: oklch(60.5% 0.175 42); /* solid ember */
/* Status */ --destructive: oklch(57.7% 0.198 27); /* #DC2626 */ --destructive-foreground: oklch(98% 0 0);
/* Base radius — used by anything reading var(--radius) directly */ --radius: 4px;
/* Sidebar */ --sidebar: oklch(98% 0 0); /* #FAFAFA */ --sidebar-foreground: oklch(13.7% 0 0); --sidebar-primary: oklch(60.5% 0.175 42); /* ember */ --sidebar-primary-foreground: oklch(100% 0 0); --sidebar-accent: oklch(96.1% 0 0); --sidebar-accent-foreground: oklch(13.7% 0 0); --sidebar-border: oklch(85% 0 0); --sidebar-ring: oklch(60.5% 0.175 42);
/* Charts */ --chart-1: oklch(60.5% 0.175 42); --chart-2: oklch(45% 0 0); --chart-3: oklch(72% 0.100 60); --chart-4: oklch(60% 0.040 30); --chart-5: oklch(78% 0 0);
/* Shadows — soft elevation in light */ --shadow-xs-val: 0 1px 2px rgba(10, 10, 10, 0.04); --shadow-sm-val: 0 1px 3px rgba(10, 10, 10, 0.08); --shadow-md-val: 0 4px 12px rgba(10, 10, 10, 0.08); --shadow-lg-val: 0 12px 32px rgba(10, 10, 10, 0.12); --shadow-pop-val: 0 12px 28px rgba(10, 10, 10, 0.14), 0 1px 3px rgba(10, 10, 10, 0.06);}
/* ──────────────────────────────────────────────────────────────────────────── DARK — Stark × Ember dark page #0A0A0A · surface #141414 · raised #1E1E1E · fg #F4F4F4 Hotter ember (#F07040) for contrast. No flat shadows. ──────────────────────────────────────────────────────────────────────────── */.dark { /* Surfaces */ --background: oklch(13.7% 0 0); /* #0A0A0A */ --foreground: oklch(95% 0 0); /* #F4F4F4 */ --card: oklch(17.4% 0 0); /* #141414 */ --card-foreground: oklch(95% 0 0); --popover: oklch(17.4% 0 0); /* same as card */ --popover-foreground: oklch(95% 0 0);
/* Brand */ --primary: oklch(72% 0.175 50); /* #F07040 */ --primary-foreground: oklch(13.7% 0 0);
/* Secondary */ --secondary: oklch(20% 0 0); /* #1E1E1E */ --secondary-foreground: oklch(95% 0 0);
/* Highlight — translucent ember tint */ --accent: oklch(72% 0.175 50 / 0.12); --accent-foreground: oklch(72% 0.175 50); /* ember itself in dark */
/* Neutral hover & muted */ --muted: oklch(20% 0 0); /* = raised in dark */ --muted-foreground: oklch(70% 0 0); /* #A0A0A0 */
/* Borders */ --border: oklch(25% 0 0); /* #2A2A2A */ --input: oklch(40% 0 0); /* #5A5A5A */ --ring: oklch(72% 0.175 50);
/* Status */ --destructive: oklch(63% 0.210 27); /* #EF4444 */ --destructive-foreground: oklch(95% 0 0);
/* Sidebar */ --sidebar: oklch(7% 0 0); /* #050505 */ --sidebar-foreground: oklch(95% 0 0); --sidebar-primary: oklch(72% 0.175 50); --sidebar-primary-foreground: oklch(13.7% 0 0); --sidebar-accent: oklch(20% 0 0); --sidebar-accent-foreground: oklch(95% 0 0); --sidebar-border: oklch(25% 0 0); --sidebar-ring: oklch(72% 0.175 50);
/* Charts */ --chart-1: oklch(72% 0.175 50); --chart-2: oklch(78% 0 0); --chart-3: oklch(78% 0.120 65); --chart-4: oklch(60% 0.060 30); --chart-5: oklch(45% 0 0);
/* Shadows — flat in dark; only overlays use --shadow-pop */ --shadow-xs-val: 0 0 #0000; --shadow-sm-val: 0 0 #0000; --shadow-md-val: 0 0 #0000; --shadow-lg-val: 0 0 #0000; --shadow-pop-val: 0 18px 40px rgba(0, 0, 0, 0.55), 0 1px 0 var(--border) inset;}
@layer base { * { @apply border-border outline-ring/50; } body { @apply bg-background text-foreground; font-feature-settings: "ss01" 1, "cv11" 1; -webkit-font-smoothing: antialiased; }}
/* Pangea dnd placeholder — thin dashed line instead of full-height gap */[data-rfd-placeholder] { height: 3px !important; min-height: 3px !important; margin: 0 !important; padding: 0 !important; background: transparent !important; border-radius: 0 !important; border-top: 2px dashed var(--border) !important;}Environment variables
Section titled “Environment variables”Create a Convex dev deployment if you don’t have one. convex dev writes CONVEX_DEPLOYMENT,
NEXT_PUBLIC_CONVEX_URL and NEXT_PUBLIC_CONVEX_SITE_URL to .env.local. Then add the rest
to .env.local, using your app’s own URL:
# Since the ".env.local" file is gitignored, use this file to build a new one# when you clone the repo. Keep it up to date when you add new variables to# `.env.local`.
# This file is committed to version control — never put secrets in it.
# When adding new environment variables, update the schema in "src/env.mjs".
NEXT_PUBLIC_CONVEX_URL=""NEXT_PUBLIC_CONVEX_SITE_URL=""
NEXT_PUBLIC_SITE_URL="http://localhost:3010"SITE_URL="http://localhost:3010"BETTER_AUTH_SECRET=""Generate the secret with openssl rand -base64 32. Better Auth runs inside the deployment and
never reads .env.local, so set the same two values there too:
npx convex env set SITE_URL http://localhost:3000npx convex env set BETTER_AUTH_SECRET <the BETTER_AUTH_SECRET from .env.local>pnpm convex env set SITE_URL http://localhost:3000pnpm convex env set BETTER_AUTH_SECRET <the BETTER_AUTH_SECRET from .env.local>yarn convex env set SITE_URL http://localhost:3000yarn convex env set BETTER_AUTH_SECRET <the BETTER_AUTH_SECRET from .env.local>bunx convex env set SITE_URL http://localhost:3000bunx convex env set BETTER_AUTH_SECRET <the BETTER_AUTH_SECRET from .env.local>deno x convex env set SITE_URL http://localhost:3000deno x convex env set BETTER_AUTH_SECRET <the BETTER_AUTH_SECRET from .env.local>A missing or different value on the deployment makes the first sign-in fail with a 403.
Run it
Section titled “Run it”vex dev replaces convex dev. It generates the schema and types from your config, then runs
convex dev and watches for changes. Run it beside next dev:
npm run vex:devpnpm run vex:devyarn run vex:devbun run vex:devdeno task vex:devOpen /auth/sign-up and create an account, then make it the admin. In a new project the welcome
page does this; here, run promoteFirstAdmin once as that account, using the email you signed up
with:
npx convex run vex/firstUser:promoteFirstAdmin --identity '{"email":"you@example.com"}'pnpm convex run vex/firstUser:promoteFirstAdmin --identity '{"email":"you@example.com"}'yarn convex run vex/firstUser:promoteFirstAdmin --identity '{"email":"you@example.com"}'bunx convex run vex/firstUser:promoteFirstAdmin --identity '{"email":"you@example.com"}'deno x convex run vex/firstUser:promoteFirstAdmin --identity '{"email":"you@example.com"}'It does nothing once an admin exists. Then open /admin.
OAuth providers
Section titled “OAuth providers”Choosing a provider when you create a project changes the files below. This is what they look like
with Google; other providers follow the same pattern with their own variable names. Create the
OAuth client in the provider’s console with the callback URL
<your site URL>/api/auth/callback/google, put both values in .env.local, and set them on the
Convex deployment with convex env set.
import type { BetterAuthOptions } from "better-auth"
import { anonRoleDatabaseHook } from "@vexcms/better-auth"
import { AUTH_COOKIE_PREFIX, USER_ROLES } from "~/db/constants"
import { createPlugins } from "./plugins"import { authSchema } from "./schema"
// `plugins` on the shared schema is a descriptor map for// `betterAuthCollections`, not Better Auth plugin instances — dropped by name// so the intent survives a reordering of the object literal below.const { plugins: _pluginDescriptors, ...schemaOptions } = authSchema
/** * Better Auth options for this project. * * Model names and `user.additionalFields` come from `./schema`, the one module * both this file and `src/vex.config.ts` read, so a field added there reaches * the database and the admin panel without being written twice. Everything * below the spread is server-only. * * @see ./schema for the shared, client-safe half */export const authOptions: BetterAuthOptions = { ...schemaOptions, // Unique per app so another Better Auth app on localhost cannot share or // shadow this session cookie — see AUTH_COOKIE_PREFIX. advanced: { cookiePrefix: AUTH_COOKIE_PREFIX }, baseURL: process.env.SITE_URL, databaseHooks: { // Ties Better Auth's anonymous-plugin users to `access.anonRole` (see // `~/auth/access.ts`) by stamping the same role explicitly, rather than // relying solely on `roles`' `defaultValue` below — which every new user // gets regardless of `isAnonymous`, anon-plugin or not. user: anonRoleDatabaseHook(USER_ROLES.user), }, emailAndPassword: { enabled: true }, socialProviders: { google: { clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, } }, plugins: createPlugins(), secret: process.env.BETTER_AUTH_SECRET, trustedOrigins: [process.env.SITE_URL!],}"use client"
import type { ReactNode } from "react"
import { AuthUIProvider } from "@daveyplate/better-auth-ui"import Link from "next/link"
import { authClient } from "~/auth/client"
/** * Mounts `@daveyplate/better-auth-ui`'s `AuthUIProvider` around `AuthView` * only, at the two places it renders (`(frontend)/auth/[pathname]/view.tsx`, * the `@auth` intercepted sign-in modal) — not at the app root. `AuthView` * reads its form config (credentials, navigation) from this provider's context; * nothing else in the app needs it. * * `navigate`/`replace` hard-navigate (`window.location.href`/`.replace`, a full * document load) instead of `router.push`/`router.replace`. The library's own * `useOnSuccessTransition` (driving sign-in/sign-up success, among other auth * transitions) does `await refetchSession(); await onSessionChange?.(); * navigate(redirectTo)` — `onSessionChange` used to be `() => router.refresh()`, * a fire-and-forget call with no real promise to await (`router.refresh()` * returns `void`), so `navigate(redirectTo)` (`router.push`) fired immediately * after, while the refresh's own RSC re-fetch for the PRE-navigation route was * still in flight. When that refresh resolved after the push had already * started (worse under a slow first compile), Next's router reconciled the * stale pre-navigation tree over the pushed route — "credentials accepted, the * app compiled for a while, then nothing happened," landing back on the * sign-in page despite a real session (confirmed signed in on back/forward). * A hard navigation has no client-side router state to race: there is nothing * left for a stale `refresh()` to clobber, and the full load re-resolves every * server-rendered auth state fresh — `onSessionChange` is dropped entirely, it * no longer does anything a hard navigation doesn't already cover. */export default function AuthViewProvider({ children }: { children: ReactNode }) { return ( <AuthUIProvider authClient={authClient} credentials={true} social={{ providers: ["google"] }} Link={Link} navigate={(href) => { window.location.href = href }} replace={(href) => { window.location.replace(href) }} > {children} </AuthUIProvider> )}import { createEnv } from "@t3-oss/env-nextjs"import { z } from "zod"
export const env = createEnv({ /** * Specify your client-side environment variables schema here. This way you can ensure the app * isn't built with invalid env vars. To expose them to the client, prefix them with * `NEXT_PUBLIC_`. */ client: { NEXT_PUBLIC_CONVEX_SITE_URL: z.string(), NEXT_PUBLIC_CONVEX_URL: z.string(), NEXT_PUBLIC_SITE_URL: z.string(), },
/** * Makes it so that empty strings are treated as undefined. `SOME_VAR: z.string()` and * `SOME_VAR=''` will throw an error. */ emptyStringAsUndefined: true,
/** * You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g. * middlewares) or client-side so we need to destruct manually. */ runtimeEnv: { BETTER_AUTH_SECRET: process.env.BETTER_AUTH_SECRET, GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET, NEXT_PUBLIC_CONVEX_SITE_URL: process.env.NEXT_PUBLIC_CONVEX_SITE_URL, NEXT_PUBLIC_CONVEX_URL: process.env.NEXT_PUBLIC_CONVEX_URL, NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL, NODE_ENV: process.env.NODE_ENV, }, /** * Specify your server-side environment variables schema here. This way you can ensure the app * isn't built with invalid env vars. */ server: { BETTER_AUTH_SECRET: z.string(), GOOGLE_CLIENT_ID: z.string(), GOOGLE_CLIENT_SECRET: z.string(), NODE_ENV: z.enum(["development", "test", "production"]), }, /** * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially * useful for Docker builds. * * Also skipped inside the Convex runtime: `convex/vex.ts` imports the admin config, which * can reach this module through registered admin components, and a Convex push never sets * `NEXT_PUBLIC_*` (only Next does). `CONVEX_CLOUD_URL` is set by Convex and never by Next, so * its presence is a reliable signal we are inside a Convex function/push, not a Next process. */ skipValidation: !!process.env.SKIP_ENV_VALIDATION || !!process.env.CONVEX_CLOUD_URL,})# Since the ".env.local" file is gitignored, use this file to build a new one# when you clone the repo. Keep it up to date when you add new variables to# `.env.local`.
# This file is committed to version control — never put secrets in it.
# When adding new environment variables, update the schema in "src/env.mjs".
NEXT_PUBLIC_CONVEX_URL=""NEXT_PUBLIC_CONVEX_SITE_URL=""
NEXT_PUBLIC_SITE_URL="http://localhost:3010"SITE_URL="http://localhost:3010"BETTER_AUTH_SECRET=""
# Google OAuth Client IDGOOGLE_CLIENT_ID=# Google OAuth Client SecretGOOGLE_CLIENT_SECRET=See Authentication for how providers reach the admin panel.
Optional pieces
Section titled “Optional pieces”The admin works without these. vex doctor lists each one as optional.
Sign-in modal
Section titled “Sign-in modal”The @auth parallel route opens sign-in in a dialog over the current page instead of navigating
away. Add the files, then take auth as a prop in the root layout and render {auth} after
{children} (see the reference layout above).
export default function Page() { return null}export default function Page() { return null}/** * Catches every route under this slot that isn't the intercepted `/auth/*` * page or the exact root (`page.tsx`) — i.e. soft-navigating anywhere else * while the auth modal is open. Without this, Next.js's documented parallel- * route limitation applies: on a soft navigation to a URL this slot has no * match for, it keeps rendering whatever was last active instead of falling * back to `default.tsx`, so the modal would stay open over the new page. A * catch-all gives the slot an explicit (null) match for every other route, * closing the modal the instant the caller navigates away. */export default function Page() { return null}// `(.)auth` — not `(...)auth` — because the interception convention keys off// ROUTE SEGMENTS, not filesystem nesting, and slots (`@auth`) add no segment// of their own. `@auth` sits directly under `app/`, i.e. at the app root,// which is the SAME level as `auth/[pathname]` (under the `(frontend)` route// group, which also adds no segment). `(.)` ("same level") is therefore both// correct and the idiomatic choice — it's what Next's own parallel-routes// modal example uses for a root-level slot. `(...)` ("from the app root")// would resolve identically here only because that same level IS the root;// `(.)` says that plainly instead of relying on the coincidence.import AuthView from "./view"
export const dynamic = "force-dynamic"
export default async function AuthPage({ params }: { params: Promise<{ pathname: string }> }) { const { pathname } = await params
return <AuthView pathname={pathname} />}"use client";
import { AuthView } from "@daveyplate/better-auth-ui";import { useRouter, useSearchParams } from "next/navigation";
import AuthViewProvider from "~/auth/AuthViewProvider";import { Dialog, DialogContent, DialogTitle } from "~/components/ui/dialog";import { resolveAuthPageTitle } from "~/lib/authPageTitle";
export default function AuthCard({ pathname }: { pathname: string }) { const router = useRouter(); const searchParams = useSearchParams(); // `redirectTo` alone can't distinguish a server GUARD redirect (middleware's // `redirectToSignIn`, or `/admin`'s own `redirect("/auth/sign-in?redirectTo=…")`) // from an explicit "Sign in" click — `AdminTopNav`'s `AuthControl` also sends // `redirectTo` (the current admin URL, to return to after signing in), and it // wants the DIALOG like every other explicit sign-in trigger, not the // full-screen guard card. `~/auth/client`'s `signInHref` appends `modal=1` as // the marker that says "this is a deliberate sign-in, render it as a modal" — // its absence is what makes a redirect a guard redirect. const isGuardRedirect = searchParams.has("redirectTo") && !searchParams.has("modal"); if (isGuardRedirect) { return ( <AuthViewProvider> <main className="absolute inset-0 grid place-items-center"> <AuthView path={pathname} /> </main> </AuthViewProvider> ); } // No in-flow wrapper here on purpose. The Dialog portals into <body>, so a // wrapping <main> would be an empty element sitting after everything else // (the `@auth` slot renders last in the root layout). Next's post-navigation // scroll handler targets the new segment's first DOM node and would scroll // that empty element into view — i.e. jump the page to the bottom behind // the modal. With only a portal rendered there is no node to target. return ( <AuthViewProvider> <Dialog onOpenChange={(open) => { if (!open) { router.back(); } }} open > <DialogContent aria-describedby={undefined} className="grid place-items-center bg-transparent shadow-none ring-transparent" > <DialogTitle className="sr-only">{resolveAuthPageTitle(pathname)}</DialogTitle> <AuthView path={pathname} /> </DialogContent> </Dialog> </AuthViewProvider> );}"use client"
import { Button as ButtonPrimitive } from "@base-ui/react/button"import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "~/lib/utils"
const buttonVariants = cva( "focus-visible:border-ring focus-visible:focus-ring aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 rounded-md border border-transparent bg-clip-padding text-sm font-medium aria-invalid:ring-[3px] [&_svg:not([class*='size-'])]:size-4 inline-flex items-center justify-center whitespace-nowrap transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none shrink-0 [&_svg]:shrink-0 outline-none group/button select-none", { defaultVariants: { size: "default", variant: "default", }, variants: { size: { default: "h-9 gap-1.5 px-2.5 in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2", icon: "size-9", "icon-lg": "size-10", "icon-sm": "size-8 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-md", "icon-xs": "size-6 rounded-[min(var(--radius-md),8px)] in-data-[slot=button-group]:rounded-md [&_svg:not([class*='size-'])]:size-3", lg: "h-10 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-3 has-data-[icon=inline-start]:pl-3", sm: "h-8 gap-1 rounded-[min(var(--radius-md),10px)] px-2.5 in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5", xs: "h-6 gap-1 rounded-[min(var(--radius-md),8px)] px-2 text-xs in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3", }, variant: { default: "bg-primary text-primary-foreground hover:bg-primary/80", destructive: "bg-destructive/10 hover:bg-destructive/20 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/20 text-destructive focus-visible:border-destructive/40 dark:hover:bg-destructive/30", ghost: "hover:bg-muted hover:text-foreground dark:hover:bg-muted/50 aria-expanded:bg-muted aria-expanded:text-foreground", link: "text-primary underline-offset-4 hover:underline", outline: "border-border bg-background hover:bg-muted hover:text-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50 aria-expanded:bg-muted aria-expanded:text-foreground shadow-xs", secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground", }, }, })
function Button({ className, size = "default", variant = "default", ...props}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) { return ( <ButtonPrimitive className={cn(buttonVariants({ className, size, variant }))} data-slot="button" {...props} /> )}
export { Button, buttonVariants }"use client"
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"import { XIcon } from "lucide-react"import * as React from "react"
import { Button } from "~/components/ui/button"import { cn } from "~/lib/utils"
let openDialogCount = 0
function Dialog({ ...props }: DialogPrimitive.Root.Props) { return <DialogPrimitive.Root data-slot="dialog" {...props} />}
function DialogClose({ ...props }: DialogPrimitive.Close.Props) { return <DialogPrimitive.Close data-slot="dialog-close" {...props} />}
function DialogContent({ children, className, showCloseButton = true, ...props}: DialogPrimitive.Popup.Props & { showCloseButton?: boolean}) { React.useEffect(() => { const main = document.getElementById("main") openDialogCount += 1 main?.setAttribute("inert", "") return () => { openDialogCount -= 1 if (openDialogCount === 0) { main?.removeAttribute("inert") } } }, [])
return ( <DialogPortal> <DialogOverlay /> <DialogPrimitive.Popup aria-modal="true" className={cn( "bg-background data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 ring-foreground/10 grid max-w-[calc(100%-2rem)] gap-6 rounded-xl p-6 text-sm ring-1 duration-100 sm:max-w-md fixed top-1/2 left-1/2 z-50 w-full -translate-x-1/2 -translate-y-1/2 outline-none", className )} data-slot="dialog-content" {...props} > {children} {showCloseButton && ( <DialogPrimitive.Close data-slot="dialog-close" render={<Button className="absolute top-4 right-4" size="icon-sm" variant="ghost" />} > <XIcon /> <span className="sr-only">Close</span> </DialogPrimitive.Close> )} </DialogPrimitive.Popup> </DialogPortal> )}
function DialogDescription({ className, ...props }: DialogPrimitive.Description.Props) { return ( <DialogPrimitive.Description className={cn( "text-muted-foreground *:[a]:hover:text-foreground text-sm *:[a]:underline *:[a]:underline-offset-3", className )} data-slot="dialog-description" {...props} /> )}
function DialogFooter({ children, className, showCloseButton = false, ...props}: React.ComponentProps<"div"> & { showCloseButton?: boolean}) { return ( <div className={cn("gap-2 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)} data-slot="dialog-footer" {...props} > {children} {showCloseButton && ( <DialogPrimitive.Close render={<Button variant="outline" />}>Close</DialogPrimitive.Close> )} </div> )}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { return ( <div className={cn("gap-2 flex flex-col", className)} data-slot="dialog-header" {...props} /> )}
function DialogOverlay({ className, ...props }: DialogPrimitive.Backdrop.Props) { return ( <DialogPrimitive.Backdrop className={cn( "data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs fixed inset-0 isolate z-50", className )} data-slot="dialog-overlay" {...props} /> )}
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) { return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />}
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) { return ( <DialogPrimitive.Title className={cn("leading-none font-medium", className)} data-slot="dialog-title" {...props} /> )}
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) { return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />}
export { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger,}import { type ClassValue, clsx } from "clsx"import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs))}Live preview
Section titled “Live preview”Live preview turns on Next.js Draft Mode through this route:
import { createVexDraftModeRoute } from "@vexcms/next/livePreview"
import { getToken, getUserOrgForVexApi } from "~/auth/server"import config from "~/vex.config.server"
/** * `GET /api/vex/live-preview` — enables or disables Next.js Draft Mode for * this app's live-preview sessions. * * `proxy.ts`'s `proxy` hands a `?vexLivePreview=1` request off here once it * verifies the session itself; this route re-verifies with its own session * accessor (`getToken`), resolves the caller (`getUserOrgForVexApi`) and * requires that they could preview at least one collection or global, then * enables Draft Mode, sets the `vex-live-preview` marker cookie, and * redirects back to `redirect`. A public page can then check * `(await draftMode()).isEnabled` to render a never-published document * instead of a 404, for the client-side preview layer to take over. A * session that cannot preview anything is sent back without * `vexLivePreview=1` and Draft Mode stays off. * * Also handles leaving preview mode: `?disable=1` (no session required — * turning preview off needs no authorization) and a signed-out request that * still carries a `redirect` target both disable Draft Mode and clear the * marker before redirecting. See `createVexDraftModeRoute`'s own doc comment * for the full enable/disable decision tree. */export const { GET } = createVexDraftModeRoute({ getToken, getRequestAuth: getUserOrgForVexApi, config })A request with ?vexLivePreview=1 has to pass through that route once. A new project does this
in src/proxy.ts. Don’t copy that file as it is: besides the hand-off, it signs people out of
every route except /, the auth pages and /admin. Instead, merge the parts that mention
LIVE_PREVIEW_QUERY_PARAM, hasPreviewHandOffCookies and redirectToDraftModeRoute into your own
proxy.ts (middleware.ts on Next.js 15), and wrap your layout’s children in
LivePreviewProvider from @vexcms/react:
import { api } from "@convex/_generated/api";import { LIVE_PREVIEW_COOKIE, LIVE_PREVIEW_QUERY_PARAM, loadVexConfigModule } from "@vexcms/core";import { DRAFT_MODE_BYPASS_COOKIE } from "@vexcms/next/livePreview";import { getSessionCookie } from "better-auth/cookies";import { fetchQuery } from "convex/nextjs";import { type NextRequest, NextResponse } from "next/server";
import { AUTH_COOKIE_PREFIX } from "~/db/constants";
/** * Both names Better Auth may give this app's session cookie: `__Secure-` over * https, bare over http. Derived from `AUTH_COOKIE_PREFIX` so a different * Better Auth app's cookie on the same host (e.g. another `localhost` port) is * never read — or deleted — as ours. */const SESSION_COOKIES = { https: `__Secure-${AUTH_COOKIE_PREFIX}.session_token`, http: `${AUTH_COOKIE_PREFIX}.session_token`,} as const;
/** * Paths the proxy must never guard, because they are where it sends people. * Guarding them turns a Convex outage into an infinite redirect loop. */const ALWAYS_ALLOWED: Record<string, true> = { "/": true, "/unauthorized": true };
/** * Session gate for every route except the public ones in `config.matcher`, * plus the live-preview hand-off. * * `/admin/*` is one of those exclusions: its own page component * (`src/app/(vexcms)/admin/[[...path]]/page.tsx`) is its only gate, and fails * closed the same way this one does (see that file's doc comment). * * **Live preview.** A `?vexLivePreview=1` request from a verified session that * has not yet been through `/api/vex/live-preview` is redirected there: Draft * Mode can only be enabled from a Route Handler, never from middleware. "Been * through" means BOTH the `vex-live-preview` marker and Next's * `__prerender_bypass` cookie are present — the marker outlives Draft Mode * (1h vs. browser session), so the marker alone would skip re-enabling it. The * hand-off fails open: without a verified session the request continues as if * it carried no param, because the route's signed-out branch redirects back to * this same URL and would otherwise loop. * * Fails **closed** on guarded routes: if the session cannot be verified — no * cookie, no matching session, or the Convex lookup throwing — the request is * redirected rather than served. A verification error is not evidence of a * valid session, and serving the page anyway would drop authentication for * every guarded route the moment Convex became unreachable. * * Two distinct outcomes, deliberately: * - **No/invalid session** → `/auth/sign-in`, clearing the stale cookie so the * presence check cannot lie on the next request. * - **Verification failed** (Convex unreachable, timeout) → `/unauthorized`, * leaving cookies intact: the session may well be fine, so signing the user * out and discarding it would be wrong. * * **`admin.livePreview.expiredSessions: "deny"`.** Every guarded route here * already fails closed on "unauthenticated" — but that only clears the * session cookie, never the two live-preview ones (`vex-live-preview` / * `__prerender_bypass`), and `ALWAYS_ALLOWED` routes (`/`, `/unauthorized`) * skip the session check entirely by default. Left alone (`"allow"`, the * default), a request carrying a live-preview cookie whose session has since * gone can keep Draft Mode on past sign-out until the cookies expire on their * own — not a content-secrecy gap, since draft content stays gated behind * each query's own `readDrafts` check, but it can serve the draft-only base * layer's published fallback (or nothing) instead of the live site. Setting * `expiredSessions: "deny"` closes that gap: ANY request carrying either * cookie — even an `ALWAYS_ALLOWED` one, even without `?vexLivePreview=1` — * is checked, and an unauthenticated one is redirected to * `/api/vex/live-preview?disable=1&redirect=<this path>` first, to clear both * cookies before (for a guarded route) the normal sign-in redirect would take * over on the next pass. A "verification-failed" session is left alone here * too, for the same reason `redirectToUnauthorized` leaves cookies intact. * `/api/vex/live-preview` itself is excluded from `config.matcher` below, so * this redirect can never loop. * * @param request - The incoming request. * @returns A redirect to the Draft Mode hand-off, the expired-session disable * route, sign-in, or the unauthorized page; otherwise `NextResponse.next()`. */export async function proxy(request: NextRequest) { const isAlwaysAllowed = ALWAYS_ALLOWED[request.nextUrl.pathname] === true; const hasPreviewMarker = hasAnyPreviewCookie(request); const isPreviewHandOff = request.nextUrl.searchParams.get(LIVE_PREVIEW_QUERY_PARAM) === "1" && !hasPreviewHandOffCookies(request); const clientConfig = await loadVexConfigModule({ load: () => import("~/vex.config") }); const expiredSessionsDeny = clientConfig.status === "loaded" && clientConfig.config.admin.livePreview.expiredSessions === "deny";
if (isAlwaysAllowed && !isPreviewHandOff && !(expiredSessionsDeny && hasPreviewMarker)) { return NextResponse.next(); }
const sessionStatus = await resolveSessionStatus(request); if (expiredSessionsDeny && hasPreviewMarker && sessionStatus === "unauthenticated") { return redirectToDisableLivePreview(request); } if (isPreviewHandOff && sessionStatus === "authenticated") { return redirectToDraftModeRoute(request); } if (isAlwaysAllowed) { return NextResponse.next(); } if (sessionStatus === "unauthenticated") { return redirectToSignIn(request); } if (sessionStatus === "verification-failed") { return redirectToUnauthorized(request); } return NextResponse.next();}
/** * Reads and verifies the Better Auth session cookie, through Better Auth's own * reader (it checks the `__Secure-` name, then the bare one). * * @param request - The incoming request. * @returns `"authenticated"` for a session with a user, `"unauthenticated"` * for no cookie or no matching session, `"verification-failed"` when the * Convex lookup throws. */async function resolveSessionStatus( request: NextRequest,): Promise<"authenticated" | "unauthenticated" | "verification-failed"> { const sessionToken = getSessionCookie(request, { cookiePrefix: AUTH_COOKIE_PREFIX }); if (!sessionToken) return "unauthenticated";
try { const session = await fetchQuery(api.auth.sessions.getSessionWithUser, { sessionToken: extractToken(sessionToken), }); return session?.user ? "authenticated" : "unauthenticated"; } catch { return "verification-failed"; }}
/** * Whether this request already round-tripped through `/api/vex/live-preview` * with Draft Mode still on. * * @param request - The incoming request. * @returns `true` when both the marker and Next's Draft Mode cookie are present. */function hasPreviewHandOffCookies(request: NextRequest): boolean { return ( request.cookies.get(LIVE_PREVIEW_COOKIE)?.value === "1" && request.cookies.has(DRAFT_MODE_BYPASS_COOKIE) );}
/** * Whether this request carries EITHER live-preview cookie — the marker or * Next's own Draft Mode cookie — as opposed to {@link hasPreviewHandOffCookies}, * which requires both. Used by the `expiredSessions: "deny"` check: a stale * cookie on its own is still a sign that Draft Mode may be on for this * visitor. * * @param request - The incoming request. * @returns `true` when at least one of the two cookies is present. */function hasAnyPreviewCookie(request: NextRequest): boolean { return ( request.cookies.get(LIVE_PREVIEW_COOKIE)?.value === "1" || request.cookies.has(DRAFT_MODE_BYPASS_COOKIE) );}
/** * Redirect to the Draft Mode Route Handler, which re-verifies the session, * enables Draft Mode, sets the marker cookie, and sends the editor back here. * * @param request - The `?vexLivePreview=1` request to return to. * @returns A redirect to `/api/vex/live-preview?redirect=<this path + query>`. */function redirectToDraftModeRoute(request: NextRequest) { const draftModeUrl = new URL("/api/vex/live-preview", request.url); draftModeUrl.searchParams.set("redirect", request.nextUrl.pathname + request.nextUrl.search); return NextResponse.redirect(draftModeUrl);}
/** * Redirect to the Draft Mode Route Handler's explicit disable branch — clears * both the `vex-live-preview` marker and `__prerender_bypass`, then sends the * visitor back here, published — used by the `expiredSessions: "deny"` check. * * @param request - The request carrying a stale live-preview cookie. * @returns A redirect to `/api/vex/live-preview?disable=1&redirect=<this path + query>`. */function redirectToDisableLivePreview(request: NextRequest) { const disableUrl = new URL("/api/vex/live-preview", request.url); disableUrl.searchParams.set("disable", "1"); disableUrl.searchParams.set("redirect", request.nextUrl.pathname + request.nextUrl.search); return NextResponse.redirect(disableUrl);}
/** Extract the raw token — better-auth stores "<raw_token>.<hmac_signature>" */function extractToken(cookieValue: string) { return cookieValue.includes(".") ? cookieValue.split(".")[0] : cookieValue;}
/** * Redirect for a caller with no usable session. Clears the session cookies so * the presence check cannot lie on the next request. * * @param request - The request being rejected. * @returns A redirect to sign-in preserving the intended destination. */function redirectToSignIn(request: NextRequest) { const signInUrl = new URL("/auth/sign-in", request.url); // Preserve where the user was headed (path + query) signInUrl.searchParams.set("redirectTo", request.nextUrl.pathname + request.nextUrl.search);
const response = NextResponse.redirect(signInUrl); // Clear the stale cookie so the presence-check never lies again. The // `__Secure-` name must be expired with `secure: true` — browsers reject any // `Set-Cookie` for a `__Secure-` name that lacks it, so a bare delete is a // silent no-op. response.cookies.delete({ name: SESSION_COOKIES.https, path: "/", secure: true }); response.cookies.delete({ name: SESSION_COOKIES.http, path: "/" }); return response;}
/** * Redirect for a caller whose session could not be *verified* — as opposed to * one who has none. * * Cookies are deliberately left intact: the session is probably valid and the * verification path (Convex) is simply unavailable, so discarding it would sign * out every user during an outage. `/unauthorized` is exempt from this proxy, so * this cannot loop. * * @param request - The request that could not be verified. * @returns A redirect to the unauthorized page. */function redirectToUnauthorized(request: NextRequest) { return NextResponse.redirect(new URL("/unauthorized", request.url));}
export const config = { matcher: [ "/((?!api|_next/static|_next/image|favicon.ico|favicons|models/*|staging/*|auth/sign-in|auth/sign-up|admin).*)", ],};On-demand revalidation
Section titled “On-demand revalidation”Revalidates cached pages when content is published. See Caching and SEO.
import { createVexRevalidateRoute } from "@vexcms/next/cache"
import { getToken, getUserOrgForVexApi } from "~/auth/server"import config from "~/vex.config.server"
/** * `POST /api/vex/revalidate` — session-authorized path purge. * * Called by `useVexMutation` after every admin-panel write, same origin, and * by the admin panel's Revalidate control over the same session. Never * secret-authorized: the caller must hold a real session with write * permission on the affected collection. */export const { POST } = createVexRevalidateRoute({ config, getToken, getAuth: getUserOrgForVexApi,})Theme script
Section titled “Theme script”Applies the saved light or dark theme, and restores the edit form’s scroll position, before the
first paint. Render both in the root layout’s <head>.
"use client";
import { buildThemeInitScript } from "@vexcms/react/server";
/** * Next.js App Router wrapper around `@vexcms/react/server`'s * `buildThemeInitScript` — renders the real blocking theme-init script during * SSR (so it's part of the raw HTML text the browser parses, exactly like * `@vexcms/react/server`'s `<ThemeScript />`), but renders nothing on any * CLIENT render of this component. * * Why this file exists instead of just using `<ThemeScript />` directly: see * `packages/react/src/server/ThemeScript.tsx`'s doc comment ("Next.js App * Router: a dev-only console warning") for the full root cause and the live * evidence this exact pattern was verified against. Short version — `next * dev` answers a thrown `notFound()` with a minimal error shell first, then * reconciles the real root layout (this component included) entirely on the * client from the RSC payload. A `<script>` host node React commits that way * (rather than the browser parsing it from raw HTML) triggers React's * "Encountered a script tag while rendering React component" warning — by * design, since scripts inserted that way never execute. A genuine Server * Component only ever runs once (server-side), so it can't distinguish "I'm * raw HTML text" from "I'm being committed by the client reconciler" to * avoid that second case. This component can, via `typeof window`, because it * runs again for every client render. * * `typeof window !== "undefined"` is true during BOTH ordinary hydration and * the problematic client-only reconciliation above — in both cases the real * script already ran (ordinary hydration: it ran during the initial HTML * parse; the error-shell case: there was never a correct `.dark` class to * begin with, and `ThemeProvider`'s layout effect — not this script — is * what applies it, see its own doc comment). Rendering `null` here is a * pure no-op in both, not a functional regression: confirmed live, the real * script still lands verbatim in the SSR'd HTML, the `notFound()` 404 warning * stops reproducing, and `<html>` still carries `.dark` with no flash. * * This wrapper is intentionally NOT exported from `@vexcms/react` (kept * local to each Next.js app instead): a `"use client"` file exported through * a real package boundary crosses Next's cross-package client-reference * resolution, a path this exact live verification didn't cover. * * @param props - Component props. * @param props.storageKey - localStorage key (default: `"vex-theme"`). * @returns The real theme-init script during SSR; `null` on every client render. */export function ThemeScript({ storageKey = "vex-theme" }: { storageKey?: string } = {}) { if (typeof window !== "undefined") { return null; }
return ( <script dangerouslySetInnerHTML={{ __html: buildThemeInitScript({ storageKey }) }} suppressHydrationWarning /> );}"use client";
import { buildScrollRestoreInitScript } from "@vexcms/react/server";
/** * Next.js App Router wrapper around `@vexcms/react/server`'s * `buildScrollRestoreInitScript` — renders the real head-level scroll-restore * script during SSR (so it's part of the raw HTML text the browser parses, * exactly like `@vexcms/react/server`'s `<ScrollRestoreScript />`), but * renders nothing on any CLIENT render of this component. * * Why this file exists instead of just using `<ScrollRestoreScript />` * directly: the exact same reason `~/components/ThemeScript.tsx` exists — * see `packages/react/src/server/ThemeScript.tsx`'s doc comment ("Next.js * App Router: a dev-only console warning") for the full root cause. A * genuine Server Component only ever runs once (server-side), so it can't * distinguish "I'm raw HTML text" from "I'm being committed by the client * reconciler" to avoid rendering a stray `<script>` host node in the * second case. This component can, via `typeof window`, because it runs * again for every client render. * * @returns The real scroll-restore-init script during SSR; `null` on every client render. */export function ScrollRestoreScript() { if (typeof window !== "undefined") { return null }
return <script dangerouslySetInnerHTML={{ __html: buildScrollRestoreInitScript() }} suppressHydrationWarning />}Global error page
Section titled “Global error page”Shows the VexCMS config error banner when the config throws at runtime.
"use client"
import "./globals.css"
import { isVexConfigError, summarizeVexConfigError } from "@vexcms/core"import { buttonVariants, cn, VexConfigErrorBanner } from "@vexcms/react"import { useEffect } from "react"
/** * Last-resort boundary for errors the root layout itself throws. The root layout already turns a * Vex config failure into `VexConfigErrorBanner` on the server; this covers one that only throws * in the browser. Anything else gets a generic message and a retry. * * @param props.error - The thrown error; logged to the console. * @param props.reset - Re-renders the root. */export default function GlobalError({ error, reset,}: { error: Error & { digest?: string } reset: () => void}) { useEffect(() => { console.error(error) }, [error])
return ( <html lang="en"> <body> {isVexConfigError(error) ? ( <VexConfigErrorBanner className="min-h-svh" error={summarizeVexConfigError({ error, includeDetail: process.env.NODE_ENV === "development" })} /> ) : ( <div className="flex min-h-screen flex-col items-center justify-center gap-4 p-8 text-center"> <h1 className="text-2xl font-semibold">Something went wrong</h1> <button className={cn(buttonVariants({ variant: "default" }))} onClick={reset} type="button"> Try again </button> </div> )} </body> </html> )}Access helpers
Section titled “Access helpers”Server and client helpers for checking VexCMS permissions in your own pages. See Access control.
"use client";
import { hasPermission as hasPermissionCore, type HasPermissionProps } from "@vexcms/core";
import { useAuth } from "~/context/AuthContext";
import { access } from "./access";
type Subjects = NonNullable<typeof access.__subjects>;/** * Client-side permission check for UI affordances (advisory — server guards enforce). * * Kept alongside `@vexcms/react`'s `usePermission` deliberately: the frontend tree is * not wrapped in the Vex providers, so this reads the app's own `AuthContext` and * imports the access config directly instead of resolving both from context. * * @param props.resource - Subject slug (collection/global/media/`adminPanel`). * @param props.action - Action to check. * @param props.data - The concrete document for an exact per-doc check (edit views). * @param props.scope - How to answer when a check needs the document and `data` was * not supplied: `"all"` (the default) → false, `"any"` → true (sidebar/list * gating), `"doc"` → throws (edit views — pass `data`). No effect when `data` is * given. See `PERMISSION_SCOPES`. * @returns The permission boolean. `false` for a signed-out user; `true` when no * `access` config exists at all — the access system being absent is the documented * open-by-default escape hatch, not a denial. * * `changes` is deliberately omitted: it authorizes a write against a field map, and a * client-side check cannot be trusted with that. Field maps are resolved for UI gating * via `useFieldPermissions` (`@vexcms/react`); the server is what enforces them. */export function hasPermission<TSubject extends keyof Subjects, TData extends object = object>( props: Omit< HasPermissionProps<Subjects, TSubject, TData>, "access" | "organization" | "user" | "changes" >,): boolean { // eslint-disable-next-line react-hooks/rules-of-hooks const { user } = useAuth(); return hasPermissionCore({ access, user, ...props, });}"use client";
import { hasPermission as hasPermissionCore, type HasPermissionProps } from "@vexcms/core";
import { useAuth } from "~/context/AuthContext";
import { access } from "./access";
type Subjects = NonNullable<typeof access.__subjects>;/** * Client-side permission check for UI affordances (advisory — server guards enforce). * * Kept alongside `@vexcms/react`'s `usePermission` deliberately: the frontend tree is * not wrapped in the Vex providers, so this reads the app's own `AuthContext` and * imports the access config directly instead of resolving both from context. * * @param props.resource - Subject slug (collection/global/media/`adminPanel`). * @param props.action - Action to check. * @param props.data - The concrete document for an exact per-doc check (edit views). * @param props.scope - How to answer when a check needs the document and `data` was * not supplied: `"all"` (the default) → false, `"any"` → true (sidebar/list * gating), `"doc"` → throws (edit views — pass `data`). No effect when `data` is * given. See `PERMISSION_SCOPES`. * @returns The permission boolean. `false` for a signed-out user; `true` when no * `access` config exists at all — the access system being absent is the documented * open-by-default escape hatch, not a denial. * * `changes` is deliberately omitted: it authorizes a write against a field map, and a * client-side check cannot be trusted with that. Field maps are resolved for UI gating * via `useFieldPermissions` (`@vexcms/react`); the server is what enforces them. */export function hasPermission<TSubject extends keyof Subjects, TData extends object = object>( props: Omit< HasPermissionProps<Subjects, TSubject, TData>, "access" | "organization" | "user" | "changes" >,): boolean { // eslint-disable-next-line react-hooks/rules-of-hooks const { user, organization } = useAuth(); return hasPermissionCore({ access, user, organization, ...props, });}import { api } from "@convex/_generated/api"import { getSessionCookie } from "better-auth/cookies"import { fetchQuery } from "convex/nextjs"import { headers } from "next/headers"
import { AUTH_COOKIE_PREFIX } from "~/db/constants"
/** * Read the Better Auth session token from cookies. * * Uses Better Auth's own reader with this app's `AUTH_COOKIE_PREFIX` rather * than a literal cookie name (AP-022): it checks `__Secure-<prefix>.session_token` * (https) then `<prefix>.session_token` (http), and the unique prefix keeps a * different Better Auth app on the same host from being read as this one. */export async function getSessionToken() { const sessionTokenCookie = getSessionCookie(await headers(), { cookiePrefix: AUTH_COOKIE_PREFIX })
if (!sessionTokenCookie) {return null}
// better-auth stores tokens as "<raw_token>.<hmac_signature>" (2 parts, not a JWT) // The raw token (first part) is what's indexed in the DB by_token if (sessionTokenCookie.includes(".")) { return sessionTokenCookie.split(".")[0] }
return sessionTokenCookie}
/** * Get current user session in Next.js server components/actions * Validates the Better Auth session token from cookies and fetches user data */export const getCurrentUser = async () => { try { const sessionToken = await getSessionToken() if (!sessionToken) {return null}
const session = await fetchQuery(api.auth.sessions.getSessionWithUser, { sessionToken, }) if (!session?.user) {return null} return session.user } catch (error) { console.error("Error getting current user:", error) return null }}
/** * Get full session (user + session data) in Next.js server components/actions */export async function getSession() { try { const sessionToken = await getSessionToken() if (!sessionToken) {return null}
const session = await fetchQuery(api.auth.sessions.getSessionWithUser, { sessionToken, }) if (!session?.user) {return null} return session } catch (error) { console.error("[getSession] Error:", error) return null }}import type { getSession } from "./serverUtils"
export type ServerAuthContext = Awaited<ReturnType<typeof getSession>>import { getToken, getUserOrg } from "~/auth/server";import { AuthProvider } from "~/context/AuthContext";
export async function AuthServerProvider(props: { children: React.ReactNode }) { // Started together, not sequentially — see `page.tsx`'s identical comment. Both calls // are `cache()`-memoized (`auth/server.ts`), so this reuses whichever of `layout.tsx`'s/ // `page.tsx`'s own calls for the same values resolves first, instead of firing a third // round trip for identical data. const [sessionToken, auth] = await Promise.all([getToken(), getUserOrg()]); if (!sessionToken) { return <AuthProvider value={{ user: null }}>{props.children}</AuthProvider>; } return <AuthProvider value={auth}>{props.children}</AuthProvider>;}"use client";
import { createContext, useContext } from "react";
import { type UserDoc } from "~/db/constants";
export interface CurrentAuth { user: null | UserDoc; // null → unauthenticated → no roles → deny}export const AuthContext = createContext<CurrentAuth>({ user: null });
export function AuthProvider(props: { children: React.ReactNode; value: { user: null | UserDoc; // null → unauthenticated → no roles → deny };}) { return <AuthContext.Provider value={props.value}>{props.children}</AuthContext.Provider>;}/** @returns the current caller `{ user }` from the server layout. */export function useAuth(): CurrentAuth { const context = useContext(AuthContext); if (context === null) { throw new Error("useAuth must be used within a AuthProvider"); } return context;}"use client";
import { createContext, useContext } from "react";
import { type OrganizationDoc, type UserDoc } from "~/db/constants";
export interface CurrentAuth { organization?: OrganizationDoc; user: null | UserDoc; // null → unauthenticated → no roles → deny}export const AuthContext = createContext<CurrentAuth>({ user: null });
export function AuthProvider(props: { children: React.ReactNode; value: { organization?: OrganizationDoc; user: null | UserDoc; // null → unauthenticated → no roles → deny };}) { return <AuthContext.Provider value={props.value}>{props.children}</AuthContext.Provider>;}/** @returns the current caller `{ user, organization }` from the server layout. */export function useAuth(): CurrentAuth { const context = useContext(AuthContext); if (context === null) { throw new Error("useAuth must be used within a AuthProvider"); } return context;}Images from Convex storage
Section titled “Images from Convex storage”A new project’s next.config.ts lets next/image load uploads from your Convex deployment’s host
(convexHost and images.remotePatterns) and sets security headers in production (headers(),
built from src/lib/csp.ts). Copy only those parts into your own config. Leave out
turbopack.root and findWorkspaceRoot: they only pin the build root for a new project, and
your app’s config already builds from the right place.
import type { NextConfig } from "next"
import { existsSync, readFileSync } from "node:fs"import { dirname, join, resolve } from "node:path"
import { env } from "./src/env.mjs"import { buildContentSecurityPolicy } from "./src/lib/csp"
/** * Whether `dir` is a workspace root: it holds `pnpm-workspace.yaml`, or a * `package.json` with a `workspaces` field (npm, yarn and bun workspaces). * * @param dir - Directory to check. * @returns `true` for a workspace root. */function isWorkspaceRoot(dir: string): boolean { if (existsSync(join(dir, "pnpm-workspace.yaml"))) {return true} const manifestPath = join(dir, "package.json") if (!existsSync(manifestPath)) {return false} try { const manifest: unknown = JSON.parse(readFileSync(manifestPath, "utf-8")) return typeof manifest === "object" && manifest !== null && "workspaces" in manifest } catch { return false }}
const LOCKFILES = ["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "bun.lock", "bun.lockb", "deno.lock"]
/** * Walks up from the app directory looking for a workspace root. Stops at the * first directory with its own lockfile: that directory owns `node_modules`, * so an unrelated workspace further up is never adopted. * * @param from - Directory to start from. * @returns The workspace root when this app is a workspace member, otherwise * `from` unchanged. */function findWorkspaceRoot(from: string): string { let dir = resolve(from) for (;;) { if (isWorkspaceRoot(dir)) {return dir} if (LOCKFILES.some((file) => existsSync(join(dir, file)))) {return resolve(from)} const parent = dirname(dir) if (parent === dir) {return resolve(from)} dir = parent }}
// Convex file storage URLs (`next/image` sources for uploaded media) are// served from `<deployment>.convex.cloud` — derive the hostname from the// validated NEXT_PUBLIC_CONVEX_URL so scaffolds work without a manual// next.config.ts edit. Falls back to an empty list/string when the URL is// unset or unparsable (e.g. a deployment-less build with SKIP_ENV_VALIDATION set).let convexHost = ""try { convexHost = new URL(env.NEXT_PUBLIC_CONVEX_URL).hostname} catch { // No deployment yet — leave convexHost empty.}
const convexImageRemotePatterns: NonNullable<NextConfig["images"]>["remotePatterns"] = convexHost ? [{ hostname: convexHost }] : []
// Vercel sets NODE_ENV=production for both the production domain and every// preview deployment, so a pushed branch's preview still gets the full// header set below; only `next dev` skips it.const isProduction = process.env.NODE_ENV === "production"
const securityHeaders: { key: string; value: string }[] = isProduction ? [ { key: "Content-Security-Policy", value: buildContentSecurityPolicy({ convexHost, frameAncestors: "'self'" }), }, { key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" }, { key: "X-Content-Type-Options", value: "nosniff" }, { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" }, { key: "Permissions-Policy", value: "geolocation=(), camera=(), microphone=()" }, ] : []
const nextConfig: NextConfig = { devIndicators: { position: "bottom-right", }, allowedDevOrigins: ["127.0.01", "localhost"], reactCompiler: true, // Every UA is treated as HTML-limited so metadata (the <title>, the // theme-color meta) always streams in the initial HTML rather than only // after JS hydration — the served HTML stays valid and assistive tech // reading the first response gets a real title. htmlLimitedBots: /.*/, // Turbopack's root sets the file-tracing root AND Tailwind's source-scan // root, so it has to be the directory that actually owns `node_modules`. // // Standalone scaffold: that is this app. Pinning it stops Next walking up // and adopting an unrelated outer lockfile. // // Workspace member (pnpm, npm, yarn or bun): it is the workspace root — // dependencies are hoisted there and `next` is only reachable from there. // Pinning to the app dir makes the build fail with "Could not find the // Next.js package". // // Detecting a workspace root picks the right answer in both cases without // the template needing a monorepo-specific variant. turbopack: { root: findWorkspaceRoot(import.meta.dirname), }, images: { // Additional remote image hosts (e.g. an external CMS or CDN) can be // added here alongside the auto-derived Convex hostname above. remotePatterns: convexImageRemotePatterns, }, async headers() { return securityHeaders.length > 0 ? [{ source: "/:path*", headers: securityHeaders }] : [] },}
export default nextConfigexport interface ContentSecurityPolicyInput { /** `new URL(env.NEXT_PUBLIC_CONVEX_URL).hostname`, or `""` when no deployment is configured. */ convexHost: string /** The `frame-ancestors` source list, e.g. `"'self'"`. */ frameAncestors: string}
/** * Builds the static `Content-Security-Policy` header value for this project. * * `script-src` carries `'unsafe-inline'`, not a hash list: Next's App Router * inlines a fresh `self.__next_f.push(...)` Flight payload (and, on a * dynamically rendered route, a random `self.__next_r="..."` resume token) * into every single response — static, ISR, or dynamic — and neither can be * pinned by a finite set of `sha256` hashes. Next's own nonce mechanism would * avoid `'unsafe-inline'`, but requires every route to render dynamically, * which would drop ISR/CDN caching entirely. * * @param props - Input props. * @returns The `;`-joined directive list. */export function buildContentSecurityPolicy(props: ContentSecurityPolicyInput): string { const convexOrigin = props.convexHost ? ` https://${props.convexHost}` : "" const convexSocket = props.convexHost ? ` wss://${props.convexHost}` : ""
return [ `default-src 'self'`, `script-src 'self' 'unsafe-inline'`, `style-src 'self' 'unsafe-inline'`, `img-src 'self'${convexOrigin}`, `font-src 'self'`, `connect-src 'self'${convexOrigin}${convexSocket}`, `media-src 'self'`, `frame-src 'self'`, `frame-ancestors ${props.frameAncestors}`, `worker-src 'none'`, `base-uri 'self'`, `form-action 'self'`, ].join("; ")}Check your setup with vex doctor
Section titled “Check your setup with vex doctor”npx vex doctorpnpm vex doctoryarn vex doctorbunx vex doctordeno x vex doctorEach line is one step of this guide:
✔— the step is in place.✖— a required step is missing.vex doctorexits1.!— doctor couldn’t confirm the step, for example because an import was renamed. It doesn’t change the exit code.–— an optional piece isn’t set up, or the check couldn’t run.
Doctor only reads files. When CONVEX_DEPLOYMENT is set, it also runs convex env list to check
the deployment’s variables, and prints only their names. It exits 0 when every required step is
in place, 1 when one is missing, and 2 when it can’t read the project. vex dev runs the
same checks, except the deployment one, every time it starts, and prints a single line when a
required step is missing.
For CI and agents, --json prints the full report:
{ "schemaVersion": 1, "ok": false, "checks": [ { "id": "admin-route", "title": "Admin route", "tier": "required", "status": "fail", "detail": "Missing: app/unauthorized/page.tsx", "fix": "Add the files from the guide's \"Admin route\" step.", "docsUrl": "https://docs.vexcms.dev/guides/add-to-existing-app/#admin-route" } ]}Check ids are stable. Run it from another folder with --cwd <dir>.