### Navigate to example directory and install dependencies Source: https://github.com/get-convex/better-auth/blob/main/examples/tanstack/README.md Changes to the TanStack example directory and installs example-specific dependencies. This prepares the example application for local development. ```bash cd examples/tanstack npm install ``` -------------------------------- ### Navigate to example and install dependencies Source: https://github.com/get-convex/better-auth/blob/main/examples/README.md Change to a specific example directory and install its dependencies. ```bash cd examples/ npm install ``` -------------------------------- ### Setup React Example Dependencies Source: https://github.com/get-convex/better-auth/blob/main/examples/react/README.md Navigates into the specific React example directory and installs its local dependencies. This step is required before running the example application. ```bash cd examples/react npm install ``` -------------------------------- ### Install root dependencies with npm Source: https://github.com/get-convex/better-auth/blob/main/examples/tanstack/README.md Installs all root-level project dependencies required for the Convex + Better Auth + TanStack Start integration. This is the first step in setting up the project environment. ```bash npm install ``` -------------------------------- ### Navigate to Example and Install Dependencies Source: https://github.com/get-convex/better-auth/blob/main/examples/next/README.md Changes the directory to the Next.js example and installs its specific dependencies. ```bash cd examples/next npm install ``` -------------------------------- ### Run Better Auth Convex locally Source: https://github.com/get-convex/better-auth/blob/main/CONTRIBUTING.md Install dependencies in the root and example directories, then start the Convex development server. ```sh npm i cd example npm i npx convex dev ``` -------------------------------- ### Start development server Source: https://github.com/get-convex/better-auth/blob/main/examples/tanstack/README.md Runs the development server for the TanStack Start application with hot-reload enabled. This starts the local development environment for testing and development. ```bash npm run dev ``` -------------------------------- ### Initialize Convex database Source: https://github.com/get-convex/better-auth/blob/main/examples/tanstack/README.md Initializes the Convex database for the first time using the dev command with the --once flag. This sets up the backend database schema and configuration. ```bash npx convex dev --once ``` -------------------------------- ### Initialize Convex Database Source: https://github.com/get-convex/better-auth/blob/main/examples/next/README.md Initializes the Convex database for the first time setup of the example project. ```bash npx convex dev --once ``` -------------------------------- ### Start Convex Development Server Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/index.mdx Run the Convex CLI development server to initialize your Convex deployment and keep generated types current during development. This command should be kept running throughout the setup process. ```bash npx convex dev ``` -------------------------------- ### Run Next.js Development Server Source: https://github.com/get-convex/better-auth/blob/main/examples/next/README.md Starts the Next.js development server to run the example application locally. ```bash npm run dev ``` -------------------------------- ### Initialize Convex Project with npm Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/index.mdx Create a new Convex project using npm create command. This sets up the initial Convex project structure and configuration needed before integrating Better Auth. ```bash npm create convex@latest ``` -------------------------------- ### Set Up TanStack Start Auth Route Handler Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/tanstack-start.mdx Configures a TanStack Start route handler to proxy GET and POST authentication requests to the Convex deployment. ```typescript import { createFileRoute } from '@tanstack/react-router' import { handler } from '~/lib/auth-server' export const Route = createFileRoute('/api/auth/$')({ server: { handlers: { GET: ({ request }) => handler(request), POST: ({ request }) => handler(request), }, }, }) ``` -------------------------------- ### Watch and rebuild component changes Source: https://github.com/get-convex/better-auth/blob/main/examples/tanstack/README.md Runs the build watch task in a separate terminal to automatically rebuild the Better Auth component when source files change. This enables real-time component development without manual rebuilds. ```bash npm run build:watch ``` -------------------------------- ### Install Root Dependencies Source: https://github.com/get-convex/better-auth/blob/main/examples/next/README.md Installs the base dependencies required for the entire repository. ```bash npm install ``` -------------------------------- ### Install Convex and SvelteKit integration package Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/sveltekit.mdx Installs the core Convex client library and the community-maintained SvelteKit adapter package for Convex. ```npm npm install convex @mmailaender/convex-svelte ``` -------------------------------- ### Test and lint the project Source: https://github.com/get-convex/better-auth/blob/main/CONTRIBUTING.md Build the project, run type checks and tests, and perform linting within the example directory. ```sh rm -rf dist/ && npm run build npm run typecheck npm run test cd example npm run lint cd .. ``` -------------------------------- ### Run Development Server with npm, pnpm, or yarn Source: https://github.com/get-convex/better-auth/blob/main/docs/README.md Start the Next.js development server using one of the three package managers. Choose the command based on your project's package manager. ```bash npm run dev ``` ```bash pnpm dev ``` ```bash yarn dev ``` -------------------------------- ### Install Better Auth and SvelteKit Packages Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/sveltekit.mdx Installs the necessary npm packages for Better Auth, its Svelte component, and ensures Convex is up-to-date. Requires Convex `1.25.0` or later. ```npm npm install @convex-dev/better-auth @mmailaender/convex-better-auth-svelte npm install better-auth@~1.6.15 ``` -------------------------------- ### Install Convex and Better Auth Packages Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/expo.mdx Installs the core Convex and Better Auth packages, including specific versions for Better Auth components, as a prerequisite for integration. ```npm npm install convex@latest @convex-dev/better-auth npm install better-auth@~1.6.15 @better-auth/expo@~1.6.15 ``` -------------------------------- ### Initialize Better Auth client and instance Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/react.mdx Creates a Better Auth client and initializes the `betterAuth` instance with Convex and cross-domain plugins. This setup enables email/password authentication without verification. ```ts import { createClient, type GenericCtx } from "@convex-dev/better-auth"; import { convex, crossDomain } from "@convex-dev/better-auth/plugins"; import { components } from "./_generated/api"; import { DataModel } from "./_generated/dataModel"; import { query } from "./_generated/server"; import { betterAuth, type BetterAuthOptions } from "better-auth/minimal"; import authConfig from "./auth.config"; const siteUrl = process.env.SITE_URL!; // The component client has methods needed for integrating Convex with Better Auth, // as well as helper methods for general use. export const authComponent = createClient(components.betterAuth); export const createAuth = (ctx: GenericCtx) => { return betterAuth({ baseURL: process.env.CONVEX_SITE_URL, // [!code ++] trustedOrigins: [siteUrl], database: authComponent.adapter(ctx), // Configure simple, non-verified email/password to get started emailAndPassword: { enabled: true, requireEmailVerification: false, }, plugins: [ // The cross domain plugin is required for client side frameworks crossDomain({ siteUrl }), // The Convex plugin is required for Convex compatibility convex({ authConfig }), ], }); } ``` -------------------------------- ### Refactor Convex Plugin Configuration Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/migrations/migrate-to-0-8.mdx Shows how to simplify Better Auth setup by removing the separate options parameter from the Convex plugin. The createAuth function now directly passes configuration to betterAuth() with the convex() plugin, eliminating the need for separated option handling. ```typescript export const createAuth = (ctx: GenericCtx) => { return betterAuth({ baseURL: siteUrl, database: authComponent.adapter(ctx), plugins: [ // ...plugins convex(), ], }); }; ``` -------------------------------- ### SSR with TanStack Query in TanStack Start Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/tanstack-start.mdx Demonstrates how to use `ensureQueryData` and `useSuspenseQuery` with `convexQuery` for server-side rendering of Convex data in a TanStack Start route loader. Requires `expectAuth: true` in `ConvexQueryClient` for seamless initial render. ```tsx import { createFileRoute } from "@tanstack/react-router"; import { api } from "~/convex/_generated/api"; import { convexQuery } from "@convex-dev/react-query"; import { useSuspenseQuery } from "@tanstack/react-query"; export const Route = createFileRoute("/")({ component: App, loader: async ({ context }) => { await Promise.all([ context.queryClient.ensureQueryData( convexQuery(api.auth.getCurrentUser, {}) ), // Load multiple queries in parallel if needed ]); }, }); ``` -------------------------------- ### Update Route Handlers for Next.js and TanStack Start Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/migrations/migrate-to-0-10.mdx This snippet illustrates how to update your framework's route handler file to utilize the new unified authentication handler. For Next.js, it replaces the direct `nextJsHandler()` call with the `handler` exported from your `lib/auth-server` file. For TanStack Start, it updates the `GET` and `POST` server handlers to use the new `handler` function, ensuring consistent authentication processing across your application. ```ts import { handler } from "@/lib/auth-server"; export const { GET, POST } = handler; ``` ```ts import { createFileRoute } from '@tanstack/react-router' import { handler } from '~/lib/auth-server' export const Route = createFileRoute('/api/auth/$')({ server: { handlers: { GET: ({ request }) => handler(request), POST: ({ request }) => handler(request), }, }, }) ``` -------------------------------- ### Create component definition file Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/features/local-install.mdx Define the Better Auth component in its own Convex subdirectory. This signals to Convex that the directory is a locally installed component. ```typescript import { defineComponent } from "convex/server"; const component = defineComponent("betterAuth"); export default component; ``` -------------------------------- ### Regenerate schema for Local Install Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/migrations/migrate-to-0-11.mdx Navigate to the Better Auth directory and use the CLI to regenerate the schema. This is a required step for applications using the Local Install method after updating dependencies. ```bash cd convex/betterAuth npx @better-auth/cli generate -y ``` -------------------------------- ### Initialize Better Auth with Convex Database Adapter Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/api/component-client.mdx Demonstrates how to use the adapter() method to connect Better Auth to the Convex database. This setup requires the Convex data model and context to provide the necessary database interface for Better Auth. ```ts import { createClient } from "@convex-dev/better-auth"; import { components } from "./_generated/api"; import { type GenericCtx } from "./_generated/server"; import { DataModel } from "./_generated/dataModel"; export const authComponent = createClient(components.betterAuth); export const createAuth = (ctx: GenericCtx) => { return betterAuth({ database: authComponent.adapter(ctx), }); }; ``` -------------------------------- ### Install Better Auth 0.9 dependencies Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/migrations/migrate-to-0-9/index.mdx Update the @convex-dev/better-auth component and the core better-auth package to the required versions for this release. ```bash npm install @convex-dev/better-auth@0.9 npm install better-auth@1.3.34 --save-exact ``` -------------------------------- ### Install Expo Secure Store Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/expo.mdx Installs `expo-secure-store`, a required dependency for secure cookie storage when using Better Auth in Expo applications. ```npm npx expo install expo-secure-store ``` -------------------------------- ### Configure TanStack Start Router for Convex Auth Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/migrations/migrate-to-0-10.mdx Updates the router configuration to set expectAuth: true on the ConvexQueryClient, ensuring authenticated data from server rendering is preserved. ```tsx export function getRouter() { const convexUrl = (import.meta as any).env.VITE_CONVEX_URL!; if (!convexUrl) { throw new Error("VITE_CONVEX_URL is not set"); } const convexQueryClient = new ConvexQueryClient(convexUrl, { expectAuth: true, }); const queryClient: QueryClient = new QueryClient({ defaultOptions: { queries: { queryKeyHashFn: convexQueryClient.hashFn(), queryFn: convexQueryClient.queryFn(), }, }, }); convexQueryClient.connect(queryClient); const router = createTanStackRouter({ routeTree, defaultPreload: "intent", defaultErrorComponent: DefaultCatchBoundary, defaultNotFoundComponent: () => , context: { queryClient, convexQueryClient }, scrollRestoration: true, }); setupRouterSsrQueryIntegration({ router, queryClient, }); return router; } ``` -------------------------------- ### Install Better Auth Dependencies Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/migrations/migrate-to-0-12.mdx Update Better Auth and its component. Better Auth must be on `1.6.9` or later in the `1.6.x` line. ```npm npm install @convex-dev/better-auth@^0.12.0 npm install better-auth@~1.6.15 ``` -------------------------------- ### Call Convex Better Auth Mutation from TanStack Start Server Action Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/tanstack-start.mdx Shows how to invoke the Convex mutation (`api.users.updatePassword`) from a TanStack Start server action using `fetchAuthMutation` to update user passwords. ```ts import { createServerFn } from "@tanstack/react-start"; import { fetchAuthMutation } from "@/lib/auth-server"; import { api } from "../../convex/_generated/api"; export const updatePassword = createServerFn({ method: "POST" }).handler( async ({ data: { currentPassword, newPassword } }) => { await fetchAuthMutation(api.users.updatePassword, { currentPassword, newPassword, }); } ); ``` -------------------------------- ### Run Build Watch Task for Component Changes Source: https://github.com/get-convex/better-auth/blob/main/examples/next/README.md Starts a watch task that automatically rebuilds components when changes are detected, useful during active development. ```bash npm run build:watch ``` -------------------------------- ### Configure TanStack Router with Convex for SSR and Auth Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/tanstack-start.mdx Illustrates the integration of Convex with TanStack Router, showing modifications to `getRouter` for `ConvexQueryClient` setup, context provision, and `ConvexProvider` wrapping, including SSR query integration. ```ts import { createRouter } from '@tanstack/react-router' import { QueryClient } from '@tanstack/react-query' // [!code ++:2] // You may need to install this package if you haven't already import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query' import { routerWithQueryClient } from '@tanstack/react-router-with-query' // [!code --] import { ConvexQueryClient } from '@convex-dev/react-query' import { ConvexProvider } from 'convex/react' // [!code --] import { routeTree } from './routeTree.gen' export function getRouter() { if (typeof document !== 'undefined') { notifyManager.setScheduler(window.requestAnimationFrame) } const convexUrl = (import.meta as any).env.VITE_CONVEX_URL! if (!convexUrl) { throw new Error('VITE_CONVEX_URL is not set') } const convexQueryClient = new ConvexQueryClient(convexUrl) // [!code --] // [!code ++:3] const convexQueryClient = new ConvexQueryClient(convexUrl, { expectAuth: true, }) const queryClient: QueryClient = new QueryClient({ defaultOptions: { queries: { queryKeyHashFn: convexQueryClient.hashFn(), queryFn: convexQueryClient.queryFn(), }, }, }) convexQueryClient.connect(queryClient) // [!code --:2] const router = routerWithQueryClient( createRouter({ // [!code ++] const router = createRouter({ routeTree, defaultPreload: 'intent', context: { queryClient }, // [!code --] context: { queryClient, convexQueryClient }, // [!code ++] scrollRestoration: true, defaultErrorComponent: (err) =>

