| name | components-guide |
| description | Guide to using Convex components for feature encapsulation. Learn about sibling components, creating your own, and when to use components vs monolithic code. |
Convex Components Guide
Use components to encapsulate features and build maintainable, reusable backends.
What Are Convex Components?
Components are self-contained mini-backends that bundle:
- Their own database schema
- Their own functions (queries, mutations, actions)
- Their own data (isolated tables)
- Clear API boundaries
Think of them as: npm packages for your backend, or microservices without the deployment complexity.
Why Use Components?
Traditional Approach (Monolithic)
convex/
├── users.ts (500 lines)
├── files.ts (600 lines - upload, storage, permissions, rate limiting)
├── payments.ts (400 lines - Stripe, webhooks, billing)
├── notifications.ts (300 lines)
└── analytics.ts (200 lines)
Total: One big codebase, everything mixed together
Component Approach (Encapsulated)
convex/
├── components/
│ ├── storage/ (File uploads - reusable)
│ ├── billing/ (Payments - reusable)
│ ├── notifications/ (Alerts - reusable)
│ └── analytics/ (Tracking - reusable)
├── convex.config.ts (Wire components together)
└── domain/ (Your actual business logic)
├── users.ts (50 lines - uses components)
└── projects.ts (75 lines - uses components)
Total: Clean, focused, reusable
Quick Start
1. Install a Component
npm install @convex-dev/ratelimiter
2. Configure in convex.config.ts
import { defineApp } from "convex/server";
import ratelimiter from "@convex-dev/ratelimiter/convex.config";
export default defineApp({
components: {
ratelimiter,
},
});
3. Use in Your Code
import { components } from "./_generated/api";
export const createPost = mutation({
handler: async (ctx, args) => {
await components.ratelimiter.check(ctx, {
key: `user:${ctx.user._id}`,
limit: 10,
period: 60000,
});
return await ctx.db.insert("posts", args);
},
});
Sibling Components Pattern
Multiple components working together at the same level:
export default defineApp({
components: {
auth: authComponent,
storage: storageComponent,
payments: paymentsComponent,
emails: emailComponent,
analytics: analyticsComponent,
},
});
Example: Complete Feature Using Siblings
import { components } from "./_generated/api";
export const subscribe = mutation({
args: { plan: v.string() },
handler: async (ctx, args) => {
const user = await components.auth.getCurrentUser(ctx);
const subscription = await components.payments.createSubscription(ctx, {
userId: user._id,
plan: args.plan,
amount: getPlanAmount(args.plan),
});
await components.analytics.track(ctx, {
event: "subscription_created",
userId: user._id,
plan: args.plan,
});
await components.emails.send(ctx, {
to: user.email,
template: "subscription_welcome",
data: { plan: args.plan },
});
await ctx.db.insert("subscriptions", {
userId: user._id,
paymentId: subscription.id,
plan: args.plan,
status: "active",
});
return subscription;
},
});
What this achieves:
- ✅ Each component is single-purpose
- ✅ Components are reusable across features
- ✅ Easy to swap implementations (change email provider)
- ✅ Can update components independently
- ✅ Clear separation of concerns
Official Components
Browse Component Directory:
Authentication
- @convex-dev/better-auth - Better Auth integration
Storage
- @convex-dev/r2 - Cloudflare R2 file storage
- @convex-dev/storage - File upload/download
Payments
- @convex-dev/polar - Polar billing & subscriptions
AI
- @convex-dev/agent - AI agent workflows
- @convex-dev/embeddings - Vector storage & search
Backend Utilities
- @convex-dev/ratelimiter - Rate limiting
- @convex-dev/aggregate - Data aggregations
- @convex-dev/action-cache - Cache action results
- @convex-dev/sharded-counter - Distributed counters
- @convex-dev/migrations - Schema migrations
- @convex-dev/workflow - Workflow orchestration
Creating Your Own Component
When to Create a Component
Good reasons:
- Feature is self-contained
- You'll reuse it across projects
- Want to share with team/community
- Complex feature with its own data model
- Third-party integration wrapper
Not good reasons:
- One-off business logic
- Tightly coupled to main app
- Simple utility functions
Structure
mkdir -p convex/components/notifications
import { defineComponent } from "convex/server";
export default defineComponent("notifications");
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
export default defineSchema({
notifications: defineTable({
userId: v.id("users"),
message: v.string(),
read: v.boolean(),
createdAt: v.number(),
})
.index("by_user", ["userId"])
.index("by_user_and_read", ["userId", "read"]),
});
import { mutation } from "./_generated/server";
import { v } from "convex/values";
export const send = mutation({
args: {
userId: v.id("users"),
message: v.string(),
},
handler: async (ctx, args) => {
await ctx.db.insert("notifications", {
userId: args.userId,
message: args.message,
read: false,
createdAt: Date.now(),
});
},
});
export const markRead = mutation({
args: { notificationId: v.id("notifications") },
handler: async (ctx, args) => {
await ctx.db.patch(args.notificationId, { read: true });
},
});
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("notifications")
.withIndex("by_user", q => q.eq("userId", args.userId))
.order("desc")
.collect();
},
});
export const unreadCount = query({
args: { userId: v.id("users") },
handler: async (ctx, args) => {
const unread = await ctx.db
.query("notifications")
.withIndex("by_user_and_read", q =>
q.eq("userId", args.userId).eq("read", false)
)
.collect();
return unread.length;
},
});
Use Your Component
import { defineApp } from "convex/server";
import notifications from "./components/notifications/convex.config";
export default defineApp({
components: {
notifications,
},
});
import { components } from "./_generated/api";
export const completeTask = mutation({
args: { taskId: v.id("tasks") },
handler: async (ctx, args) => {
const task = await ctx.db.get(args.taskId);
await ctx.db.patch(args.taskId, { completed: true });
await components.notifications.send(ctx, {
userId: task.userId,
message: `Task "${task.title}" completed!`,
});
},
});
Component Communication Patterns
✅ Parent → Component (Good)
await components.storage.upload(ctx, file);
await components.analytics.track(ctx, event);
✅ Parent → Multiple Siblings (Good)
await components.auth.verify(ctx);
const file = await components.storage.upload(ctx, data);
await components.notifications.send(ctx, message);
✅ Component Receives Parent Data (Good)
await components.audit.log(ctx, {
userId: user._id,
action: "delete",
resourceId: task._id,
});
❌ Component → Parent Tables (Bad)
const user = await ctx.db.get(userId);
❌ Sibling → Sibling (Bad)
Components can't call each other directly. If you need this, they should be in the main app or refactor the design.
Real-World Examples
Multi-Tenant SaaS
export default defineApp({
components: {
auth: "@convex-dev/better-auth",
organizations: "./components/organizations",
billing: "./components/billing",
storage: "@convex-dev/r2",
analytics: "./components/analytics",
emails: "./components/emails",
},
});
Each component:
auth - User authentication & sessions
organizations - Tenant isolation & permissions
billing - Stripe integration & subscriptions
storage - File uploads to R2
analytics - Event tracking & metrics
emails - Email sending via SendGrid
E-Commerce Platform
export default defineApp({
components: {
cart: "./components/cart",
inventory: "./components/inventory",
orders: "./components/orders",
payments: "@convex-dev/polar",
shipping: "./components/shipping",
recommendations: "./components/recommendations",
},
});
AI Application
export default defineApp({
components: {
agent: "@convex-dev/agent",
embeddings: "./components/embeddings",
documents: "./components/documents",
chat: "./components/chat",
workflow: "@convex-dev/workflow",
},
});
Migration from Monolithic
Step 1: Identify Features
Current monolith:
- File uploads (mixed with main app)
- Rate limiting (scattered everywhere)
- Analytics (embedded in functions)
Step 2: Extract One Feature
mkdir -p convex/components/storage
Step 3: Test Independently
Step 4: Repeat
Extract other features incrementally.
Best Practices
1. Single Responsibility
Each component does ONE thing well:
- ✅ storage component handles files
- ✅ auth component handles authentication
- ❌ Don't create "utils" component with everything
2. Clear API Surface
export { upload, download, delete } from "./storage";
3. Minimal Coupling
await components.audit.log(ctx, {
userId: user._id,
action: "delete"
});
4. Version Your Components
{
"name": "@yourteam/notifications-component",
"version": "1.0.0"
}
5. Document Your Components
Include README with:
- What the component does
- How to install
- How to use
- API reference
- Examples
Troubleshooting
Component not found
Can't access parent tables
This is by design! Components are sandboxed.
Pass data as arguments instead.
Component conflicts
Each component has isolated tables.
Components can't see each other's data.
Learn More
Checklist
Remember: Components are about encapsulation and reusability. When in doubt, prefer components over monolithic code!