Convex guidelines
description: Guidelines and best practices for building Convex projects, including database schema design, queries, mutations, and real-world examples
globs: **/*.{ts,tsx,js,jsx}
Convex guidelines
Function guidelines
New function syntax
- ALWAYS use the new function syntax for Convex functions. For example:
typescript import { query } from "./_generated/server"; import { v } from "convex/values"; export const f = query({ args: {}, returns: v.null(), handler: async (ctx, args) => { // Function body }, });
Http endpoint syntax
- HTTP endpoints are defined in
convex/http.ts and require an httpAction decorator. For example:
typescript import { httpRouter } from "convex/server"; import { httpAction } from "./_generated/server"; const http = httpRouter(); http.route({ path: "/echo", method: "POST", handler: httpAction(async (ctx, req) => { const body = await req.bytes(); return new Response(body, { status: 200 }); }), });
- HTTP endpoints are always registered at the exact path you specify in the
path field. For example, if you specify /api/someRoute, the endpoint will be registered at /api/someRoute.
Validators
- Below is an example of an array validator:
typescript import { mutation } from "./_generated/server"; import { v } from "convex/values"; export default mutation({ args: { simpleArray: v.array(v.union(v.string(), v.number())), }, handler: async (ctx, args) => { //... }, });
- Below is an example of a schema with validators that codify a discriminated union type:
typescript import { defineSchema, defineTable } from "convex/server"; import { v } from "convex/values"; export default defineSchema({ results: defineTable( v.union( v.object({ kind: v.literal("error"), errorMessage: v.string(), }), v.object({ kind: v.literal("success"), value: v.number(), }), ), ) });
- Always use the
v.null() validator when returning a null value. Below is an example query that returns a null value:
typescript import { query } from "./_generated/server"; import { v } from "convex/values"; export const exampleQuery = query({ args: {}, returns: v.null(), handler: async (ctx, args) => { console.log("This query returns a null value"); return null; }, });
- Here are the valid Convex types along with their respective validators:
| Convex Type |
TS/JS type |
Example Usage |
Validator for argument validation and schemas |
Notes |
| Id |
string |
doc._id |
v.id(tableName) |
|
| Null |
null |
null |
v.null() |
JavaScript's undefined is not a valid Convex value. Functions the return undefined or do not return will return null when called from a client. Use null instead. |
| Int64 |
bigint |
3n |
v.int64() |
Int64s only support BigInts between -2^63 and 2^63-1. Convex supports bigints in most modern browsers. |
| Float64 |
number |
3.1 |
v.number() |
Convex supports all IEEE-754 double-precision floating point numbers (such as NaNs). Inf and NaN are JSON serialized as strings. |
| Boolean |
boolean |
true |
v.boolean() |
|
| String |
string |
"abc" |
v.string() |
Strings are stored as UTF-8 and must be valid Unicode sequences. Strings must be smaller than the 1MB total size limit when encoded as UTF-8. |
| Bytes |
ArrayBuffer |
new ArrayBuffer(8) |
v.bytes() |
Convex supports first class bytestrings, passed in as ArrayBuffers. Bytestrings must be smaller than the 1MB total size limit for Convex types. |
| Array |
Array] |
[1, 3.2, "abc"] |
v.array(values) |
Arrays can have at most 8192 values. |
| Object |
Object |
{a: "abc"} |
v.object({property: value}) |
Convex only supports "plain old JavaScript objects" (objects that do not have a custom prototype). Objects can have at most 1024 entries. Field names must be nonempty and not start with "$" or "_". |
| Record |
Record |
{"a": "1", "b": "2"} |
v.record(keys, values) |
Records are objects at runtime, but can have dynamic keys. Keys must be only ASCII characters, nonempty, and not start with "$" or "_". |
Function registration
- Use
internalQuery, internalMutation, and internalAction to register internal functions. These functions are private and aren't part of an app's API. They can only be called by other Convex functions. These functions are always imported from ./_generated/server.
- Use
query, mutation, and action to register public functions. These functions are part of the public API and are exposed to the public Internet. Do NOT use query, mutation, or action to register sensitive internal functions that should be kept private.
- You CANNOT register a function through the
api or internal objects.
- ALWAYS include argument and return validators for all Convex functions. This includes all of
query, internalQuery, mutation, internalMutation, action, and internalAction. If a function doesn't return anything, include returns: v.null() as its output validator.
- If the JavaScript implementation of a Convex function doesn't have a return value, it implicitly returns
null.
Function calling
- Use
ctx.runQuery to call a query from a query, mutation, or action.
- Use
ctx.runMutation to call a mutation from a mutation or action.
- Use
ctx.runAction to call an action from an action.
- ONLY call an action from another action if you need to cross runtimes (e.g. from V8 to Node). Otherwise, pull out the shared code into a helper async function and call that directly instead.
- Try to use as few calls from actions to queries and mutations as possible. Queries and mutations are transactions, so splitting logic up into multiple calls introduces the risk of race conditions.
- All of these calls take in a
FunctionReference. Do NOT try to pass the callee function directly into one of these calls.
- When using
ctx.runQuery, ctx.runMutation, or ctx.runAction to call a function in the same file, specify a type annotation on the return value to work around TypeScript circularity limitations. For example,
export const f = query({ args: { name: v.string() }, returns: v.string(), handler: async (ctx, args) => { return "Hello " + args.name; }, }); export const g = query({ args: {}, returns: v.null(), handler: async (ctx, args) => { const result: string = await ctx.runQuery(api.example.f, { name: "Bob" }); return null; }, });
Function references
- Function references are pointers to registered Convex functions.
- Use the
api object defined by the framework in convex/_generated/api.ts to call public functions registered with query, mutation, or action.
- Use the
internal object defined by the framework in convex/_generated/api.ts to call internal (or private) functions registered with internalQuery, internalMutation, or internalAction.
- Convex uses file-based routing, so a public function defined in
convex/example.ts named f has a function reference of api.example.f.
- A private function defined in
convex/example.ts named g has a function reference of internal.example.g.
- Functions can also registered within directories nested within the
convex/ folder. For example, a public function h defined in convex/messages/access.ts has a function reference of api.messages.access.h.
Api design
- Convex uses file-based routing, so thoughtfully organize files with public query, mutation, or action functions within the
convex/ directory.
- Use
query, mutation, and action to define public functions.
- Use
internalQuery, internalMutation, and internalAction to define private, internal functions.
Pagination
Paginated queries are queries that return a list of results in incremental pages.
You can define pagination using the following syntax:
```ts
import { v } from "convex/values";
import { query, mutation } from "./_generated/server";
import { paginationOptsValidator } from "convex/server";
export const listWithExtraArg = query({
args: { paginationOpts: paginationOptsValidator, author: v.string() },
handler: async (ctx, args) => {
return await ctx.db
.query("messages")
.filter((q) => q.eq(q.field("author"), args.author))
.order("desc")
.paginate(args.paginationOpts);
},
});
```
Note: `paginationOpts` is an object with the following properties:
- `numItems`: the maximum number of documents to return (the validator is `v.number()`)
- `cursor`: the cursor to use to fetch the next page of documents (the validator is `v.union(v.string(), v.null())`)
A query that ends in .paginate() returns an object that has the following properties:
- page (contains an array of documents that you fetches)
- isDone (a boolean that represents whether or not this is the last page of documents)
- continueCursor (a string that represents the cursor to use to fetch the next page of documents)
Validator guidelines
v.bigint() is deprecated for representing signed 64-bit integers. Use v.int64() instead.
- Use
v.record() for defining a record type. v.map() and v.set() are not supported.
Schema guidelines
- Always define your schema in
convex/schema.ts.
- Always import the schema definition functions from
convex/server:
- System fields are automatically added to all documents and are prefixed with an underscore. The two system fields that are automatically added to all documents are
_creationTime which has the validator v.number() and _id which has the validator v.id(tableName).
- Always include all index fields in the index name. For example, if an index is defined as
["field1", "field2"], the index name should be "by_field1_and_field2".
- Index fields must be queried in the same order they are defined. If you want to be able to query by "field1" then "field2" and by "field2" then "field1", you must create separate indexes.
Typescript guidelines
- You can use the helper typescript type
Id imported from './_generated/dataModel' to get the type of the id for a given table. For example if there is a table called 'users' you can use Id<'users'> to get the type of the id for that table.
- If you need to define a
Record make sure that you correctly provide the type of the key and value in the type. For example a validator v.record(v.id('users'), v.string()) would have the type Record<Id<'users'>, string>. Below is an example of using Record with an Id type in a query:
ts import { query } from "./_generated/server"; import { Doc, Id } from "./_generated/dataModel"; export const exampleQuery = query({ args: { userIds: v.array(v.id("users")) }, returns: v.record(v.id("users"), v.string()), handler: async (ctx, args) => { const idToUsername: Record<Id<"users">, string> = {}; for (const userId of args.userIds) { const user = await ctx.db.get(userId); if (user) { users[user._id] = user.username; } } return idToUsername; }, });
- Be strict with types, particularly around id's of documents. For example, if a function takes in an id for a document in the 'users' table, take in
Id<'users'> rather than string.
- Always use
as const for string literals in discriminated union types.
- When using the
Array type, make sure to always define your arrays as const array: Array<T> = [...];
- When using the
Record type, make sure to always define your records as const record: Record<KeyType, ValueType> = {...};
- Always add
@types/node to your package.json when using any Node.js built-in modules.
Full text search guidelines
- A query for "10 messages in channel '#general' that best match the query 'hello hi' in their body" would look like:
const messages = await ctx.db
.query("messages")
.withSearchIndex("search_body", (q) =>
q.search("body", "hello hi").eq("channel", "#general"),
)
.take(10);
Query guidelines
- Do NOT use
filter in queries. Instead, define an index in the schema and use withIndex instead.
- Convex queries do NOT support
.delete(). Instead, .collect() the results, iterate over them, and call ctx.db.delete(row._id) on each result.
- Use
.unique() to get a single document from a query. This method will throw an error if there are multiple documents that match the query.
- When using async iteration, don't use
.collect() or .take(n) on the result of a query. Instead, use the for await (const row of query) syntax.
Ordering
- By default Convex always returns documents in ascending
_creationTime order.
- You can use
.order('asc') or .order('desc') to pick whether a query is in ascending or descending order. If the order isn't specified, it defaults to ascending.
- Document queries that use indexes will be ordered based on the columns in the index and can avoid slow table scans.
Mutation guidelines
- Use
ctx.db.replace to fully replace an existing document. This method will throw an error if the document does not exist.
- Use
ctx.db.patch to shallow merge updates into an existing document. This method will throw an error if the document does not exist.
Action guidelines
- Always add
"use node"; to the top of files containing actions that use Node.js built-in modules.
- Never use
ctx.db inside of an action. Actions don't have access to the database.
- Below is an example of the syntax for an action:
ts import { action } from "./_generated/server"; export const exampleAction = action({ args: {}, returns: v.null(), handler: async (ctx, args) => { console.log("This action does not return anything"); return null; }, });
Scheduling guidelines
Cron guidelines
- Only use the
crons.interval or crons.cron methods to schedule cron jobs. Do NOT use the crons.hourly, crons.daily, or crons.weekly helpers.
- Both cron methods take in a FunctionReference. Do NOT try to pass the function directly into one of these methods.
- Define crons by declaring the top-level
crons object, calling some methods on it, and then exporting it as default. For example,
ts import { cronJobs } from "convex/server"; import { internal } from "./_generated/api"; import { internalAction } from "./_generated/server"; const empty = internalAction({ args: {}, returns: v.null(), handler: async (ctx, args) => { console.log("empty"); }, }); const crons = cronJobs(); // Run `internal.crons.empty` every two hours. crons.interval("delete inactive users", { hours: 2 }, internal.crons.empty, {}); export default crons;
- You can register Convex functions within
crons.ts just like any other file.
- If a cron calls an internal function, always import the
internal object from '_generated/api`, even if the internal function is registered in the same file.
File storage guidelines
Convex includes file storage for large files like images, videos, and PDFs.
The ctx.storage.getUrl() method returns a signed URL for a given file. It returns null if the file doesn't exist.
Do NOT use the deprecated ctx.storage.getMetadata call for loading a file's metadata.
Instead, query the `_storage` system table. For example, you can use `ctx.db.system.get` to get an `Id<"_storage">`.
```
import { query } from "./_generated/server";
import { Id } from "./_generated/dataModel";
type FileMetadata = {
_id: Id<"_storage">;
_creationTime: number;
contentType?: string;
sha256: string;
size: number;
}
export const exampleQuery = query({
args: { fileId: v.id("_storage") },
returns: v.null();
handler: async (ctx, args) => {
const metadata: FileMetadata | null = await ctx.db.system.get(args.fileId);
console.log(metadata);
return null;
},
});
```
Convex storage stores items as Blob objects. You must convert all items to/from a Blob when using Convex storage.
Examples:
Example: chat-app
Task
Create a real-time chat application backend with AI responses. The app should:
- Allow creating users with names
- Support multiple chat channels
- Enable users to send messages to channels
- Automatically generate AI responses to user messages
- Show recent message history
The backend should provide APIs for:
1. User management (creation)
2. Channel management (creation)
3. Message operations (sending, listing)
4. AI response generation using OpenAI's GPT-4
Messages should be stored with their channel, author, and content. The system should maintain message order
and limit history display to the 10 most recent messages per channel.
Analysis
- Task Requirements Summary:
- Build a real-time chat backend with AI integration
- Support user creation
- Enable channel-based conversations
- Store and retrieve messages with proper ordering
- Generate AI responses automatically
- Main Components Needed:
- Database tables: users, channels, messages
- Public APIs for user/channel management
- Message handling functions
- Internal AI response generation system
- Context loading for AI responses
- Public API and Internal Functions Design:
Public Mutations:
- createUser:
- file path: convex/index.ts
- arguments: {name: v.string()}
- returns: v.object({userId: v.id("users")})
- purpose: Create a new user with a given name
- createChannel:
- file path: convex/index.ts
- arguments: {name: v.string()}
- returns: v.object({channelId: v.id("channels")})
- purpose: Create a new channel with a given name
- sendMessage:
- file path: convex/index.ts
- arguments: {channelId: v.id("channels"), authorId: v.id("users"), content: v.string()}
- returns: v.null()
- purpose: Send a message to a channel and schedule a response from the AI
Public Queries:
- listMessages:
- file path: convex/index.ts
- arguments: {channelId: v.id("channels")}
- returns: v.array(v.object({
_id: v.id("messages"),
_creationTime: v.number(),
channelId: v.id("channels"),
authorId: v.optional(v.id("users")),
content: v.string(),
}))
- purpose: List the 10 most recent messages from a channel in descending creation order
Internal Functions:
- generateResponse:
- file path: convex/index.ts
- arguments: {channelId: v.id("channels")}
- returns: v.null()
- purpose: Generate a response from the AI for a given channel
- loadContext:
- file path: convex/index.ts
- arguments: {channelId: v.id("channels")}
- returns: v.array(v.object({
_id: v.id("messages"),
_creationTime: v.number(),
channelId: v.id("channels"),
authorId: v.optional(v.id("users")),
content: v.string(),
}))
- writeAgentResponse:
- file path: convex/index.ts
- arguments: {channelId: v.id("channels"), content: v.string()}
- returns: v.null()
- purpose: Write an AI response to a given channel
- Schema Design:
- users
- validator: { name: v.string() }
- indexes:
- channels
- validator: { name: v.string() }
- indexes:
- messages
- validator: { channelId: v.id("channels"), authorId: v.optional(v.id("users")), content: v.string() }
- indexes
- by_channel: ["channelId"]
- Background Processing:
- AI response generation runs asynchronously after each user message
- Uses OpenAI's GPT-4 to generate contextual responses
- Maintains conversation context using recent message history
Implementation
package.json
{
"name": "chat-app",
"description": "This example shows how to build a chat app without authentication.",
"version": "1.0.0",
"dependencies": {
"convex": "^1.17.4",
"openai": "^4.79.0"
},
"devDependencies": {
"typescript": "^5.7.3"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"allowImportingTsExtensions": true,
"noEmit": true,
"jsx": "react-jsx"
},
"exclude": ["convex"],
"include": ["**/src/**/*.tsx", "**/src/**/*.ts", "vite.config.ts"]
}
convex/index.ts
import {
query,
mutation,
internalQuery,
internalMutation,
internalAction,
} from "./_generated/server";
import { v } from "convex/values";
import OpenAI from "openai";
import { internal } from "./_generated/api";
/**
* Create a user with a given name.
*/
export const createUser = mutation({
args: {
name: v.string(),
},
returns: v.id("users"),
handler: async (ctx, args) => {
return await ctx.db.insert("users", { name: args.name });
},
});
/**
* Create a channel with a given name.
*/
export const createChannel = mutation({
args: {
name: v.string(),
},
returns: v.id("channels"),
handler: async (ctx, args) => {
return await ctx.db.insert("channels", { name: args.name });
},
});
/**
* List the 10 most recent messages from a channel in descending creation order.
*/
export const listMessages = query({
args: {
channelId: v.id("channels"),
},
returns: v.array(
v.object({
_id: v.id("messages"),
_creationTime: v.number(),
channelId: v.id("channels"),
authorId: v.optional(v.id("users")),
content: v.string(),
}),
),
handler: async (ctx, args) => {
const messages = await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
.order("desc")
.take(10);
return messages;
},
});
/**
* Send a message to a channel and schedule a response from the AI.
*/
export const sendMessage = mutation({
args: {
channelId: v.id("channels"),
authorId: v.id("users"),
content: v.string(),
},
returns: v.null(),
handler: async (ctx, args) => {
const channel = await ctx.db.get(args.channelId);
if (!channel) {
throw new Error("Channel not found");
}
const user = await ctx.db.get(args.authorId);
if (!user) {
throw new Error("User not found");
}
await ctx.db.insert("messages", {
channelId: args.channelId,
authorId: args.authorId,
content: args.content,
});
await ctx.scheduler.runAfter(0, internal.index.generateResponse, {
channelId: args.channelId,
});
return null;
},
});
const openai = new OpenAI();
export const generateResponse = internalAction({
args: {
channelId: v.id("channels"),
},
returns: v.null(),
handler: async (ctx, args) => {
const context = await ctx.runQuery(internal.index.loadContext, {
channelId: args.channelId,
});
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: context,
});
const content = response.choices[0].message.content;
if (!content) {
throw new Error("No content in response");
}
await ctx.runMutation(internal.index.writeAgentResponse, {
channelId: args.channelId,
content,
});
return null;
},
});
export const loadContext = internalQuery({
args: {
channelId: v.id("channels"),
},
returns: v.array(
v.object({
role: v.union(v.literal("user"), v.literal("assistant")),
content: v.string(),
}),
),
handler: async (ctx, args) => {
const channel = await ctx.db.get(args.channelId);
if (!channel) {
throw new Error("Channel not found");
}
const messages = await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
.order("desc")
.take(10);
const result = [];
for (const message of messages) {
if (message.authorId) {
const user = await ctx.db.get(message.authorId);
if (!user) {
throw new Error("User not found");
}
result.push({
role: "user" as const,
content: `${user.name}: ${message.content}`,
});
} else {
result.push({ role: "assistant" as const, content: message.content });
}
}
return result;
},
});
export const writeAgentResponse = internalMutation({
args: {
channelId: v.id("channels"),
content: v.string(),
},
returns: v.null(),
handler: async (ctx, args) => {
await ctx.db.insert("messages", {
channelId: args.channelId,
content: args.content,
});
return null;
},
});
convex/schema.ts
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
export default defineSchema({
channels: defineTable({
name: v.string(),
}),
users: defineTable({
name: v.string(),
}),
messages: defineTable({
channelId: v.id("channels"),
authorId: v.optional(v.id("users")),
content: v.string(),
}).index("by_channel", ["channelId"]),
});
src/App.tsx
export default function App() {
return <div>Hello World</div>;
}
1---2name: convex-guidelines3description: Apply for convex-guidelines. --- description: Guidelines and best practices for building Convex projects, including database schema design, queries, mutations, and real-world examples globs: **/*.{ts,tsx,js,jsx}4---56# Convex guidelines78---9description: Guidelines and best practices for building Convex projects, including database schema design, queries, mutations, and real-world examples10globs: **/*.{ts,tsx,js,jsx}11---1213# Convex guidelines14## Function guidelines15### New function syntax16- ALWAYS use the new function syntax for Convex functions. For example:17 ```typescript18 import { query } from "./_generated/server";19 import { v } from "convex/values";20 export const f = query({21 args: {},22 returns: v.null(),23 handler: async (ctx, args) => {24 // Function body25 },26 });27 ```2829### Http endpoint syntax30- HTTP endpoints are defined in `convex/http.ts` and require an `httpAction` decorator. For example:31 ```typescript32 import { httpRouter } from "convex/server";33 import { httpAction } from "./_generated/server";34 const http = httpRouter();35 http.route({36 path: "/echo",37 method: "POST",38 handler: httpAction(async (ctx, req) => {39 const body = await req.bytes();40 return new Response(body, { status: 200 });41 }),42 });43 ```44- HTTP endpoints are always registered at the exact path you specify in the `path` field. For example, if you specify `/api/someRoute`, the endpoint will be registered at `/api/someRoute`.4546### Validators47- Below is an example of an array validator:48 ```typescript49 import { mutation } from "./_generated/server";50 import { v } from "convex/values";5152 export default mutation({53 args: {54 simpleArray: v.array(v.union(v.string(), v.number())),55 },56 handler: async (ctx, args) => {57 //...58 },59 });60 ```61- Below is an example of a schema with validators that codify a discriminated union type:62 ```typescript63 import { defineSchema, defineTable } from "convex/server";64 import { v } from "convex/values";6566 export default defineSchema({67 results: defineTable(68 v.union(69 v.object({70 kind: v.literal("error"),71 errorMessage: v.string(),72 }),73 v.object({74 kind: v.literal("success"),75 value: v.number(),76 }),77 ),78 )79 });80 ```81- Always use the `v.null()` validator when returning a null value. Below is an example query that returns a null value:82 ```typescript83 import { query } from "./_generated/server";84 import { v } from "convex/values";8586 export const exampleQuery = query({87 args: {},88 returns: v.null(),89 handler: async (ctx, args) => {90 console.log("This query returns a null value");91 return null;92 },93 });94 ```95- Here are the valid Convex types along with their respective validators:96 Convex Type | TS/JS type | Example Usage | Validator for argument validation and schemas | Notes |97| ----------- | ------------| -----------------------| -----------------------------------------------| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|98| Id | string | `doc._id` | `v.id(tableName)` | |99| Null | null | `null` | `v.null()` | JavaScript's `undefined` is not a valid Convex value. Functions the return `undefined` or do not return will return `null` when called from a client. Use `null` instead. |100| Int64 | bigint | `3n` | `v.int64()` | Int64s only support BigInts between -2^63 and 2^63-1. Convex supports `bigint`s in most modern browsers. |101| Float64 | number | `3.1` | `v.number()` | Convex supports all IEEE-754 double-precision floating point numbers (such as NaNs). Inf and NaN are JSON serialized as strings. |102| Boolean | boolean | `true` | `v.boolean()` |103| String | string | `"abc"` | `v.string()` | Strings are stored as UTF-8 and must be valid Unicode sequences. Strings must be smaller than the 1MB total size limit when encoded as UTF-8. |104| Bytes | ArrayBuffer | `new ArrayBuffer(8)` | `v.bytes()` | Convex supports first class bytestrings, passed in as `ArrayBuffer`s. Bytestrings must be smaller than the 1MB total size limit for Convex types. |105| Array | Array] | `[1, 3.2, "abc"]` | `v.array(values)` | Arrays can have at most 8192 values. |106| Object | Object | `{a: "abc"}` | `v.object({property: value})` | Convex only supports "plain old JavaScript objects" (objects that do not have a custom prototype). Objects can have at most 1024 entries. Field names must be nonempty and not start with "$" or "_". |107| Record | Record | `{"a": "1", "b": "2"}` | `v.record(keys, values)` | Records are objects at runtime, but can have dynamic keys. Keys must be only ASCII characters, nonempty, and not start with "$" or "_". |108109### Function registration110- Use `internalQuery`, `internalMutation`, and `internalAction` to register internal functions. These functions are private and aren't part of an app's API. They can only be called by other Convex functions. These functions are always imported from `./_generated/server`.111- Use `query`, `mutation`, and `action` to register public functions. These functions are part of the public API and are exposed to the public Internet. Do NOT use `query`, `mutation`, or `action` to register sensitive internal functions that should be kept private.112- You CANNOT register a function through the `api` or `internal` objects.113- ALWAYS include argument and return validators for all Convex functions. This includes all of `query`, `internalQuery`, `mutation`, `internalMutation`, `action`, and `internalAction`. If a function doesn't return anything, include `returns: v.null()` as its output validator.114- If the JavaScript implementation of a Convex function doesn't have a return value, it implicitly returns `null`.115116### Function calling117- Use `ctx.runQuery` to call a query from a query, mutation, or action.118- Use `ctx.runMutation` to call a mutation from a mutation or action.119- Use `ctx.runAction` to call an action from an action.120- ONLY call an action from another action if you need to cross runtimes (e.g. from V8 to Node). Otherwise, pull out the shared code into a helper async function and call that directly instead.121- Try to use as few calls from actions to queries and mutations as possible. Queries and mutations are transactions, so splitting logic up into multiple calls introduces the risk of race conditions.122- All of these calls take in a `FunctionReference`. Do NOT try to pass the callee function directly into one of these calls.123- When using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction` to call a function in the same file, specify a type annotation on the return value to work around TypeScript circularity limitations. For example,124 ```125 export const f = query({126 args: { name: v.string() },127 returns: v.string(),128 handler: async (ctx, args) => {129 return "Hello " + args.name;130 },131 });132133 export const g = query({134 args: {},135 returns: v.null(),136 handler: async (ctx, args) => {137 const result: string = await ctx.runQuery(api.example.f, { name: "Bob" });138 return null;139 },140 });141 ```142143### Function references144- Function references are pointers to registered Convex functions.145- Use the `api` object defined by the framework in `convex/_generated/api.ts` to call public functions registered with `query`, `mutation`, or `action`.146- Use the `internal` object defined by the framework in `convex/_generated/api.ts` to call internal (or private) functions registered with `internalQuery`, `internalMutation`, or `internalAction`.147- Convex uses file-based routing, so a public function defined in `convex/example.ts` named `f` has a function reference of `api.example.f`.148- A private function defined in `convex/example.ts` named `g` has a function reference of `internal.example.g`.149- Functions can also registered within directories nested within the `convex/` folder. For example, a public function `h` defined in `convex/messages/access.ts` has a function reference of `api.messages.access.h`.150151### Api design152- Convex uses file-based routing, so thoughtfully organize files with public query, mutation, or action functions within the `convex/` directory.153- Use `query`, `mutation`, and `action` to define public functions.154- Use `internalQuery`, `internalMutation`, and `internalAction` to define private, internal functions.155156### Pagination157- Paginated queries are queries that return a list of results in incremental pages.158- You can define pagination using the following syntax:159160 ```ts161 import { v } from "convex/values";162 import { query, mutation } from "./_generated/server";163 import { paginationOptsValidator } from "convex/server";164 export const listWithExtraArg = query({165 args: { paginationOpts: paginationOptsValidator, author: v.string() },166 handler: async (ctx, args) => {167 return await ctx.db168 .query("messages")169 .filter((q) => q.eq(q.field("author"), args.author))170 .order("desc")171 .paginate(args.paginationOpts);172 },173 });174 ```175 Note: `paginationOpts` is an object with the following properties:176 - `numItems`: the maximum number of documents to return (the validator is `v.number()`)177 - `cursor`: the cursor to use to fetch the next page of documents (the validator is `v.union(v.string(), v.null())`)178- A query that ends in `.paginate()` returns an object that has the following properties:179 - page (contains an array of documents that you fetches)180 - isDone (a boolean that represents whether or not this is the last page of documents)181 - continueCursor (a string that represents the cursor to use to fetch the next page of documents)182183184## Validator guidelines185- `v.bigint()` is deprecated for representing signed 64-bit integers. Use `v.int64()` instead.186- Use `v.record()` for defining a record type. `v.map()` and `v.set()` are not supported.187188## Schema guidelines189- Always define your schema in `convex/schema.ts`.190- Always import the schema definition functions from `convex/server`:191- System fields are automatically added to all documents and are prefixed with an underscore. The two system fields that are automatically added to all documents are `_creationTime` which has the validator `v.number()` and `_id` which has the validator `v.id(tableName)`.192- Always include all index fields in the index name. For example, if an index is defined as `["field1", "field2"]`, the index name should be "by_field1_and_field2".193- Index fields must be queried in the same order they are defined. If you want to be able to query by "field1" then "field2" and by "field2" then "field1", you must create separate indexes.194195## Typescript guidelines196- You can use the helper typescript type `Id` imported from './_generated/dataModel' to get the type of the id for a given table. For example if there is a table called 'users' you can use `Id<'users'>` to get the type of the id for that table.197- If you need to define a `Record` make sure that you correctly provide the type of the key and value in the type. For example a validator `v.record(v.id('users'), v.string())` would have the type `Record<Id<'users'>, string>`. Below is an example of using `Record` with an `Id` type in a query:198 ```ts199 import { query } from "./_generated/server";200 import { Doc, Id } from "./_generated/dataModel";201202 export const exampleQuery = query({203 args: { userIds: v.array(v.id("users")) },204 returns: v.record(v.id("users"), v.string()),205 handler: async (ctx, args) => {206 const idToUsername: Record<Id<"users">, string> = {};207 for (const userId of args.userIds) {208 const user = await ctx.db.get(userId);209 if (user) {210 users[user._id] = user.username;211 }212 }213214 return idToUsername;215 },216 });217 ```218- Be strict with types, particularly around id's of documents. For example, if a function takes in an id for a document in the 'users' table, take in `Id<'users'>` rather than `string`.219- Always use `as const` for string literals in discriminated union types.220- When using the `Array` type, make sure to always define your arrays as `const array: Array<T> = [...];`221- When using the `Record` type, make sure to always define your records as `const record: Record<KeyType, ValueType> = {...};`222- Always add `@types/node` to your `package.json` when using any Node.js built-in modules.223224## Full text search guidelines225- A query for "10 messages in channel '#general' that best match the query 'hello hi' in their body" would look like:226227const messages = await ctx.db228 .query("messages")229 .withSearchIndex("search_body", (q) =>230 q.search("body", "hello hi").eq("channel", "#general"),231 )232 .take(10);233234## Query guidelines235- Do NOT use `filter` in queries. Instead, define an index in the schema and use `withIndex` instead.236- Convex queries do NOT support `.delete()`. Instead, `.collect()` the results, iterate over them, and call `ctx.db.delete(row._id)` on each result.237- Use `.unique()` to get a single document from a query. This method will throw an error if there are multiple documents that match the query.238- When using async iteration, don't use `.collect()` or `.take(n)` on the result of a query. Instead, use the `for await (const row of query)` syntax.239### Ordering240- By default Convex always returns documents in ascending `_creationTime` order.241- You can use `.order('asc')` or `.order('desc')` to pick whether a query is in ascending or descending order. If the order isn't specified, it defaults to ascending.242- Document queries that use indexes will be ordered based on the columns in the index and can avoid slow table scans.243244245## Mutation guidelines246- Use `ctx.db.replace` to fully replace an existing document. This method will throw an error if the document does not exist.247- Use `ctx.db.patch` to shallow merge updates into an existing document. This method will throw an error if the document does not exist.248249## Action guidelines250- Always add `"use node";` to the top of files containing actions that use Node.js built-in modules.251- Never use `ctx.db` inside of an action. Actions don't have access to the database.252- Below is an example of the syntax for an action:253 ```ts254 import { action } from "./_generated/server";255256 export const exampleAction = action({257 args: {},258 returns: v.null(),259 handler: async (ctx, args) => {260 console.log("This action does not return anything");261 return null;262 },263 });264 ```265266## Scheduling guidelines267### Cron guidelines268- Only use the `crons.interval` or `crons.cron` methods to schedule cron jobs. Do NOT use the `crons.hourly`, `crons.daily`, or `crons.weekly` helpers.269- Both cron methods take in a FunctionReference. Do NOT try to pass the function directly into one of these methods.270- Define crons by declaring the top-level `crons` object, calling some methods on it, and then exporting it as default. For example,271 ```ts272 import { cronJobs } from "convex/server";273 import { internal } from "./_generated/api";274 import { internalAction } from "./_generated/server";275276 const empty = internalAction({277 args: {},278 returns: v.null(),279 handler: async (ctx, args) => {280 console.log("empty");281 },282 });283284 const crons = cronJobs();285286 // Run `internal.crons.empty` every two hours.287 crons.interval("delete inactive users", { hours: 2 }, internal.crons.empty, {});288289 export default crons;290 ```291- You can register Convex functions within `crons.ts` just like any other file.292- If a cron calls an internal function, always import the `internal` object from '_generated/api`, even if the internal function is registered in the same file.293294295## File storage guidelines296- Convex includes file storage for large files like images, videos, and PDFs.297- The `ctx.storage.getUrl()` method returns a signed URL for a given file. It returns `null` if the file doesn't exist.298- Do NOT use the deprecated `ctx.storage.getMetadata` call for loading a file's metadata.299300 Instead, query the `_storage` system table. For example, you can use `ctx.db.system.get` to get an `Id<"_storage">`.301 ```302 import { query } from "./_generated/server";303 import { Id } from "./_generated/dataModel";304305 type FileMetadata = {306 _id: Id<"_storage">;307 _creationTime: number;308 contentType?: string;309 sha256: string;310 size: number;311 }312313 export const exampleQuery = query({314 args: { fileId: v.id("_storage") },315 returns: v.null();316 handler: async (ctx, args) => {317 const metadata: FileMetadata | null = await ctx.db.system.get(args.fileId);318 console.log(metadata);319 return null;320 },321 });322 ```323- Convex storage stores items as `Blob` objects. You must convert all items to/from a `Blob` when using Convex storage.324325326# Examples:327## Example: chat-app328329### Task330```331Create a real-time chat application backend with AI responses. The app should:332- Allow creating users with names333- Support multiple chat channels334- Enable users to send messages to channels335- Automatically generate AI responses to user messages336- Show recent message history337338The backend should provide APIs for:3391. User management (creation)3402. Channel management (creation)3413. Message operations (sending, listing)3424. AI response generation using OpenAI's GPT-4343344Messages should be stored with their channel, author, and content. The system should maintain message order345and limit history display to the 10 most recent messages per channel.346347```348349### Analysis3501. Task Requirements Summary:351- Build a real-time chat backend with AI integration352- Support user creation353- Enable channel-based conversations354- Store and retrieve messages with proper ordering355- Generate AI responses automatically3563572. Main Components Needed:358- Database tables: users, channels, messages359- Public APIs for user/channel management360- Message handling functions361- Internal AI response generation system362- Context loading for AI responses3633643. Public API and Internal Functions Design:365Public Mutations:366- createUser:367 - file path: convex/index.ts368 - arguments: {name: v.string()}369 - returns: v.object({userId: v.id("users")})370 - purpose: Create a new user with a given name371- createChannel:372 - file path: convex/index.ts373 - arguments: {name: v.string()}374 - returns: v.object({channelId: v.id("channels")})375 - purpose: Create a new channel with a given name376- sendMessage:377 - file path: convex/index.ts378 - arguments: {channelId: v.id("channels"), authorId: v.id("users"), content: v.string()}379 - returns: v.null()380 - purpose: Send a message to a channel and schedule a response from the AI381382Public Queries:383- listMessages:384 - file path: convex/index.ts385 - arguments: {channelId: v.id("channels")}386 - returns: v.array(v.object({387 _id: v.id("messages"),388 _creationTime: v.number(),389 channelId: v.id("channels"),390 authorId: v.optional(v.id("users")),391 content: v.string(),392 }))393 - purpose: List the 10 most recent messages from a channel in descending creation order394395Internal Functions:396- generateResponse:397 - file path: convex/index.ts398 - arguments: {channelId: v.id("channels")}399 - returns: v.null()400 - purpose: Generate a response from the AI for a given channel401- loadContext:402 - file path: convex/index.ts403 - arguments: {channelId: v.id("channels")}404 - returns: v.array(v.object({405 _id: v.id("messages"),406 _creationTime: v.number(),407 channelId: v.id("channels"),408 authorId: v.optional(v.id("users")),409 content: v.string(),410 }))411- writeAgentResponse:412 - file path: convex/index.ts413 - arguments: {channelId: v.id("channels"), content: v.string()}414 - returns: v.null()415 - purpose: Write an AI response to a given channel4164174. Schema Design:418- users419 - validator: { name: v.string() }420 - indexes: <none>421- channels422 - validator: { name: v.string() }423 - indexes: <none>424- messages425 - validator: { channelId: v.id("channels"), authorId: v.optional(v.id("users")), content: v.string() }426 - indexes427 - by_channel: ["channelId"]4284295. Background Processing:430- AI response generation runs asynchronously after each user message431- Uses OpenAI's GPT-4 to generate contextual responses432- Maintains conversation context using recent message history433434435### Implementation436437#### package.json438```typescript439{440 "name": "chat-app",441 "description": "This example shows how to build a chat app without authentication.",442 "version": "1.0.0",443 "dependencies": {444 "convex": "^1.17.4",445 "openai": "^4.79.0"446 },447 "devDependencies": {448 "typescript": "^5.7.3"449 }450}451```452453#### tsconfig.json454```typescript455{456 "compilerOptions": {457 "target": "ESNext",458 "lib": ["DOM", "DOM.Iterable", "ESNext"],459 "skipLibCheck": true,460 "allowSyntheticDefaultImports": true,461 "strict": true,462 "forceConsistentCasingInFileNames": true,463 "module": "ESNext",464 "moduleResolution": "Bundler",465 "resolveJsonModule": true,466 "isolatedModules": true,467 "allowImportingTsExtensions": true,468 "noEmit": true,469 "jsx": "react-jsx"470 },471 "exclude": ["convex"],472 "include": ["**/src/**/*.tsx", "**/src/**/*.ts", "vite.config.ts"]473}474```475476#### convex/index.ts477```typescript478import {479 query,480 mutation,481 internalQuery,482 internalMutation,483 internalAction,484} from "./_generated/server";485import { v } from "convex/values";486import OpenAI from "openai";487import { internal } from "./_generated/api";488489/**490 * Create a user with a given name.491 */492export const createUser = mutation({493 args: {494 name: v.string(),495 },496 returns: v.id("users"),497 handler: async (ctx, args) => {498 return await ctx.db.insert("users", { name: args.name });499 },500});501502/**503 * Create a channel with a given name.504 */505export const createChannel = mutation({506 args: {507 name: v.string(),508 },509 returns: v.id("channels"),510 handler: async (ctx, args) => {511 return await ctx.db.insert("channels", { name: args.name });512 },513});514515/**516 * List the 10 most recent messages from a channel in descending creation order.517 */518export const listMessages = query({519 args: {520 channelId: v.id("channels"),521 },522 returns: v.array(523 v.object({524 _id: v.id("messages"),525 _creationTime: v.number(),526 channelId: v.id("channels"),527 authorId: v.optional(v.id("users")),528 content: v.string(),529 }),530 ),531 handler: async (ctx, args) => {532 const messages = await ctx.db533 .query("messages")534 .withIndex("by_channel", (q) => q.eq("channelId", args.channelId))535 .order("desc")536 .take(10);537 return messages;538 },539});540541/**542 * Send a message to a channel and schedule a response from the AI.543 */544export const sendMessage = mutation({545 args: {546 channelId: v.id("channels"),547 authorId: v.id("users"),548 content: v.string(),549 },550 returns: v.null(),551 handler: async (ctx, args) => {552 const channel = await ctx.db.get(args.channelId);553 if (!channel) {554 throw new Error("Channel not found");555 }556 const user = await ctx.db.get(args.authorId);557 if (!user) {558 throw new Error("User not found");559 }560 await ctx.db.insert("messages", {561 channelId: args.channelId,562 authorId: args.authorId,563 content: args.content,564 });565 await ctx.scheduler.runAfter(0, internal.index.generateResponse, {566 channelId: args.channelId,567 });568 return null;569 },570});571572const openai = new OpenAI();573574export const generateResponse = internalAction({575 args: {576 channelId: v.id("channels"),577 },578 returns: v.null(),579 handler: async (ctx, args) => {580 const context = await ctx.runQuery(internal.index.loadContext, {581 channelId: args.channelId,582 });583 const response = await openai.chat.completions.create({584 model: "gpt-4o",585 messages: context,586 });587 const content = response.choices[0].message.content;588 if (!content) {589 throw new Error("No content in response");590 }591 await ctx.runMutation(internal.index.writeAgentResponse, {592 channelId: args.channelId,593 content,594 });595 return null;596 },597});598599export const loadContext = internalQuery({600 args: {601 channelId: v.id("channels"),602 },603 returns: v.array(604 v.object({605 role: v.union(v.literal("user"), v.literal("assistant")),606 content: v.string(),607 }),608 ),609 handler: async (ctx, args) => {610 const channel = await ctx.db.get(args.channelId);611 if (!channel) {612 throw new Error("Channel not found");613 }614 const messages = await ctx.db615 .query("messages")616 .withIndex("by_channel", (q) => q.eq("channelId", args.channelId))617 .order("desc")618 .take(10);619620 const result = [];621 for (const message of messages) {622 if (message.authorId) {623 const user = await ctx.db.get(message.authorId);624 if (!user) {625 throw new Error("User not found");626 }627 result.push({628 role: "user" as const,629 content: `${user.name}: ${message.content}`,630 });631 } else {632 result.push({ role: "assistant" as const, content: message.content });633 }634 }635 return result;636 },637});638639export const writeAgentResponse = internalMutation({640 args: {641 channelId: v.id("channels"),642 content: v.string(),643 },644 returns: v.null(),645 handler: async (ctx, args) => {646 await ctx.db.insert("messages", {647 channelId: args.channelId,648 content: args.content,649 });650 return null;651 },652});653```654655#### convex/schema.ts656```typescript657import { defineSchema, defineTable } from "convex/server";658import { v } from "convex/values";659660export default defineSchema({661 channels: defineTable({662 name: v.string(),663 }),664665 users: defineTable({666 name: v.string(),667 }),668669 messages: defineTable({670 channelId: v.id("channels"),671 authorId: v.optional(v.id("users")),672 content: v.string(),673 }).index("by_channel", ["channelId"]),674});675```676677#### src/App.tsx678```typescript679export default function App() {680 return <div>Hello World</div>;681}682```683684