{err.error.stack}

, defaultNotFoundComponent: () =>

not found

, // [!code --:5] Wrap: ({ children }) => ( {children} ), }) // [!code ++:4] setupRouterSsrQueryIntegration({ router, queryClient, }) return router } ``` -------------------------------- ### Update Convex Better Auth Server Utilities for Next.js and TanStack Start Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/migrations/migrate-to-0-10.mdx This snippet demonstrates how to refactor your `auth-server` utility file to use the new `convexBetterAuthNextJs` or `convexBetterAuthReactStart` functions. It replaces individual imports and function calls with a single, comprehensive export that includes various authentication utilities like `handler`, `preloadAuthQuery`, and `fetchAuthQuery`. The configuration requires explicit `convexUrl` and `convexSiteUrl` environment variables for robust runtime validation. ```ts import { convexBetterAuthNextJs } from "@convex-dev/better-auth/nextjs"; export const { handler, preloadAuthQuery, isAuthenticated, getToken, fetchAuthQuery, fetchAuthMutation, fetchAuthAction, } = convexBetterAuthNextJs({ convexUrl: process.env.NEXT_PUBLIC_CONVEX_URL!, convexSiteUrl: process.env.NEXT_PUBLIC_CONVEX_SITE_URL!, }); ``` ```ts import { convexBetterAuthReactStart } from "@convex-dev/better-auth/react-start"; export const { handler, getToken, fetchAuthQuery, fetchAuthMutation, fetchAuthAction, } = convexBetterAuthReactStart({ convexUrl: process.env.VITE_CONVEX_URL!, convexSiteUrl: process.env.VITE_CONVEX_SITE_URL!, }); ``` -------------------------------- ### Handle Sign Out with Page Reload in TanStack Start Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/tanstack-start.mdx Provides a recommended approach for signing out when `expectAuth: true` is enabled, ensuring proper re-authentication by reloading the page after `authClient.signOut`. ```ts import { authClient } from "~/lib/auth-client"; const handleSignOut = async () => { await authClient.signOut({ fetchOptions: { onSuccess: () => { location.reload(); }, }, }, }; ``` -------------------------------- ### Wrap Authenticated Route with AuthBoundary - TanStack Start Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/experimental.mdx TanStack Start file route that wraps authenticated routes with ClientAuthBoundary. Uses beforeLoad hook for server-side authentication validation and redirects unauthenticated users. ```typescript import { createFileRoute, Outlet, redirect } from '@tanstack/react-router' import { ClientAuthBoundary } from '@/lib/auth-client' export const Route = createFileRoute("/_authed")({ beforeLoad: ({ context }) => { if (!context.isAuthenticated) { console.log("redirecting to /sign-in"); throw redirect({ to: "/sign-in" }); } }, component: () => { return ( ); }, }); ``` -------------------------------- ### Install Better Auth Dependencies (npm) Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/migrations/migrate-to-0-10.mdx Update Better Auth and its component dependencies to the specified versions. This ensures compatibility and leverages new features. Review breaking changes for Better Auth 1.4 before upgrading. ```npm npm install @convex-dev/better-auth@^0.10.0 npm install better-auth@1.4.9 --save-exact ``` -------------------------------- ### Pass Initial Token to ConvexBetterAuthProvider Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/migrations/migrate-to-0-10.mdx Speeds up client-side authentication by passing an initial token fetched on the server to the ConvexBetterAuthProvider. This implementation covers the Provider and Layout updates for Next.js and the Root Component for TanStack Start. ```tsx export function ConvexClientProvider({ children, initialToken, }: { children: ReactNode; initialToken?: string | null; }) { return ( {children} ); } ``` ```tsx import { getToken } from "@/lib/auth-server"; import { ConvexClientProvider } from "./ConvexClientProvider"; import { PropsWithChildren } from "react"; export default async function RootLayout({ children }: PropsWithChildren) { const token = await getToken(); return ( {children} ); } ``` ```tsx function RootComponent() { const context = useRouteContext({ from: Route.id }) return ( ) } ``` -------------------------------- ### Set Up Next.js Route Handler for Better Auth Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/next.mdx This snippet creates a Next.js route handler to proxy authentication requests from Next.js to your Convex deployment. It exports GET and POST methods from the `auth-server` handler. ```ts import { handler } from "@/lib/auth-server"; export const { GET, POST } = handler; ``` -------------------------------- ### Update Vite Configuration for TanStack Start SSR Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/migrations/migrate-to-0-10.mdx Configures Vite to bundle @convex-dev/better-auth during Server-Side Rendering (SSR) to avoid module resolution issues. ```ts export default defineConfig({ // ...other config ssr: { noExternal: ["@convex-dev/better-auth"], }, }); ``` -------------------------------- ### Update dependencies for Better Auth 0.11 Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/migrations/migrate-to-0-11.mdx Install the latest version of the Convex Better Auth component and the core Better Auth package. Users should also review breaking changes in Better Auth 1.5. ```bash npm install @convex-dev/better-auth@^0.11.0 npm install better-auth ``` -------------------------------- ### Implement changePassword Server Method with Better Auth and Convex Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/basic-usage/index.mdx Demonstrates how to use Better Auth's server-side `auth.api.changePassword` method within a Convex mutation. The example shows retrieving authenticated user context via `authComponent.getAuth()` and passing required headers for session validation. This pattern applies to other Better Auth server methods requiring authenticated users. ```typescript export const updateUserPassword = mutation({ args: { currentPassword: v.string(), newPassword: v.string(), }, handler: async (ctx, args) => { // Many Better Auth server methods require a currently authenticated // user, so request headers have to be passed in so session cookies // can be parsed and validated. The `getAuth` method provides both the // auth object and headers for convenience. const { auth, headers } = await authComponent.getAuth(createAuth, ctx); await auth.api.changePassword({ body: { currentPassword: args.currentPassword, newPassword: args.newPassword, }, headers, }); }, }); ``` -------------------------------- ### Configure Authentication Options with Action Context in TypeScript Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/api/type-utilities.mdx This TypeScript example demonstrates how to set up authentication options, including an email verification flow using the Resend integration. It utilizes the `requireActionCtx` type guard to ensure the Convex context (`ctx`) is an action context, which is necessary for performing network requests like sending emails. The snippet showcases dependencies on `@convex-dev/better-auth/utils`, `@convex-dev/resend`, and Convex's generated API types. ```ts import { requireActionCtx } from "@convex-dev/better-auth/utils"; import { type GenericCtx } from "@convex-dev/better-auth"; import { Resend } from "@convex-dev/resend"; import { components } from "./_generated/api"; import { type DataModel } from "./_generated/dataModel"; export const resend = new Resend(components.resend); export const createAuthOptions = (ctx: GenericCtx) => ({ baseURL: siteUrl, sendVerificationEmail: async ({ user, url }) => { // This function only requires a `runMutation` property on the ctx object, // but we'll make sure we have an action ctx because we know a network // request is being made, which requires an action ctx. await resend.sendEmail(requireActionCtx(ctx), { to: user.email, subject: "Verify your email", html: `

