Loading...
Loading...
Complete Convex development mastery — functions (queries, mutations, actions, HTTP actions), schema design, index optimization, argument/return validation, authentication, security patterns, error handling, file storage, scheduling, crons, aggregates, OCC handling, denormalization, TypeScript best practices, and production-ready code organization. The definitive Convex skill. Use when building any Convex backend: writing functions, designing schemas, optimizing queries, handling auth, adding real-time features, setting up webhooks, scheduling jobs, managing file uploads, or reviewing/fixing Convex code. Triggers on: convex, query, mutation, action, ctx.db, defineSchema, defineTable, v.id, v.string, v.object, withIndex, ConvexError, internalMutation, httpAction, ctx.scheduler, ctx.storage, OCC, convex best practices, convex functions, convex schema, convex performance, "how do I do X in Convex".
npx skill4agent add imfa-solutions/skills convex-pro-maxThe definitive guide for building production-ready Convex applications.
argsreturnshandler.filter().withIndex()await@typescript-eslint/no-floating-promisesinternal*ctx.dbctx.runQueryctx.runMutationnullreturns: v.null()v.id("table")v.string()@convex-dev/eslint-plugin| Type | DB Access | External APIs | Transactional | Cached/Reactive |
|---|---|---|---|---|
| Read-only via | No | Yes | Yes |
| Read/Write via | No | Yes | No |
| Via | Yes | No | No |
| Via | Yes | No | No |
import { query } from "./_generated/server";
import { v } from "convex/values";
export const getUser = query({
args: { userId: v.id("users") },
returns: v.union(v.object({
_id: v.id("users"), _creationTime: v.number(),
name: v.string(), email: v.string(),
}), v.null()),
handler: async (ctx, args) => {
return await ctx.db.get(args.userId);
},
});import { mutation } from "./_generated/server";
import { v } from "convex/values";
export const createTask = mutation({
args: { title: v.string(), userId: v.id("users") },
returns: v.id("tasks"),
handler: async (ctx, args) => {
return await ctx.db.insert("tasks", {
title: args.title, userId: args.userId,
completed: false, createdAt: Date.now(),
});
},
});"use node"; // Required for Node.js APIs
import { action } from "./_generated/server";
import { internal } from "./_generated/api";
import { v } from "convex/values";
export const processPayment = action({
args: { orderId: v.id("orders"), amount: v.number() },
returns: v.null(),
handler: async (ctx, args) => {
const order = await ctx.runQuery(internal.orders.get, { orderId: args.orderId });
const result = await fetch("https://api.stripe.com/...", { method: "POST", /* ... */ });
await ctx.runMutation(internal.orders.updateStatus, {
orderId: args.orderId, status: result.ok ? "paid" : "failed",
});
return null;
},
});import { internalMutation, internalQuery, internalAction } from "./_generated/server";
import { internal } from "./_generated/api"; // for referencing internal functions
import { api } from "./_generated/api"; // for referencing public functions// convex/schema.ts
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
export default defineSchema({
users: defineTable({
name: v.string(),
email: v.string(),
role: v.union(v.literal("admin"), v.literal("member")),
settings: v.object({ theme: v.union(v.literal("light"), v.literal("dark")) }),
})
.index("by_email", ["email"])
.index("by_role", ["role"]),
messages: defineTable({
channelId: v.id("channels"),
authorId: v.id("users"),
content: v.string(),
})
.index("by_channel", ["channelId"])
.index("by_channel_and_author", ["channelId", "authorId"])
.searchIndex("search_content", { searchField: "content", filterFields: ["channelId"] }),
});by_channel_and_authorchannelIdby_channelby_channel_and_authorby_field1_and_field2.index("by_theme", ["settings.theme"])_id_creationTime// Read
const doc = await ctx.db.get(id); // by ID (null if not found)
const docs = await ctx.db.query("table").collect(); // all (bounded)
const first = await ctx.db.query("table").first(); // first or null
const one = await ctx.db.query("table").withIndex(...).unique(); // exactly one (throws if 0 or >1)
const top10 = await ctx.db.query("table").order("desc").take(10);
// Indexed query
const results = await ctx.db.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", channelId))
.order("desc")
.take(50);
// Write
const id = await ctx.db.insert("table", { ...fields });
await ctx.db.patch(id, { field: newValue }); // partial update
await ctx.db.replace(id, { ...allFields }); // full replace (keeps _id, _creationTime)
await ctx.db.delete(id);v.string() v.number() v.boolean() v.null()
v.id("tableName") v.int64() v.bytes() v.any()
v.array(v.string()) v.record(v.string(), v.number())
v.object({ name: v.string(), age: v.optional(v.number()) })
v.union(v.literal("a"), v.literal("b")) // enum-like
v.optional(v.string()) // field can be omitted
v.nullable(v.string()) // shorthand for v.union(v.string(), v.null())const roleValidator = v.union(v.literal("admin"), v.literal("member"));
const profileValidator = v.object({ name: v.string(), bio: v.optional(v.string()) });import { Infer } from "convex/values";
type Role = Infer<typeof roleValidator>; // "admin" | "member"import { Doc, Id } from "./_generated/dataModel";
import { QueryCtx, MutationCtx, ActionCtx } from "./_generated/server";// Reusable auth helper
export async function getCurrentUser(ctx: QueryCtx | MutationCtx) {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new ConvexError({ code: "UNAUTHORIZED", message: "Must be logged in" });
const user = await ctx.db.query("users")
.withIndex("by_token", (q) => q.eq("tokenIdentifier", identity.tokenIdentifier))
.unique();
if (!user) throw new ConvexError({ code: "USER_NOT_FOUND", message: "User not found" });
return user;
}ctx.authsetTeamNametransferOwnershipupdateTeaminternalMutationimport { ConvexError } from "convex/values";
// Throw structured errors
throw new ConvexError({ code: "NOT_FOUND", message: "Task not found" });
// Client catches
try { await createUser({ email }); }
catch (error) {
if (error instanceof ConvexError) { /* error.data.code, error.data.message */ }
}ConvexErrorconvex/
├── schema.ts # Schema + indexes
├── auth.ts # getCurrentUser, requireTeamMember helpers
├── users.ts # Public user API (thin wrappers)
├── teams.ts # Public team API
├── model/
│ ├── users.ts # User business logic (pure TS functions)
│ └── teams.ts # Team business logic
├── http.ts # HTTP actions (webhooks, APIs)
├── crons.ts # Cron jobs
└── convex.config.ts # Component registrationmodel/ctx.runActionctx.runAction