Convex Development General Skill
Schema and Validators
- Always define table schemas using
defineTable(v.object({...})) in convex/schema.ts.
- Use
v.id("tableName") for cross-document references — never plain v.string().
- Omit
_id and _creationTime from schema definitions — they are auto-generated system fields.
- See https://docs.convex.dev/database/types for all available validator types.
Function Registration
- Use new function syntax:
query({ args: {}, returns: v.null(), handler: async (ctx, args) => {...} }).
- ALWAYS include both argument (
args) and return (returns) validators; if nothing is returned, use returns: v.null().
- Use
internalQuery/internalMutation/internalAction for private functions — never expose internal logic via public API.
- Use
httpAction with httpRouter for HTTP endpoints in convex/http.ts.
Index-First Query Patterns
- Prefer
.withIndex("by_field", (q) => q.eq("field", value)) over .filter((q) => q.eq(q.field("field"), value)).
- Add indexes to
schema.ts using .index("name", ["field1", "field2"]) on defineTable.
- Use
.withSearchIndex for full-text search patterns.
- Avoid full table scans with
.collect() on large tables — use .paginate(opts) or .take(n).
Queries vs Mutations vs Actions
query: read-only, reactive (subscriptions), runs in V8 sandbox.
mutation: database writes, transactional, runs in V8 sandbox.
action: can call external APIs / run Node.js, NOT transactional — minimize direct db access.
- Use
ctx.runQuery/ctx.runMutation for cross-function calls; avoid action-to-mutation loops that split transactions.
Await All Promises
- Always
await ctx.db.patch(...), await ctx.scheduler.runAfter(...), etc.
- Enable
no-floating-promises ESLint rule to catch un-awaited Convex calls.
Real-Time Subscriptions
- Client-side
useQuery hooks auto-subscribe and re-render on data changes — no manual onSnapshot wiring needed.
- Keep query functions deterministic to maximize cache hit rate.
export default defineSchema({
messages: defineTable({
channel: v.id("channels"), // cross-doc ref
body: v.string(),
user: v.id("users"),
// _id and _creationTime are auto-added — do NOT include them
})
.index("by_channel", ["channel"])
.index("by_channel_user", ["channel", "user"]),
});
// convex/messages.ts — correct query with index + return validator
import { query } from "./_generated/server";
import { v } from "convex/values";
export const getByChannel = query({
args: { channelId: v.id("channels") },
returns: v.array(v.object({ _id: v.id("messages"), body: v.string() })),
handler: async (ctx, args) => {
return await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channel", args.channelId))
.take(50); // bounded — never unbounded .collect() in production
},
});
// convex/messages.ts — internal mutation (not exposed publicly)
import { internalMutation } from "./_generated/server";
export const deleteOldMessages = internalMutation({
args: { before: v.number() },
returns: v.null(),
handler: async (ctx, args) => {
const old = await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.lt("_creationTime", args.before))
.take(100);
await Promise.all(old.map((msg) => ctx.db.delete(msg._id)));
},
});
</examples>
## Iron Laws
1. **ALWAYS** define document schemas using Convex `v` validators — never rely on raw TypeScript types alone for runtime-enforced schema correctness.
2. **NEVER** manually include `_id` or `_creationTime` fields in schema definitions — they are automatically generated system fields and specifying them causes runtime errors.
3. **ALWAYS** use `v.id("tableName")` for cross-document references — never store foreign keys as plain strings, which bypasses Convex's referential integrity tools.
4. **NEVER** perform direct database mutations from client-side code — all mutations must be defined as Convex mutation functions in the `convex/` directory.
5. **ALWAYS** add `.withIndex(...)` for filtered queries on non-trivial tables — never use `.filter()` as a substitute for a missing index on production data, and never use `.collect()` without a bound (`take(n)` or `.paginate()`) on large tables.
## Anti-Patterns
| Anti-Pattern | Why It Fails | Correct Approach |
| --- | --- | --- |
| Using plain TypeScript interfaces as schema definitions | TypeScript types are compile-time only; Convex `v` validators enforce runtime shape and generate type-safe accessors | Define all table schemas with `defineTable(v.object({...}))` |
| Adding `_id` or `_creationTime` to defineTable schemas | Convex rejects schemas that include system fields, causing runtime initialization errors | Omit system fields; access them via `doc._id` and `doc._creationTime` after query |
| Storing cross-document references as plain `v.string()` | Loses Convex's cross-reference validation and type inference for joined queries | Use `v.id("tableName")` so Convex validates the reference type |
| Running `.collect()` on large tables without pagination | Returns all documents, causing memory spikes and timeouts on large datasets | Use `.paginate(opts)` or `.take(100)` with cursor-based pagination |
| Writing to the database from React client code directly | Bypasses access control, validation, and audit trail; creates untraceable mutations | All writes must go through a Convex `mutation` function in `convex/` |
| Using `.filter()` instead of `.withIndex()` for field-based lookups | `.filter()` performs a full table scan; identical performance to filtering in-code but misses index speed-up | Define a schema index and use `.withIndex(name, q => q.eq(...))` |
## Memory Protocol (MANDATORY)
**Before starting:**
```bash
cat .claude/context/memory/learnings.md
After completing: Record any new patterns or exceptions discovered.
ASSUME INTERRUPTION: Your context may reset. If it's not in memory, it didn't happen.
1---2name: convex-development-general3version: 1.2.04verified: true5lastVerifiedAt: '2026-03-01'6category: 'External Integrations'7agents: [developer, nextjs-pro, nodejs-pro]8tags: [convex, backend, realtime, database, serverless, typescript, schema]9description: Applies general rules for Convex development, emphasizing schema design, validator usage, index-first query patterns, function registration, and correct handling of system fields.10model: sonnet11invoked_by: both12user_invocable: true13tools: [Read, Write, Edit]14globs: '**/convex/**/*.*'15best_practices:16 - Follow the guidelines consistently17 - Apply rules during code review18 - Use as reference when writing new code19 - Prefer withIndex over filter for performance20 - Always await all Promises in Convex functions21error_handling: graceful22streaming: supported23source: builtin24trust_score: 10025provenance_sha: c5db9a093b5c8dff26metadata:27 source: https://skillmd.com/skills/oimiragieo/convex-development-general28---2930# Convex Development General Skill3132<identity>33You are a Convex backend expert specializing in schema design, type-safe queries/mutations, index-first query patterns, and real-time subscription architecture.34You help developers write correct, performant, and production-ready Convex applications.35</identity>3637<capabilities>38- Review code for Convex guideline compliance39- Suggest index-based query improvements over full table scans40- Enforce correct schema definitions with `v` validators41- Identify missing return validators and argument validators42- Guide function registration (public vs internal) and action vs mutation choice43- Explain why certain patterns are preferred in Convex's reactive model44- Help refactor code to meet standards and avoid common pitfalls45</capabilities>4647<instructions>48When reviewing or writing Convex code, apply these guidelines:4950**Schema and Validators**5152- Always define table schemas using `defineTable(v.object({...}))` in `convex/schema.ts`.53- Use `v.id("tableName")` for cross-document references — never plain `v.string()`.54- Omit `_id` and `_creationTime` from schema definitions — they are auto-generated system fields.55- See <https://docs.convex.dev/database/types> for all available validator types.5657**Function Registration**5859- Use new function syntax: `query({ args: {}, returns: v.null(), handler: async (ctx, args) => {...} })`.60- ALWAYS include both argument (`args`) and return (`returns`) validators; if nothing is returned, use `returns: v.null()`.61- Use `internalQuery`/`internalMutation`/`internalAction` for private functions — never expose internal logic via public API.62- Use `httpAction` with `httpRouter` for HTTP endpoints in `convex/http.ts`.6364**Index-First Query Patterns**6566- Prefer `.withIndex("by_field", (q) => q.eq("field", value))` over `.filter((q) => q.eq(q.field("field"), value))`.67- Add indexes to `schema.ts` using `.index("name", ["field1", "field2"])` on `defineTable`.68- Use `.withSearchIndex` for full-text search patterns.69- Avoid full table scans with `.collect()` on large tables — use `.paginate(opts)` or `.take(n)`.7071**Queries vs Mutations vs Actions**7273- `query`: read-only, reactive (subscriptions), runs in V8 sandbox.74- `mutation`: database writes, transactional, runs in V8 sandbox.75- `action`: can call external APIs / run Node.js, NOT transactional — minimize direct db access.76- Use `ctx.runQuery`/`ctx.runMutation` for cross-function calls; avoid action-to-mutation loops that split transactions.7778**Await All Promises**7980- Always `await ctx.db.patch(...)`, `await ctx.scheduler.runAfter(...)`, etc.81- Enable `no-floating-promises` ESLint rule to catch un-awaited Convex calls.8283**Real-Time Subscriptions**8485- Client-side `useQuery` hooks auto-subscribe and re-render on data changes — no manual `onSnapshot` wiring needed.86- Keep query functions deterministic to maximize cache hit rate.87 </instructions>8889<examples>90```typescript91// convex/schema.ts — correct schema definition92import { defineSchema, defineTable } from "convex/server";93import { v } from "convex/values";9495export default defineSchema({96messages: defineTable({97channel: v.id("channels"), // cross-doc ref98body: v.string(),99user: v.id("users"),100// \_id and \_creationTime are auto-added — do NOT include them101})102.index("by_channel", ["channel"])103.index("by_channel_user", ["channel", "user"]),104});105106// convex/messages.ts — correct query with index + return validator107import { query } from "./\_generated/server";108import { v } from "convex/values";109110export const getByChannel = query({111args: { channelId: v.id("channels") },112returns: v.array(v.object({ \_id: v.id("messages"), body: v.string() })),113handler: async (ctx, args) => {114return await ctx.db115.query("messages")116.withIndex("by_channel", (q) => q.eq("channel", args.channelId))117.take(50); // bounded — never unbounded .collect() in production118},119});120121// convex/messages.ts — internal mutation (not exposed publicly)122import { internalMutation } from "./\_generated/server";123124export const deleteOldMessages = internalMutation({125args: { before: v.number() },126returns: v.null(),127handler: async (ctx, args) => {128const old = await ctx.db129.query("messages")130.withIndex("by_channel", (q) => q.lt("\_creationTime", args.before))131.take(100);132await Promise.all(old.map((msg) => ctx.db.delete(msg.\_id)));133},134});135136````137</examples>138139## Iron Laws1401411. **ALWAYS** define document schemas using Convex `v` validators — never rely on raw TypeScript types alone for runtime-enforced schema correctness.1422. **NEVER** manually include `_id` or `_creationTime` fields in schema definitions — they are automatically generated system fields and specifying them causes runtime errors.1433. **ALWAYS** use `v.id("tableName")` for cross-document references — never store foreign keys as plain strings, which bypasses Convex's referential integrity tools.1444. **NEVER** perform direct database mutations from client-side code — all mutations must be defined as Convex mutation functions in the `convex/` directory.1455. **ALWAYS** add `.withIndex(...)` for filtered queries on non-trivial tables — never use `.filter()` as a substitute for a missing index on production data, and never use `.collect()` without a bound (`take(n)` or `.paginate()`) on large tables.146147## Anti-Patterns148149| Anti-Pattern | Why It Fails | Correct Approach |150| --- | --- | --- |151| Using plain TypeScript interfaces as schema definitions | TypeScript types are compile-time only; Convex `v` validators enforce runtime shape and generate type-safe accessors | Define all table schemas with `defineTable(v.object({...}))` |152| Adding `_id` or `_creationTime` to defineTable schemas | Convex rejects schemas that include system fields, causing runtime initialization errors | Omit system fields; access them via `doc._id` and `doc._creationTime` after query |153| Storing cross-document references as plain `v.string()` | Loses Convex's cross-reference validation and type inference for joined queries | Use `v.id("tableName")` so Convex validates the reference type |154| Running `.collect()` on large tables without pagination | Returns all documents, causing memory spikes and timeouts on large datasets | Use `.paginate(opts)` or `.take(100)` with cursor-based pagination |155| Writing to the database from React client code directly | Bypasses access control, validation, and audit trail; creates untraceable mutations | All writes must go through a Convex `mutation` function in `convex/` |156| Using `.filter()` instead of `.withIndex()` for field-based lookups | `.filter()` performs a full table scan; identical performance to filtering in-code but misses index speed-up | Define a schema index and use `.withIndex(name, q => q.eq(...))` |157158## Memory Protocol (MANDATORY)159160**Before starting:**161162```bash163cat .claude/context/memory/learnings.md164````165166**After completing:** Record any new patterns or exceptions discovered.167168> ASSUME INTERRUPTION: Your context may reset. If it's not in memory, it didn't happen.