Click here to verify your email

`, }); }, }); ``` -------------------------------- ### Configure Custom Base Path for Convex Plugin Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/api/convex-plugin.mdx This example illustrates how to specify a custom `basePath` for Better Auth within the Convex plugin. This is crucial if your Better Auth configuration uses a non-default path, ensuring that the JWKS endpoint is correctly configured and accessible at the specified custom path. ```ts convex({ authConfig, options: { basePath: "/custom/auth/path", }, }); ``` -------------------------------- ### Build a one-off package Source: https://github.com/get-convex/better-auth/blob/main/CONTRIBUTING.md Clean the distribution folder, build the project, and create a tarball for local testing. ```sh rm -rf dist/ && npm run build npm pack ``` -------------------------------- ### Install Better Auth and Convex Component Updates Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/migrations/migrate-to-0-8.mdx Update the Better Auth package and Convex Better Auth component to their latest versions. This ensures compatibility with the new createClient API and trigger-based hooks system. ```npm npm install @convex-dev/better-auth@0.8 npm install better-auth@1.3.8 --save-exact ``` -------------------------------- ### Configure .env.local for Convex Deployments Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/next.mdx Sets up the `.env.local` file with necessary environment variables for both cloud and self-hosted Convex deployments, including Convex and site URLs for the Next.js framework. ```shell # Deployment used by \`npx convex dev\` CONVEX_DEPLOYMENT=dev:adjective-animal-123 # team: team-name, project: project-name NEXT_PUBLIC_CONVEX_URL=https://adjective-animal-123.convex.cloud # Same as NEXT_PUBLIC_CONVEX_URL but ends in .site // [!code ++] NEXT_PUBLIC_CONVEX_SITE_URL=https://adjective-animal-123.convex.site # [!code ++] # Your local site URL // [!code ++] NEXT_PUBLIC_SITE_URL=http://localhost:3000 # [!code ++] ``` ```shell # Deployment used by \`npx convex dev\` CONVEX_DEPLOYMENT=dev:adjective-animal-123 # team: team-name, project: project-name NEXT_PUBLIC_CONVEX_URL=http://127.0.0.1:3210 # Will generally be one number higher than NEXT_PUBLIC_CONVEX_URL, # so if your convex url is :3212, your site url will be :3213 NEXT_PUBLIC_CONVEX_SITE_URL=http://127.0.0.1:3211 # [!code ++] # Your local site URL // [!code ++] NEXT_PUBLIC_SITE_URL=http://localhost:3000 # [!code ++] ``` -------------------------------- ### Install Convex and Better Auth packages Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/react.mdx Installs the necessary Convex and Better Auth packages for your React project. This component requires Convex `1.25.0` or later. ```npm npm install convex@latest @convex-dev/better-auth npm install better-auth@~1.6.15 ``` -------------------------------- ### Create and initialize Better Auth instance Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/tanstack-start.mdx Create a Better Auth client and an instance of `betterAuth` in `convex/auth.ts`, configuring it for Convex compatibility and email/password authentication. ```ts import { betterAuth } from 'better-auth/minimal' import { createClient } from '@convex-dev/better-auth' import { convex } from '@convex-dev/better-auth/plugins' import authConfig from './auth.config' import { components } from './_generated/api' import { query } from './_generated/server' import type { GenericCtx } from '@convex-dev/better-auth' import type { DataModel } from './_generated/dataModel' const siteUrl = process.env.SITE_URL! // The component client has methods needed for integrating Convex with Better Auth, // as well as helper methods for general use. export const authComponent = createClient(components.betterAuth) export const createAuth = (ctx: GenericCtx) => { return betterAuth({ baseURL: siteUrl, database: authComponent.adapter(ctx), // Configure simple, non-verified email/password to get started emailAndPassword: { enabled: true, requireEmailVerification: false, }, plugins: [ // The Convex plugin is required for Convex compatibility convex({ authConfig }), ], }) } ``` -------------------------------- ### Create Better Auth Client for SvelteKit Frontend Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/sveltekit.mdx Initializes a Better Auth client instance for use in your SvelteKit frontend. This client facilitates interaction with the Better Auth server from the client-side application. ```ts import { createAuthClient } from 'better-auth/svelte'; import { convexClient } from "@convex-dev/better-auth/client/plugins"; export const authClient = createAuthClient({ plugins: [convexClient()], }); ``` -------------------------------- ### Install Convex Migrations Component Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/migrations/migrate-to-0-9/migrate-userid/userid-in-app-table.mdx This command installs the `@convex-dev/migrations` package, which provides utilities for managing data migrations in a Convex application. ```npm npm install @convex-dev/migrations ``` -------------------------------- ### Regenerate Schema for Local Install Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/migrations/migrate-to-0-12.mdx Regenerate the schema whenever updating Better Auth with Local Install. The CLI command has changed from `npx @better-auth/cli generate` to `npx auth generate`. ```npm cd convex/betterAuth npx auth generate ``` -------------------------------- ### Run Convex development command Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/sveltekit.mdx Executes the Convex development command to log in, create a project, and continuously sync backend functions with your dev deployment. ```bash npx convex dev ``` -------------------------------- ### Deploy a new version to npm Source: https://github.com/get-convex/better-auth/blob/main/CONTRIBUTING.md Increment the version, perform a dry run to verify files, publish to npm, and push tags to git. ```sh # this will change the version and commit it (if you run it in the root directory) npm version patch npm publish --dry-run # sanity check files being included npm publish git push --tags ``` -------------------------------- ### Configure ClientAuthBoundary Component - TanStack Start Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/experimental.mdx Client component wrapper for AuthBoundary in TanStack Start applications. Similar to Next.js version but uses TanStack Router's useNavigate hook for navigation. ```typescript "use client"; import { useNavigate } from "@tanstack/react-router"; import { AuthBoundary } from "@convex-dev/better-auth/react"; import { api } from "@/convex/_generated/api"; import { isAuthError } from "@/lib/utils"; import { authClient } from "@/lib/auth-client"; export const ClientAuthBoundary = ({ children }: PropsWithChildren) => { const navigate = useNavigate(); return ( navigate({ to: "/sign-in" })} getAuthUserFn={api.auth.getAuthUser} isAuthError={isAuthError} > {children} ); }; ``` -------------------------------- ### Configure .env.local for Cloud deployment Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/react.mdx Adds necessary environment variables to `.env.local` for a Convex Cloud deployment, including `VITE_CONVEX_SITE_URL` and `VITE_SITE_URL`. ```shell # Deployment used by \`npx convex dev\` CONVEX_DEPLOYMENT=dev:adjective-animal-123 # team: team-name, project: project-name VITE_CONVEX_URL=https://adjective-animal-123.convex.cloud # Same as VITE_CONVEX_URL but ends in .site // [!code ++] VITE_CONVEX_SITE_URL=https://adjective-animal-123.convex.site # [!code ++] # Your local site URL // [!code ++] VITE_SITE_URL=http://localhost:5173 # [!code ++] ``` -------------------------------- ### Initialize Convex Client with Better Auth in SvelteKit Layout Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/sveltekit.mdx Initializes the Convex client with Better Auth in your SvelteKit application's root layout. Note that `createSvelteAuthClient` already includes `setupConvex()`. ```svelte {@render children?.()} ``` -------------------------------- ### Update component registration in convex.config.ts Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/features/local-install.mdx Replace the imported Better Auth component from the package with the locally installed component from the convex/betterAuth directory. ```typescript import { defineApp } from "convex/server"; import betterAuth from "@convex-dev/better-auth/convex.config"; // [!code --] import betterAuth from "./betterAuth/convex.config"; // [!code ++] const app = defineApp(); app.use(betterAuth); export default app; ``` -------------------------------- ### Create Better Auth Client Instance Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/react.mdx Initializes the Better Auth client for client-side interaction with the Better Auth server. It configures the base URL and integrates Convex and cross-domain plugins. ```typescript import { createAuthClient } from "better-auth/react"; import { convexClient, crossDomainClient, } from "@convex-dev/better-auth/client/plugins"; export const authClient = createAuthClient({ baseURL: import.meta.env.VITE_CONVEX_SITE_URL, plugins: [convexClient(), crossDomainClient()], }); ``` -------------------------------- ### Configure .env.local for Self-hosted deployment Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/react.mdx Adds necessary environment variables to `.env.local` for a self-hosted Convex deployment, including `VITE_CONVEX_SITE_URL` and `VITE_SITE_URL`. ```shell # Deployment used by \`npx convex dev\` CONVEX_DEPLOYMENT=dev:adjective-animal-123 # team: team-name, project: project-name VITE_CONVEX_URL=http://127.0.0.1:3210 # Will generally be one number higher than VITE_CONVEX_URL, # so if your convex url is :3212, your site url will be :3213 VITE_CONVEX_SITE_URL=http://127.0.0.1:3211 # [!code ++] # Your local site URL // [!code ++] VITE_SITE_URL=http://localhost:5173 # [!code ++] ``` -------------------------------- ### Create Better Auth Client Instance Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/tanstack-start.mdx Initializes the Better Auth client for client-side interactions, integrating with Convex via a plugin. ```typescript import { createAuthClient } from 'better-auth/react' import { convexClient } from '@convex-dev/better-auth/client/plugins' export const authClient = createAuthClient({ plugins: [convexClient()], }) ``` -------------------------------- ### Initialize Better Auth Instance and Client Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/expo.mdx Initializes the Better Auth server-side instance and client in `convex/auth.ts`, configuring trusted origins, database adapter, email/password settings, and required Expo and Convex plugins. ```ts import { createClient, type GenericCtx } from "@convex-dev/better-auth"; import { convex } from "@convex-dev/better-auth/plugins"; import { betterAuth, type BetterAuthOptions } from "better-auth/minimal"; import { expo } from '@better-auth/expo' import { components } from "./_generated/api"; import { DataModel } from "./_generated/dataModel"; import { query } from "./_generated/server"; import authConfig from "./auth.config"; // The component client has methods needed for integrating Convex with Better Auth, // as well as helper methods for general use. export const authComponent = createClient(components.betterAuth); export const createAuth = (ctx: GenericCtx) => { return betterAuth({ trustedOrigins: ["your-scheme://"], database: authComponent.adapter(ctx), // Configure simple, non-verified email/password to get started emailAndPassword: { enabled: true, requireEmailVerification: false, }, plugins: [ // The Expo and Convex plugins are required expo(), convex({ authConfig }), ], }) } // Example function for getting the current user // Feel free to edit, omit, etc. export const getCurrentUser = query({ args: {}, handler: async (ctx) => { return authComponent.getAuthUser(ctx); }, }); ``` -------------------------------- ### Generate and set Better Auth secret Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/react.mdx Generates a secret for encryption and hashing, then sets it as a Convex environment variable. This command requires openssl to be installed. ```shell npx convex env set BETTER_AUTH_SECRET=$(openssl rand -base64 32) ``` -------------------------------- ### Get Auth State in SvelteKit Layout Server Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/sveltekit.mdx Use `getAuthState` in your `+layout.server.ts` to synchronously determine authentication status during SSR. No arguments are needed if `withServerConvexToken` is configured. ```typescript import type { LayoutServerLoad } from "./$types"; import { getAuthState } from "@mmailaender/convex-better-auth-svelte/sveltekit"; export const load: LayoutServerLoad = () => { return { authState: getAuthState() }; // synchronous, no await needed }; ``` -------------------------------- ### Configure SvelteKit Client to Expect Authentication Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/sveltekit.mdx This snippet shows how to configure `createSvelteAuthClient` with `expectAuth: true` in `options` to ensure all Convex queries and mutations automatically include the auth token and only run after user authentication. ```typescript import { createSvelteAuthClient } from "@mmailaender/convex-better-auth-svelte/svelte"; import { authClient } from "$lib/auth-client"; createSvelteAuthClient({ authClient, options: { expectAuth: true, }, }); ``` -------------------------------- ### Set Up SvelteKit Auth Route Handlers Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/sveltekit.mdx Configures SvelteKit route handlers to proxy authentication requests from your framework server to your Convex deployment. ```ts import { createSvelteKitHandler } from '@mmailaender/convex-better-auth-svelte/sveltekit'; export const { GET, POST } = createSvelteKitHandler(); ``` -------------------------------- ### Initialize Better Auth Instance in Convex Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/next.mdx Creates and initializes a Better Auth instance within `convex/auth.ts`, configuring it with a base URL, database adapter, email/password settings, and the Convex plugin for compatibility. ```ts import { createClient, type GenericCtx } from "@convex-dev/better-auth"; import { convex } from "@convex-dev/better-auth/plugins"; import { components } from "./_generated/api"; import { DataModel } from "./_generated/dataModel"; import { query } from "./_generated/server"; import { betterAuth } from "better-auth/minimal"; import authConfig from "./auth.config"; const siteUrl = process.env.SITE_URL!; // The component client has methods needed for integrating Convex with Better Auth, // as well as helper methods for general use. export const authComponent = createClient(components.betterAuth); export const createAuth = (ctx: GenericCtx) => { return betterAuth({ baseURL: siteUrl, database: authComponent.adapter(ctx), // Configure simple, non-verified email/password to get started emailAndPassword: { enabled: true, requireEmailVerification: false, }, plugins: [ // The Convex plugin is required for Convex compatibility convex({ authConfig }), ], }) } // Example function for getting the current user // Feel free to edit, omit, etc. export const getCurrentUser = query({ args: {}, handler: async (ctx) => { return authComponent.getAuthUser(ctx); }, }); ``` -------------------------------- ### Configure Environment Variables for Expo Deployments Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/expo.mdx Sets essential environment variables in `.env.local` for Convex deployments, including `CONVEX_DEPLOYMENT`, `EXPO_PUBLIC_CONVEX_URL`, and `EXPO_PUBLIC_CONVEX_SITE_URL`. ```shell # Deployment used by \`npx convex dev\` CONVEX_DEPLOYMENT=dev:adjective-animal-123 # team: team-name, project: project-name EXPO_PUBLIC_CONVEX_URL=https://adjective-animal-123.convex.cloud # Same as EXPO_PUBLIC_CONVEX_URL but ends in .site // [!code ++] EXPO_PUBLIC_CONVEX_SITE_URL=https://adjective-animal-123.convex.site # [!code ++] ``` ```shell # Deployment used by \`npx convex dev\` CONVEX_DEPLOYMENT=dev:adjective-animal-123 # team: team-name, project: project-name EXPO_PUBLIC_CONVEX_URL=http://127.0.0.1:3210 # Will generally be one number higher than EXPO_PUBLIC_CONVEX_URL, # so if your convex url is :3212, your site url will be :3213 EXPO_PUBLIC_CONVEX_SITE_URL=http://127.0.0.1:3211 # [!code ++] ``` -------------------------------- ### Set JWKS Environment Variable via CLI Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/experimental.mdx Executes the internal mutation to get the JWKS and stores the result in a Convex environment variable using the CLI. ```bash npx convex run auth:getLatestJwks | npx convex env set JWKS ``` -------------------------------- ### Initialize Better Auth Client for React Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/next.mdx This snippet initializes the Better Auth client for React applications, integrating it with Convex using the `convexClient` plugin. Use this to set up client-side authentication capabilities. ```ts import { createAuthClient } from "better-auth/react"; import { convexClient } from "@convex-dev/better-auth/client/plugins"; export const authClient = createAuthClient({ plugins: [convexClient()], }); ``` -------------------------------- ### Prefetch User Data in SvelteKit Layout Server Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/sveltekit.mdx Prefetch user data on the server in `+layout.server.ts` using `createConvexHttpClient` and `api.auth.getCurrentUser` to prevent content flashes. This ensures `currentUser` is available for authenticated users. ```typescript import type { LayoutServerLoad } from "./$types"; import { api } from "$convex/_generated/api"; import { createConvexHttpClient, getAuthState } from "@mmailaender/convex-better-auth-svelte/sveltekit"; export const load: LayoutServerLoad = async () => { const authState = getAuthState(); if (!authState.isAuthenticated) { return { authState, currentUser: null }; } const client = createConvexHttpClient(); try { const currentUser = await client.query(api.auth.getCurrentUser, {}); return { authState, currentUser }; } catch { return { authState, currentUser: null }; } }; ``` -------------------------------- ### Configure JWT Caching for Server Utilities Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/experimental.mdx Enables JWT caching in server-side utilities for Next.js or TanStack Start to reuse Convex JWTs from request cookies, improving SSR performance. ```next-js import { convexBetterAuthNextJs } from "@convex-dev/better-auth/nextjs"; import { isAuthError } from "@/lib/utils"; export const { fetchAuthQuery } = convexBetterAuthNextJs({ convexUrl: process.env.NEXT_PUBLIC_CONVEX_URL!, convexSiteUrl: process.env.NEXT_PUBLIC_CONVEX_SITE_URL!, jwtCache: { enabled: true, isAuthError, }, }); ``` ```tanstack-start import { convexBetterAuthReactStart } from "@convex-dev/better-auth/react-start"; import { isAuthError } from "@/lib/utils"; export const { fetchAuthQuery } = convexBetterAuthReactStart({ convexUrl: process.env.VITE_CONVEX_URL!, convexSiteUrl: process.env.VITE_CONVEX_SITE_URL!, jwtCache: { enabled: true, isAuthError, }, }); ``` -------------------------------- ### Configure ConvexBetterAuthProvider in React Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/react.mdx Wraps the React application with `ConvexBetterAuthProvider` to provide authentication context. It initializes `ConvexReactClient` and optionally pauses queries until authentication is complete. ```typescript import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; import "./index.css"; import { ConvexReactClient } from "convex/react"; import { ConvexBetterAuthProvider } from "@convex-dev/better-auth/react"; // [!code ++] import { authClient } from "@/lib/auth-client"; // [!code ++] const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string, { // Optionally pause queries until the user is authenticated // [!code ++] expectAuth: true, // [!code ++] }); ReactDOM.createRoot(document.getElementById("root")!).render( // [!code ++] // [!code ++] ); ``` -------------------------------- ### Social Sign-in Authorized Origin and Redirect URI for Expo Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/framework-guides/expo.mdx Example of authorized origin and redirect URI formats for social sign-in providers like Google when using Better Auth with Expo, based on your Convex site URL. ```text // authorized origin https://adjective-animal-123.convex.site // authorized redirect URI https://adjective-animal-123.convex.site/api/auth/callback/google ``` -------------------------------- ### Configure Logger in Better Auth Options Source: https://github.com/get-convex/better-auth/blob/main/docs/content/docs/migrations/migrate-to-0-8.mdx Demonstrates how to disable logging when createAuth is called only to generate options. The logger configuration accepts a disabled property that prevents log output during option-only initialization. ```typescript logger: { disabled: optionsOnly, } ```