Skip to content

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.

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

The client auth instance uses createAuthClient from better-auth/react augmented with the @convex-dev/better-auth/client/plugins plugin.

src/lib/auth/client.ts
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 credentials
await authClient.signIn.email({ email, password });
// Terminate session
await authClient.signOut();
// Access active session state
const { data: session, isPending } = authClient.useSession();

The Convex deployment initializes the Better Auth component via createClient, passing a database adapter and event triggers.

convex/auth.ts
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);
},
});

TanStack Start handles HTTP auth endpoints under /api/auth/* through convexBetterAuthReactStart.

src/lib/auth/server.ts
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.


Protected routes enforce authentication state and domain constraints (e.g. completed onboarding) inside the layout’s beforeLoad hook.

src/routes/_protected.tsx
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.