Authentication with Convex, Better Auth and TanStack Start
Integrating authentication across a full-stack React application with Convex and TanStack Start requires coordinating client state, server handlers, database triggers, and route guards. Combining Better Auth with @convex-dev/better-auth bridges reactivity and session validation across both server and client execution contexts.
Overview
Section titled “Overview”The authentication lifecycle spans four layers:
| Layer | Responsibility | Primary File |
|---|---|---|
| Client | React state, sign-in/sign-out methods, active session state | src/lib/auth/client.ts |
| Backend | Database adapter, user triggers, schema auth utilities | convex/auth.ts |
| API Router | Server-side request routing for /api/auth/* endpoints |
src/lib/auth/server.ts |
| Route Guards | Navigation redirection and session enforcement | src/routes/_protected.tsx |
Client Setup
Section titled “Client Setup”The client auth instance uses createAuthClient from better-auth/react augmented with the @convex-dev/better-auth/client/plugins plugin.
import { convexClient } from "@convex-dev/better-auth/client/plugins";import { createAuthClient } from "better-auth/react";
export const authClient = createAuthClient({ plugins: [convexClient()],});Using authClient in components:
import { authClient } from "@/lib/auth/client";
// Sign in with credentialsawait authClient.signIn.email({ email, password });
// Terminate sessionawait authClient.signOut();
// Access active session stateconst { data: session, isPending } = authClient.useSession();Convex Backend Integration
Section titled “Convex Backend Integration”The Convex deployment initializes the Better Auth component via createClient, passing a database adapter and event triggers.
import { createClient } from "@convex-dev/better-auth";import { convex } from "@convex-dev/better-auth/plugins";import { betterAuth } from "better-auth/minimal";
import { requireEnv } from "@/lib/utils";import { components, internal } from "./_generated/api";import authConfig from "./auth.config";import type { DataModel } from "./_generated/dataModel";import type { GenericCtx } from "@convex-dev/better-auth";
const siteUrl = requireEnv("SITE_URL");
export const authComponent = createClient<DataModel>(components.betterAuth, { authFunctions: internal.auth, triggers: { user: { onCreate: async (ctx, doc) => { await ctx.db.insert("profiles", { userId: doc._id, username: "", role: "user", onBoardingCompleted: false, isDeleted: false, }); }, }, },});
export const { onCreate } = authComponent.triggersApi();
export const createAuth = (ctx: GenericCtx<DataModel>) => { return betterAuth({ baseURL: siteUrl, database: authComponent.adapter(ctx), emailAndPassword: { enabled: true, requireEmailVerification: false, }, plugins: [convex({ authConfig })], telemetry: { enabled: false }, });};Retrieving Authenticated Context in Functions
Section titled “Retrieving Authenticated Context in Functions”Inside Convex queries or mutations, authenticate callers using authComponent.getAuthUser(ctx):
import { query } from "./_generated/server";import { authComponent } from "./auth";
export const getCurrentUser = query({ args: {}, handler: async (ctx) => { return await authComponent.getAuthUser(ctx); },});Server HTTP Handler
Section titled “Server HTTP Handler”TanStack Start handles HTTP auth endpoints under /api/auth/* through convexBetterAuthReactStart.
import { convexBetterAuthReactStart } from "@convex-dev/better-auth/react-start";import { requireEnv } from "@/lib/utils";
export const { handler, getToken, fetchAuthQuery, fetchAuthMutation, fetchAuthAction,} = convexBetterAuthReactStart({ convexUrl: requireEnv("VITE_CONVEX_URL"), convexSiteUrl: requireEnv("VITE_CONVEX_SITE_URL"),});The route file at src/routes/api/auth/$.ts delegates incoming requests directly to handler.
Route Guards with TanStack Router
Section titled “Route Guards with TanStack Router”Protected routes enforce authentication state and domain constraints (e.g. completed onboarding) inside the layout’s beforeLoad hook.
import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";import { convexQuery } from "@convex-dev/react-query";import { api } from "@/convex/_generated/api";
export const Route = createFileRoute("/_protected")({ beforeLoad: async ({ context }) => { if (!context.isAuthenticated) { throw redirect({ to: "/signin" }); }
const profile = await context.queryClient.fetchQuery( convexQuery(api.profiles.getProfile) );
if (!profile?.onBoardingCompleted) { throw redirect({ to: "/onboarding" }); } }, component: ProtectedLayout,});Want help with this in your own project? See my services: TypeScript development, React development.