BETTER-CONVEX

Introduction

A complete framework for building type-safe, real-time applications with Convex.

Introduction

Better Convex is a complete framework for Convex. It brings tRPC-style APIs, TanStack Query, Convex Ents, and Better Auth together into a cohesive developer experience.

This is not just a query wrapper. It's how you build production Convex applications.

Philosophy

We didn't reinvent the wheel. Better Convex integrates battle-tested tools—Convex Ents for relationships, TanStack Query for caching, Better Auth for authentication—into a unified developer experience.

Instead of assembling these yourself with custom glue code, you get:

  • Type safety end-to-end — From schema to procedures to client, with full inference
  • Real-time by default — WebSocket subscriptions flow into TanStack Query cache
  • TanStack Query native — No wrapper hooks, use useQuery and useMutation directly
  • Incremental adoption — Add features as you need them, migrate function by function

What's Included

LayerFeatureDescription
ServercRPCtRPC-style procedure builder with .input(), .use(), middleware
DatabaseEntsRelationships, fluent queries, ctx.table()
DatabaseTriggersAutomatic side effects on data changes
DatabaseAggregatesO(log n) counts, sums, leaderboards
ClientReactTanStack Query integration with real-time sync
ClientNext.jsRSC prefetching, hydration, server caller
AuthBetter AuthLifecycle hooks, session management, guards
CLICodegenProcedure metadata for auth-aware queries

Quick Look

// Server: Define a procedure
export const list = authQuery
  .input(z.object({ limit: z.number().optional() }))
  .query(async ({ ctx, input }) => {
    return ctx.table('posts').take(input.limit ?? 10);
  });

// Client: Use it with TanStack Query
const { data: posts } = useQuery(crpc.posts.list.queryOptions({ limit: 10 }));

Packages

ExportDescription
better-convex/servercRPC builder, middleware, server caller
better-convex/reactReact client, providers, auth hooks
better-convex/rscRSC prefetching, hydration
better-convex/authBetter Auth adapter
better-convex/auth-nextjsBetter Auth Next.js adapter

Requirements

  • Convex 1.31+
  • TanStack Query 5+
  • React 18+

Next Steps


For AI Agents

If you're an AI agent integrating better-convex, ask the user to select their stack before starting. Use your AskUserQuestion tool (or equivalent) to let them pick:

Required Choices

FeatureOptionsDefault
ApproachTop-down (copy from Templates), Bottom-up (follow docs step-by-step)Top-down
React FrameworkNext.js App Router, Vite, Remix, OtherNext.js
Database APIctx.table (Ents), ctx.db (vanilla)ctx.table

Optional Features

FeatureOptionsWhen to Include
AuthBetter Auth, Custom, NoneMost apps need auth
SSR/RSCYes, NoNext.js App Router apps
TriggersYes, NoAuto side effects on data changes
AggregatesYes, NoCounts, sums, leaderboards
Rate LimitingYes, NoAPI protection

After Selection

Top-down approach:

  1. Copy relevant sections from Templates based on choices
  2. For ctx.table: use the "ctx.table" tab in code examples
  3. For ctx.db: use the "ctx.db" tab in code examples
  4. Skip sections for features not selected

Bottom-up approach:

  1. Follow Quickstart for initial setup
  2. Read individual docs for each feature needed
  3. Reference Templates for production patterns

Quick Reference by Stack

StackKey Docs
Next.js + Better Auth + EntsTemplates, Next.js Setup, Auth Server
Next.js + Better Auth + ctx.dbTemplates (ctx.db tabs), Next.js Setup
Vite + No AuthReact Setup, Server Setup
Any + Custom AuthServer Setup, Middlewares

Documentation Map

Complete reference for all documentation pages.

Getting Started

PageWhen to Use
QuickstartFirst-time setup. Follow step-by-step to get a working app.
ConceptsUnderstand architecture, folder structure (convex/functions/, convex/lib/, convex/shared/), and design decisions.
TemplatesCopy-paste production code. Complete files for schema, cRPC, providers, auth, triggers, rate limiting. Start here for fastest setup.

Server (Backend)

PageWhen to Use
Server SetupInitialize cRPC builder with initCRPC. Configure dataModel, context, meta.
ProceduresDefine queries, mutations, actions with .input(), .output(), .query()/.mutation()/.action(). Paginated queries with .paginated().
ContextExtend context with ctx.db, ctx.table, ctx.auth. Add custom properties via .context().
MiddlewaresCreate reusable middleware with .use(). Auth guards, logging, rate limiting. Chain with .pipe().
MetadataAdd procedure metadata with .meta(). Used by CLI for auth-aware query handling.
Error HandlingThrow CRPCError with codes like UNAUTHORIZED, NOT_FOUND, BAD_REQUEST.
Server-Side CallsCall procedures from server with createCallerFactory. RSC data fetching.
Rate LimitingToken bucket and fixed window rate limiting with @convex-dev/rate-limiter.

Database

PageWhen to Use
EntsUse ctx.table() instead of ctx.db. Relationships, fluent queries, .edge(), .edges().
TriggersAutomatic side effects on insert/update/delete. Use convex-helpers/server/triggers.
AggregatesO(log n) counts and sums with @convex-dev/aggregate. Leaderboards, running totals.

React (Client)

PageWhen to Use
React SetupConfigure providers: QueryClientProvider, CRPCProvider. Singleton helpers.
QueriesuseQuery with crpc.path.queryOptions(). Real-time updates, skipToken for conditional queries.
MutationsuseMutation with crpc.path.mutationOptions(). Toast patterns, optimistic updates.
Infinite QueriesuseInfiniteQuery with crpc.path.infiniteQueryOptions(). Cursor-based pagination.
Type InferenceinferApiInputs, inferApiOutputs for tRPC-style type extraction.
Error HandlingHandle CRPCClientError on client. Error boundaries, toast notifications.

Next.js

PageWhen to Use
Next.js SetupConfigure convexBetterAuth for RSC. Server caller factory, JWT caching.
RSCServer components with prefetch, preloadQuery, HydrateClient. SSR data fetching.

Auth (Better Auth)

PageWhen to Use
Auth OverviewArchitecture overview. When to use Better Auth vs other auth solutions.
Auth ServerComplete Better Auth setup: schema, adapters, HTTP routes, helpers.
Auth ClientuseAuth, Authenticated/Unauthenticated components.
Auth TriggersUser lifecycle hooks: beforeCreate, onCreate, onDelete.

Reference

PageWhen to Use
CLIbetter-convex dev for codegen. Procedure metadata generation.
MigrationMigrate from vanilla Convex. Function-by-function upgrade guide.
ComparisonCompare with tRPC, Convex hooks, other patterns.

Common Workflows

New project setup:

  1. Quickstart → basic setup
  2. Templates → copy production files
  3. Concepts → understand folder structure

Add authentication:

  1. Auth Server → configure Better Auth
  2. Auth Client → use auth in components
  3. Middlewares → protect procedures

Add database features:

  1. Ents → relationships with ctx.table()
  2. Triggers → automatic side effects
  3. Aggregates → counts and sums

Server components (RSC):

  1. Next.js Setup → configure caller
  2. RSC → prefetch and hydrate

On this page