Project Setup and Convex CLI Initialization
Begin by creating a fresh Next.js 15 application using the App Router. Run npx create-next-app@latest convex-next-app --typescript --tailwind --eslint --app --yes. Navigate into the directory with cd convex-next-app.
Install the Convex client and server packages: npm install convex for the client and npm install --save-dev convex to get the CLI. The CLI is what powers local development and deployment.
Initialize Convex by running npx convex dev. This command creates a convex/ folder at the project root, a convex/_generated/ directory for TypeScript definitions, and a convex.json configuration file. It also starts a local Convex instance that watches for changes.
The convex.json file contains your project identifier and deployment settings. For local development, Convex runs a full backend emulator on port 3210 by default. This setup gives you immediate database, authentication, and file storage without configuring PostgreSQL or Redis separately.
Schema Definition with Tables and Indexes
Convex uses a schema defined in TypeScript. Create convex/schema.ts with the following structure:
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
export default defineSchema({
documents: defineTable({
title: v.string(),
content: v.string(),
userId: v.id("users"),
embedding: v.array(v.float64()),
createdAt: v.number(),
})
.index("by_user", ["userId"])
.index("by_created", ["createdAt"])
.vectorIndex("by_embedding", {
vectorField: "embedding",
dimensions: 1536,
}),
messages: defineTable({
conversationId: v.id("conversations"),
content: v.string(),
role: v.union(v.literal("user"), v.literal("assistant")),
createdAt: v.number(),
}).index("by_conversation", ["conversationId", "createdAt"]),
conversations: defineTable({
userId: v.id("users"),
title: v.string(),
lastUpdated: v.number(),
}).index("by_user", ["userId", "lastUpdated"]),
});
This schema creates three tables with appropriate secondary indexes for common access patterns. The vector index on documents uses 1536 dimensions, matching OpenAI's text-embedding-3-small model. Convex automatically manages schema validation on write operations. Adding a new field later requires only updating the table definition; existing documents remain compatible until you enforce the new field.
Indexes are critical for query performance. Without the by_user index, a query filtering by userId would perform a full table scan, which Convex limits to 1000 documents by default for pagination safety.
Writing Type-Safe Queries
Queries are pure functions that read data. Create convex/documents.ts:
import { query } from "./_generated/server";
import { v } from "convex/values";
export const list = query({
args: { userId: v.id("users") },
handler: async (ctx, args) => {
return await ctx.db
.query("documents")
.withIndex("by_user", (q) => q.eq("userId", args.userId))
.order("desc")
.collect();
},
});
export const search = query({
args: { queryVector: v.array(v.float64()), limit: v.number() },
handler: async (ctx, args) => {
return await ctx.db
.query("documents")
.withIndex("by_embedding", (q) =>
q.vectorSimilarity("embedding", args.queryVector)
)
.limit(args.limit)
.collect();
},
});
These queries are automatically typed on the client. The search function uses vector similarity with cosine distance by default. Convex returns results ordered by similarity score. The limit argument prevents excessive data transfer; typical production values range between 5 and 20 depending on UI requirements.
Queries run with strong consistency from the closest regional deployment. For global applications, Convex offers multi-region replication with last-writer-wins semantics on conflicting writes.
Mutations for Writing Data
Mutations handle writes and can perform multiple operations atomically. Create convex/documents.ts (adding to the previous file):
import { mutation } from "./_generated/server";
import { v } from "convex/values";
export const create = mutation({
args: {
title: v.string(),
content: v.string(),
embedding: v.array(v.float64()),
},
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new Error("Not authenticated");
const docId = await ctx.db.insert("documents", {
title: args.title,
content: args.content,
userId: identity.subject,
embedding: args.embedding,
createdAt: Date.now(),
});
return docId;
},
});
Authentication is handled via ctx.auth. The identity.subject contains the user ID from your chosen auth provider. Mutations are executed with serializable isolation, preventing race conditions in concurrent updates to the same document.
Embedding generation should happen before calling the mutation. In practice, call an embedding API from the client or a Convex action (covered later) to avoid blocking the mutation with external network calls.
Real-Time Reactivity with useQuery
Convex's reactivity is built into its React hooks. In a Next.js client component:
"use client";
import { useQuery } from "convex/react";
import { api } from "../convex/_generated/api";
export default function DocumentList({ userId }: { userId: string }) {
const documents = useQuery(api.documents.list, { userId }) || [];
return (
<ul>
{documents.map((doc) => (
<li key={doc._id}>
{doc.title} — updated {new Date(doc.createdAt).toLocaleString()}
</li>
))}
</ul>
);
}
Any mutation that affects the queried data automatically rerenders only the affected components. This uses a dependency graph maintained by the Convex server. For a dashboard showing live metrics, this eliminates the need for WebSocket management or polling logic. The hook accepts a third argument for optimistic updates, though most patterns use mutations that return the new document ID for immediate local state updates.
In Server Components, use fetchQuery from convex/server to pre-fetch data during SSR. This integrates cleanly with Next.js streaming because Convex queries are fast (typically under 30ms for indexed reads).
Authentication Integration Patterns
Convex supports multiple auth providers. For Clerk, configure your convex.json with the Clerk JWT issuer:
{
"authInfo": [{
"application": "clerk",
"issuer": "https://clerk.yourdomain.com"
}]
}
Then in mutations and queries, ctx.auth.getUserIdentity() returns the Clerk user details. For organizations (multi-tenancy), store an orgId field and create an index on it. A common pattern is to have a users table that mirrors the external auth user on first login using an afterSignUp webhook.
Trade-off: Convex auth is tightly integrated but requires you to handle token refresh on the client using the Convex React provider. The ConvexReactClient automatically refreshes tokens when using Clerk's useAuth() hook together with Convex's ConvexProviderWithClerk.
Vector Search for Production RAG
Convex vector indexes enable semantic search without managing a separate vector database. After defining the vector index in the schema, insert documents with embeddings generated by an embedding model. A typical RAG flow looks like this in a mutation:
export const ingestDocument = mutation({
args: { title: v.string(), content: v.string() },
handler: async (ctx, args) => {
const embedding = await generateEmbedding(args.content); // calls external API
const docId = await ctx.db.insert("documents", {
title: args.title,
content: args.content,
embedding,
userId: (await ctx.auth.getUserIdentity())!.subject,
createdAt: Date.now(),
});
return docId;
},
});
The search query shown earlier returns documents with a _score field. For hybrid search, combine vector similarity with traditional filters:
.withIndex("by_embedding", (q) =>
q.vectorSimilarity("embedding", queryVector)
)
.filter((q) => q.eq(q.field("userId"), userId))
Current limitations: Convex vector search supports up to 16,000 dimensions and returns a maximum of 1000 results per query. For most RAG use cases this is sufficient. Re-indexing happens automatically when documents change. Production deployments should monitor index build time for tables with tens of thousands of documents; Convex shows index status in its dashboard.
Combine this with pgvector only if you need SQL-level joins that Convex cannot express. Most teams stay entirely in Convex once they adopt it because the reactivity and unified developer experience outweigh the need for complex relational queries.
HTTP Actions for External Integrations
Actions run outside the database transaction and can call third-party APIs. They are useful for Stripe webhooks. Create convex/http.ts:
import { httpRouter } from "convex/server";
import { httpAction } from "./_generated/server";
import Stripe from "stripe";
const http = httpRouter();
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
http.route({
path: "/stripe",
method: "POST",
handler: httpAction(async (ctx, request) => {
const signature = request.headers.get("stripe-signature")!;
const body = await request.text();
let event;
try {
event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET!
);
} catch (err) {
return new Response("Invalid signature", { status: 400 });
}
if (event.type === "checkout.session.completed") {
const session = event.data.object as Stripe.Checkout.Session;
await ctx.runMutation(api.users.upgradePlan, {
userId: session.metadata!.userId,
plan: session.metadata!.plan,
});
}
return new Response("OK", { status: 200 });
}),
});
export default http;
Actions have a 5-minute timeout and can make network calls. They cannot directly write to the database; instead they call mutations. This separation prevents long-running external calls from holding database transactions open.
Background Jobs and Scheduling
Convex supports scheduled functions and cron jobs. Define a cron in convex/crons.ts:
import { cronJobs } from "convex/server";
import { internal } from "./_generated/api";
const crons = cronJobs();
crons.interval(
"daily cleanup",
{ minutes: 1440 },
internal.documents.cleanupOldDocuments,
);
export default crons;
The target function must be marked internal so it cannot be called from the client. For one-off delayed jobs, use ctx.scheduler.runAfter(delayMs, mutationReference, args). This is useful for sending reminder emails 24 hours after trial signup. The scheduler persists jobs across deploys and server restarts.
Trade-off: Scheduled functions have the same resource limits as actions (2 CPU seconds, 512MB memory). For heavy computation, offload to external queues or RunPod-style workers and use Convex only as the coordination layer.
Structuring Large Applications
In production SaaS applications, organize Convex code by feature. Create folders like convex/users/, convex/billing/, convex/ai/. Each folder can export its own queries, mutations, and actions. Use internal mutations for operations that should only be called by other server functions.
Common pattern for multi-tenancy: every table that holds customer data includes an orgId or userId field. Row-level security is enforced at query time by filtering on the authenticated user's organization. Because every query runs this filter, add covering indexes that start with the orgId field to maintain performance.
For file storage, use Convex's built-in storage API with ctx.storage.getUrl(storageId). Files are automatically cleaned up when their referencing document is deleted if you use the afterDelete pattern.
Testing Convex Functions
Convex provides a test harness. Create tests with convex/test.ts using the test runner from convex/server. You can run full integration tests against an in-memory database:
import { test, expect } from "vitest";
import { convexTest } from "convex-test";
test("creates document", async () => {
const t = convexTest();
const user = await t.runMutation(api.users.create, { name: "Test" });
const docId = await t.runMutation(api.documents.create, {
title: "Test Doc",
content: "Hello",
embedding: new Array(1536).fill(0.1),
});
const docs = await t.runQuery(api.documents.list, { userId: user });
expect(docs.length).toBe(1);
});
These tests run in milliseconds because they use an in-memory backend. Test both success paths and authorization failures. The convex-test library allows mocking external HTTP calls made from actions.
Deployment and Observability
Deploy with npx convex deploy. This pushes your functions and schema to Convex's global edge network. Pair it with Vercel for the frontend. Environment variables are managed in the Convex dashboard and automatically injected into actions and HTTP endpoints.
Convex provides a dashboard showing function execution times, database size, and vector index health. Set up alerts for when storage approaches your plan limits. Most small-to-medium SaaS applications stay comfortably within the free tier for development and the $10-50/month paid tiers for production with thousands of daily active users.
Monitor real-time subscription counts in the dashboard. Each subscribed useQuery creates a persistent connection; design UIs to unsubscribe when components unmount. For infrequently updated admin dashboards, use regular queries instead of reactive ones to reduce connection load.
Trade-offs and When Not to Use Convex
Convex excels at reactive UIs, real-time collaboration, and rapid iteration because you write zero backend boilerplate for CRUD, realtime, or auth. However, it is not ideal for applications requiring complex SQL joins across 15 normalized tables or heavy batch analytics. For those cases, a traditional PostgreSQL + Prisma stack may be more appropriate.
Another trade-off is vendor lock-in. While you can export your data, the reactivity and query language are proprietary. Most teams accept this because the productivity gains allow them to ship features that would be prohibitively expensive to build with traditional architectures.
Vector search quality depends on the embedding model. Test multiple models (text-embedding-3-small vs. voyage-3) and store multiple embedding vectors per document if necessary. Convex allows multiple vector indexes on the same table.
Rate limits are generous (thousands of requests per second per project on paid plans) but functions have strict CPU and memory bounds. Offload heavy LLM inference to external services via actions and store only the results in Convex.
Combining Convex with Existing Next.js Patterns
Use Convex alongside Server Actions for simple form submissions that do not require realtime updates. Server Actions remain useful for progressive enhancement. For pages that need both static generation and live data, fetch initial data with fetchQuery in a Server Component and then subscribe on the client with useQuery.
In Turborepo monorepos, place the convex/ folder in the web app package. Share types between packages by exporting the generated API client. The convex/_generated/api.d.ts file provides complete end-to-end type safety from database schema through to React components.
For AI-heavy applications, store conversation history in Convex and use it as context for LLM calls. The combination of vector search for retrieval and reactive UI for streaming responses creates delightful user experiences that update live as the assistant thinks.
Common pitfall: forgetting to add indexes. Convex will warn you in the dashboard when a query performs a table scan. Always add the index before going to production. Another pitfall is returning large documents in queries used by many subscribers. Keep returned data minimal and use separate queries for detailed views.
Migrating an Existing Next.js Application to Convex
Start small. Identify one feature with high real-time requirements (notifications, collaborative editing, live dashboards) and migrate only that slice. Replace your existing API routes with Convex queries and mutations while keeping the rest of your backend intact. The Convex React client coexists peacefully with TanStack Query or SWR.
Once comfortable, migrate auth by adding the Convex provider at the root. Export your existing database and write a one-time migration script using Convex's ctx.db API. Most migrations complete in minutes for tables under 100,000 rows.
After full migration, you can remove your separate database, API layer, and cron service, reducing operational complexity significantly. Teams report 40-60% reduction in backend code when moving to Convex, though exact numbers depend on application shape.
Security Best Practices
Never trust the client. Always check ctx.auth.getUserIdentity() in mutations and add ownership checks. Use ctx.db.patch and ctx.db.delete only after verifying the document belongs to the caller. Convex automatically prevents injection attacks because all values are strongly typed.
For public data, use unauthenticated queries but still apply rate limiting at the HTTP edge (Cloudflare or Vercel). Convex supports public functions but they still run with the same execution limits.
Enable Convex's audit logs in production to track all database mutations. This helps during security incidents and provides a clear history for compliance requirements.
The combination of type-safe queries, automatic realtime, vector search, and integrated scheduling makes Convex a compelling choice for modern AI-powered SaaS products built with Next.js. The learning curve is low if you already know TypeScript, and the patterns scale from prototype to production without changing core architecture.
