Convex Backend Guidelines
When to Load
- Trigger: Convex-specific development, writing Convex functions, schemas, queries, mutations, actions, or real-time subscriptions
- Skip: Project does not use Convex as its backend
Comprehensive guide for building Convex backends with TypeScript. Covers function syntax, validators, schemas, queries, mutations, actions, scheduling, and file storage.
When to Apply
Reference these guidelines when:
- Writing new Convex functions (queries, mutations, actions)
- Defining database schemas and validators
- Implementing real-time data fetching
- Setting up cron jobs or scheduled functions
- Working with file storage
- Designing API structure
Rule Categories
| Category |
Impact |
Description |
| Function Syntax |
CRITICAL |
New function syntax with args/returns/handler |
| Validators |
CRITICAL |
Type-safe argument and return validation |
| Schema Design |
HIGH |
Table definitions, indexes, system fields |
| Query Patterns |
HIGH |
Efficient data fetching with indexes |
| Mutation Patterns |
MEDIUM |
Database writes, patch vs replace |
| Action Patterns |
MEDIUM |
External API calls, Node.js runtime |
| Scheduling |
MEDIUM |
Crons and delayed function execution |
| File Storage |
LOW |
Blob storage and metadata |
Quick Reference
Function Registration
// Public functions (exposed to clients)
import { query, mutation, action } from "./_generated/server";
// Internal functions (only callable from other Convex functions)
import {
internalQuery,
internalMutation,
internalAction,
} from "./_generated/server";
Function Syntax (Always Use This)
export const myFunction = query({
args: { name: v.string() },
returns: v.string(),
handler: async (ctx, args) => {
return "Hello " + args.name;
},
});
Common Validators
| Type |
Validator |
Example |
| String |
v.string() |
"hello" |
| Number |
v.number() |
3.14 |
| Boolean |
v.boolean() |
true |
| ID |
v.id("tableName") |
doc._id |
| Array |
v.array(v.string()) |
["a", "b"] |
| Object |
v.object({...}) |
{name: "x"} |
| Optional |
v.optional(v.string()) |
undefined |
| Union |
v.union(v.string(), v.number()) |
"x" or 1 |
| Literal |
v.literal("status") |
"status" |
| Null |
v.null() |
null |
Function References
// Public functions
import { api } from "./_generated/api";
api.example.myQuery; // convex/example.ts → myQuery
// Internal functions
import { internal } from "./_generated/api";
internal.example.myInternalMutation;
Query with Index
// Schema
messages: defineTable({...}).index("by_channel", ["channelId"])
// Query
await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", channelId))
.order("desc")
.take(10);
Key Rules
- Always include
args and returns validators on all functions
- Use
v.null() for void returns - never omit return validator
- Use
withIndex() not filter() - define indexes in schema
- Use
internalQuery/Mutation/Action for private functions
- Actions cannot access
ctx.db - use runQuery/runMutation instead
- Include type annotations when calling functions in same file
Full Compiled Document
For the complete guide with all rules and detailed code examples, see AGENTS.md.
1---2name: convex-backend3description: Convex backend development guidelines. Use when writing Convex functions, schemas, queries, mutations, actions, or any backend code in a Convex project. Triggers on tasks involving Convex database operations, real-time subscriptions, file storage, or serverless functions.4---5
6# Convex Backend Guidelines
7
8### When to Load
9
10- **Trigger**: Convex-specific development, writing Convex functions, schemas, queries, mutations, actions, or real-time subscriptions
11- **Skip**: Project does not use Convex as its backend
12
13Comprehensive guide for building Convex backends with TypeScript. Covers function syntax, validators, schemas, queries, mutations, actions, scheduling, and file storage.
14
15## When to Apply
16
17Reference these guidelines when:
18
19- Writing new Convex functions (queries, mutations, actions)
20- Defining database schemas and validators
21- Implementing real-time data fetching
22- Setting up cron jobs or scheduled functions
23- Working with file storage
24- Designing API structure
25
26## Rule Categories
27
28| Category | Impact | Description |
29| ----------------- | -------- | --------------------------------------------- |
30| Function Syntax | CRITICAL | New function syntax with args/returns/handler |
31| Validators | CRITICAL | Type-safe argument and return validation |
32| Schema Design | HIGH | Table definitions, indexes, system fields |
33| Query Patterns | HIGH | Efficient data fetching with indexes |
34| Mutation Patterns | MEDIUM | Database writes, patch vs replace |
35| Action Patterns | MEDIUM | External API calls, Node.js runtime |
36| Scheduling | MEDIUM | Crons and delayed function execution |
37| File Storage | LOW | Blob storage and metadata |
38
39## Quick Reference
40
41### Function Registration
42
43```typescript
44// Public functions (exposed to clients)
45import { query, mutation, action } from "./_generated/server";
46
47// Internal functions (only callable from other Convex functions)
48import {
49 internalQuery,
50 internalMutation,
51 internalAction,
52} from "./_generated/server";
53```
54
55### Function Syntax (Always Use This)
56
57```typescript
58export const myFunction = query({
59 args: { name: v.string() },
60 returns: v.string(),
61 handler: async (ctx, args) => {
62 return "Hello " + args.name;
63 },
64});
65```
66
67### Common Validators
68
69| Type | Validator | Example |
70| -------- | --------------------------------- | ------------- |
71| String | `v.string()` | `"hello"` |
72| Number | `v.number()` | `3.14` |
73| Boolean | `v.boolean()` | `true` |
74| ID | `v.id("tableName")` | `doc._id` |
75| Array | `v.array(v.string())` | `["a", "b"]` |
76| Object | `v.object({...})` | `{name: "x"}` |
77| Optional | `v.optional(v.string())` | `undefined` |
78| Union | `v.union(v.string(), v.number())` | `"x"` or `1` |
79| Literal | `v.literal("status")` | `"status"` |
80| Null | `v.null()` | `null` |
81
82### Function References
83
84```typescript
85// Public functions
86import { api } from "./_generated/api";
87api.example.myQuery; // convex/example.ts → myQuery
88
89// Internal functions
90import { internal } from "./_generated/api";
91internal.example.myInternalMutation;
92```
93
94### Query with Index
95
96```typescript
97// Schema
98messages: defineTable({...}).index("by_channel", ["channelId"])
99
100// Query
101await ctx.db
102 .query("messages")
103 .withIndex("by_channel", (q) => q.eq("channelId", channelId))
104 .order("desc")
105 .take(10);
106```
107
108### Key Rules
109
1101. **Always include `args` and `returns` validators** on all functions
1112. **Use `v.null()` for void returns** - never omit return validator
1123. **Use `withIndex()` not `filter()`** - define indexes in schema
1134. **Use `internalQuery/Mutation/Action`** for private functions
1145. **Actions cannot access `ctx.db`** - use runQuery/runMutation instead
1156. **Include type annotations** when calling functions in same file
116
117## Full Compiled Document
118
119For the complete guide with all rules and detailed code examples, see [AGENTS.md](AGENTS.md).