Module: server | Convex Developer Hub

Utilities for implementing server-side Convex query and mutation functions.

Code Generation

This module is typically used alongside generated server code.

To generate the server code, run npx convex dev in your Convex project. This will create a convex/_generated/server.js file with the following functions, typed for your schema:

If you aren't using TypeScript and code generation, you can use these untyped functions instead:

Example

Convex functions are defined by using either the query or mutation wrappers.

Queries receive a db that implements the GenericDatabaseReader interface.

import { query } from "./_generated/server";

export default query({
handler: async ({ db }, { arg1, arg2 }) => {
// Your (read-only) code here!
},
});

If your function needs to write to the database, such as inserting, updating, or deleting documents, use mutation instead which provides a db that implements the GenericDatabaseWriter interface.

import { mutation } from "./_generated/server";

export default mutation({
handler: async ({ db }, { arg1, arg2 }) => {
// Your mutation code here!
},
});

UserIdentityAttributes

Re-exports UserIdentityAttributes

FunctionType

Ƭ FunctionType: "query" | "mutation" | "action"

The type of a Convex function.

Defined in

server/api.ts:19


FunctionReference

Ƭ FunctionReference<Type, Visibility, Args, ReturnType, ComponentPath>: Object

A reference to a registered Convex function.

You can create a FunctionReference using the generated api utility:

import { api } from "../convex/_generated/api";

const reference = api.myModule.myFunction;

If you aren't using code generation, you can create references using anyApi:

import { anyApi } from "convex/server";

const reference = anyApi.myModule.myFunction;

Function references can be used to invoke functions from the client. For example, in React you can pass references to the useQuery hook:

const result = useQuery(api.myModule.myFunction);

Type parameters

NameTypeDescription
Typeextends FunctionTypeThe type of the function ("query", "mutation", or "action").
Visibilityextends FunctionVisibility = "public"The visibility of the function ("public" or "internal").
Argsextends DefaultFunctionArgs = anyThe arguments to this function. This is an object mapping argument names to their types.
ReturnTypeanyThe return type of this function.
ComponentPathstring | undefined-

Type declaration

NameType
_typeType
_visibilityVisibility
_argsArgs
_returnTypeReturnType
_componentPathComponentPath

Defined in

server/api.ts:52


ApiFromModules

Ƭ ApiFromModules<AllModules>: FilterApi<ApiFromModulesAllowEmptyNodes<AllModules>, FunctionReference<any, any, any, any>>

Given the types of all modules in the convex/ directory, construct the type of api.

api is a utility for constructing FunctionReferences.

Type parameters

NameTypeDescription
AllModulesextends Record<string, object>A type mapping module paths (like "dir/myModule") to the types of the modules.

Defined in

server/api.ts:255


FilterApi

Ƭ FilterApi<API, Predicate>: Expand<{ [mod in keyof API as FilterKeysInApi<mod, API[mod], Predicate>]: API[mod] extends Predicate ? API[mod] : FilterApi<API[mod], Predicate> }>

Filter a Convex deployment api object for functions which meet criteria, for example all public queries.

Type parameters

Name
API
Predicate

Defined in

server/api.ts:287


AnyApi

Ƭ AnyApi: Record<string, Record<string, AnyModuleDirOrFunc>>

The type that Convex api objects extend. If you were writing an api from scratch it should extend this type.

Defined in

server/api.ts:397


PartialApi

Ƭ PartialApi<API>: { [mod in keyof API]?: API[mod] extends FunctionReference<any, any, any, any> ? API[mod] : PartialApi<API[mod]> }

Recursive partial API, useful for defining a subset of an API when mocking or building custom api objects.

Type parameters

Name
API

Defined in

server/api.ts:405


FunctionArgs

Ƭ FunctionArgs<FuncRef>: FuncRef["_args"]

Given a FunctionReference, get the return type of the function.

This is represented as an object mapping argument names to values.

Type parameters

NameType
FuncRefextends AnyFunctionReference

Defined in

server/api.ts:439


OptionalRestArgs

Ƭ OptionalRestArgs<FuncRef>: FuncRef["_args"] extends EmptyObject ? [args?: EmptyObject] : [args: FuncRef["_args"]]

A tuple type of the (maybe optional) arguments to FuncRef.

This type is used to make methods involving arguments type safe while allowing skipping the arguments for functions that don't require arguments.

Type parameters

NameType
FuncRefextends AnyFunctionReference

Defined in

server/api.ts:450


ArgsAndOptions

Ƭ ArgsAndOptions<FuncRef, Options>: FuncRef["_args"] extends EmptyObject ? [args?: EmptyObject, options?: Options] : [args: FuncRef["_args"], options?: Options]

A tuple type of the (maybe optional) arguments to FuncRef, followed by an options object of type Options.

This type is used to make methods like useQuery type-safe while allowing

  1. Skipping arguments for functions that don't require arguments.
  2. Skipping the options object.

Type parameters

NameType
FuncRefextends AnyFunctionReference
OptionsOptions

Defined in

server/api.ts:464


FunctionReturnType

Ƭ FunctionReturnType<FuncRef>: FuncRef["_returnType"]

Given a FunctionReference, get the return type of the function.

Type parameters

NameType
FuncRefextends AnyFunctionReference

Defined in

server/api.ts:476


AuthConfig

Ƭ AuthConfig: Object

The value exported by your Convex project in auth.config.ts.

import { AuthConfig } from "convex/server";

export default {
providers: [
{
domain: "https://your.issuer.url.com",
applicationID: "your-application-id",
},
],
} satisfies AuthConfig;

Type declaration

NameType
providersAuthProvider[]

Defined in

server/authentication.ts:19


AuthProvider

Ƭ AuthProvider: { applicationID: string ; domain: string } | { type: "customJwt" ; applicationID?: string ; issuer: string ; jwks: string ; algorithm: "RS256" | "ES256" }

An authentication provider allowed to issue JWTs for your app.

See: https://docs.convex.dev/auth/advanced/custom-auth and https://docs.convex.dev/auth/advanced/custom-jwt

Defined in

server/authentication.ts:28


FunctionHandle

Ƭ FunctionHandle<Type, Args, ReturnType>: string & FunctionReference<Type, "internal", Args, ReturnType>

A serializable reference to a Convex function. Passing a this reference to another component allows that component to call this function during the current function execution or at any later time. Function handles are used like api.folder.function FunctionReferences, e.g. ctx.scheduler.runAfter(0, functionReference, args).

A function reference is stable across code pushes but it's possible the Convex function it refers to might no longer exist.

This is a feature of components, which are in beta. This API is unstable and may change in subsequent releases.

Type parameters

NameType
Typeextends FunctionType
Argsextends DefaultFunctionArgs = any
ReturnTypeany

Defined in

server/components/index.ts:35


ComponentDefinition

Ƭ ComponentDefinition<Exports>: Object

An object of this type should be the default export of a convex.config.ts file in a component definition directory.

This is a feature of components, which are in beta. This API is unstable and may change in subsequent releases.

Type parameters

NameType
Exportsextends ComponentExports = any

Type declaration

NameTypeDescription
use<Definition>(definition: Definition, options?: { name?: string }) => InstalledComponent<Definition>Install a component with the given definition in this component definition. Takes a component definition and an optional name. For editor tooling this method expects a ComponentDefinition but at runtime the object that is imported will be a ImportedComponentDefinition
__exportsExportsInternal type-only property tracking exports provided. Deprecated This is a type-only property, don't use it.

Defined in

server/components/index.ts:84


AnyChildComponents

Ƭ AnyChildComponents: Record<string, AnyComponentReference>

Defined in

server/components/index.ts:414


AnyComponents

Ƭ AnyComponents: AnyChildComponents

Defined in

server/components/index.ts:454


GenericDocument

Ƭ GenericDocument: Record<string, Value>

A document stored in Convex.

Defined in

server/data_model.ts:9


GenericFieldPaths

Ƭ GenericFieldPaths: string

A type describing all of the document fields in a table.

These can either be field names (like "name") or references to fields on nested objects (like "properties.name").

Defined in

server/data_model.ts:18


GenericIndexFields

Ƭ GenericIndexFields: string[]

A type describing the ordered fields in an index.

These can either be field names (like "name") or references to fields on nested objects (like "properties.name").

Defined in

server/data_model.ts:29


GenericTableIndexes

Ƭ GenericTableIndexes: Record<string, GenericIndexFields>

A type describing the indexes in a table.

It's an object mapping each index name to the fields in the index.

Defined in

server/data_model.ts:37


GenericSearchIndexConfig

Ƭ GenericSearchIndexConfig: Object

A type describing the configuration of a search index.

Type declaration

NameType
searchFieldstring
filterFieldsstring

Defined in

server/data_model.ts:43


GenericTableSearchIndexes

Ƭ GenericTableSearchIndexes: Record<string, GenericSearchIndexConfig>

A type describing all of the search indexes in a table.

This is an object mapping each index name to the config for the index.

Defined in

server/data_model.ts:54


GenericVectorIndexConfig

Ƭ GenericVectorIndexConfig: Object

A type describing the configuration of a vector index.

Type declaration

NameType
vectorFieldstring
dimensionsnumber
filterFieldsstring

Defined in

server/data_model.ts:63


GenericTableVectorIndexes

Ƭ GenericTableVectorIndexes: Record<string, GenericVectorIndexConfig>

A type describing all of the vector indexes in a table.

This is an object mapping each index name to the config for the index.

Defined in

server/data_model.ts:75


FieldTypeFromFieldPath

Ƭ FieldTypeFromFieldPath<Document, FieldPath>: FieldTypeFromFieldPathInner<Document, FieldPath> extends Value | undefined ? FieldTypeFromFieldPathInner<Document, FieldPath> : Value | undefined

The type of a field in a document.

Note that this supports both simple fields like "name" and nested fields like "properties.name".

If the field is not present in the document it is considered to be undefined.

Type parameters

NameType
Documentextends GenericDocument
FieldPathextends string

Defined in

server/data_model.ts:104


FieldTypeFromFieldPathInner

Ƭ FieldTypeFromFieldPathInner<Document, FieldPath>: FieldPath extends `${infer First}.${infer Second}` ? ValueFromUnion<Document, First, Record<never, never>> extends infer FieldValue ? FieldValue extends GenericDocument ? FieldTypeFromFieldPath<FieldValue, Second> : undefined : undefined : ValueFromUnion<Document, FieldPath, undefined>

The inner type of FieldTypeFromFieldPath.

It's wrapped in a helper to coerce the type to Value | undefined since some versions of TypeScript fail to infer this type correctly.

Type parameters

NameType
Documentextends GenericDocument
FieldPathextends string

Defined in

server/data_model.ts:120


GenericTableInfo

Ƭ GenericTableInfo: Object

A type describing the document type and indexes in a table.

Type declaration

NameType
documentGenericDocument
fieldPathsGenericFieldPaths
indexesGenericTableIndexes
searchIndexesGenericTableSearchIndexes
vectorIndexesGenericTableVectorIndexes

Defined in

server/data_model.ts:145


DocumentByInfo

Ƭ DocumentByInfo<TableInfo>: TableInfo["document"]

The type of a document in a table for a given GenericTableInfo.

Type parameters

NameType
TableInfoextends GenericTableInfo

Defined in

server/data_model.ts:157


FieldPaths

Ƭ FieldPaths<TableInfo>: TableInfo["fieldPaths"]

The field paths in a table for a given GenericTableInfo.

These can either be field names (like "name") or references to fields on nested objects (like "properties.name").

Type parameters

NameType
TableInfoextends GenericTableInfo

Defined in

server/data_model.ts:167


Indexes

Ƭ Indexes<TableInfo>: TableInfo["indexes"]

The database indexes in a table for a given GenericTableInfo.

This will be an object mapping index names to the fields in the index.

Type parameters

NameType
TableInfoextends GenericTableInfo

Defined in

server/data_model.ts:176


IndexNames

Ƭ IndexNames<TableInfo>: keyof Indexes<TableInfo>

The names of indexes in a table for a given GenericTableInfo.

Type parameters

NameType
TableInfoextends GenericTableInfo

Defined in

server/data_model.ts:182


NamedIndex

Ƭ NamedIndex<TableInfo, IndexName>: Indexes<TableInfo>[IndexName]

Extract the fields of an index from a GenericTableInfo by name.

Type parameters

NameType
TableInfoextends GenericTableInfo
IndexNameextends IndexNames<TableInfo>

Defined in

server/data_model.ts:189


SearchIndexes

Ƭ SearchIndexes<TableInfo>: TableInfo["searchIndexes"]

The search indexes in a table for a given GenericTableInfo.

This will be an object mapping index names to the search index config.

Type parameters

NameType
TableInfoextends GenericTableInfo

Defined in

server/data_model.ts:200


SearchIndexNames

Ƭ SearchIndexNames<TableInfo>: keyof SearchIndexes<TableInfo>

The names of search indexes in a table for a given GenericTableInfo.

Type parameters

NameType
TableInfoextends GenericTableInfo

Defined in

server/data_model.ts:207


NamedSearchIndex

Ƭ NamedSearchIndex<TableInfo, IndexName>: SearchIndexes<TableInfo>[IndexName]

Extract the config of a search index from a GenericTableInfo by name.

Type parameters

NameType
TableInfoextends GenericTableInfo
IndexNameextends SearchIndexNames<TableInfo>

Defined in

server/data_model.ts:214


VectorIndexes

Ƭ VectorIndexes<TableInfo>: TableInfo["vectorIndexes"]

The vector indexes in a table for a given GenericTableInfo.

This will be an object mapping index names to the vector index config.

Type parameters

NameType
TableInfoextends GenericTableInfo

Defined in

server/data_model.ts:225


VectorIndexNames

Ƭ VectorIndexNames<TableInfo>: keyof VectorIndexes<TableInfo>

The names of vector indexes in a table for a given GenericTableInfo.

Type parameters

NameType
TableInfoextends GenericTableInfo

Defined in

server/data_model.ts:232


NamedVectorIndex

Ƭ NamedVectorIndex<TableInfo, IndexName>: VectorIndexes<TableInfo>[IndexName]

Extract the config of a vector index from a GenericTableInfo by name.

Type parameters

NameType
TableInfoextends GenericTableInfo
IndexNameextends VectorIndexNames<TableInfo>

Defined in

server/data_model.ts:239


GenericDataModel

Ƭ GenericDataModel: Record<string, GenericTableInfo>

A type describing the tables in a Convex project.

This is designed to be code generated with npx convex dev.

Defined in

server/data_model.ts:252


AnyDataModel

Ƭ AnyDataModel: Object

A GenericDataModel that considers documents to be any and does not support indexes.

This is the default before a schema is defined.

Index signature

▪ [tableName: string]: { document: any ; fieldPaths: GenericFieldPaths ; indexes: ; searchIndexes: ; vectorIndexes: }

Defined in

server/data_model.ts:261


TableNamesInDataModel

Ƭ TableNamesInDataModel<DataModel>: keyof DataModel & string

A type of all of the table names defined in a GenericDataModel.

Type parameters

NameType
DataModelextends GenericDataModel

Defined in

server/data_model.ts:275


NamedTableInfo

Ƭ NamedTableInfo<DataModel, TableName>: DataModel[TableName]

Extract the TableInfo for a table in a GenericDataModel by table name.

Type parameters

NameType
DataModelextends GenericDataModel
TableNameextends keyof DataModel

Defined in

server/data_model.ts:284


DocumentByName

Ƭ DocumentByName<DataModel, TableName>: DataModel[TableName]["document"]

The type of a document in a GenericDataModel by table name.

Type parameters

NameType
DataModelextends GenericDataModel
TableNameextends TableNamesInDataModel<DataModel>

Defined in

server/data_model.ts:293


ExpressionOrValue

Ƭ ExpressionOrValue<T>: Expression<T> | T

An Expression or a constant Value

Type parameters

NameType
Textends Value | undefined

Defined in

server/filter_builder.ts:38


Cursor

Ƭ Cursor: string

An opaque identifier used for paginating a database query.

Cursors are returned from paginate and represent the point of the query where the page of results ended.

To continue paginating, pass the cursor back into paginate in the PaginationOptions object to fetch another page of results.

Note: Cursors can only be passed to exactly the same database query that they were generated from. You may not reuse a cursor between different database queries.

Defined in

server/pagination.ts:21


GenericMutationCtxWithTable

Ƭ GenericMutationCtxWithTable<DataModel>: Omit<GenericMutationCtx<DataModel>, "db"> & { db: GenericDatabaseWriterWithTable<DataModel> }

A set of services for use within Convex mutation functions.

The mutation context is passed as the first argument to any Convex mutation function run on the server.

You should generally use the MutationCtx type from "./_generated/server".

Type parameters

NameType
DataModelextends GenericDataModel

Defined in

server/registration.ts:163


GenericQueryCtxWithTable

Ƭ GenericQueryCtxWithTable<DataModel>: Omit<GenericQueryCtx<DataModel>, "db"> & { db: GenericDatabaseReaderWithTable<DataModel> }

A set of services for use within Convex query functions.

The query context is passed as the first argument to any Convex query function run on the server.

This differs from the MutationCtx because all of the services are read-only.

Type parameters

NameType
DataModelextends GenericDataModel

Defined in

server/registration.ts:255


DefaultFunctionArgs

Ƭ DefaultFunctionArgs: Record<string, unknown>

The default arguments type for a Convex query, mutation, or action function.

Convex functions always take an arguments object that maps the argument names to their values.

Defined in

server/registration.ts:411


ArgsArray

Ƭ ArgsArray: OneArgArray | NoArgsArray

An array of arguments to a Convex function.

Convex functions can take either a single DefaultFunctionArgs object or no args at all.

Defined in

server/registration.ts:434


ArgsArrayToObject

Ƭ ArgsArrayToObject<Args>: Args extends OneArgArray<infer ArgsObject> ? ArgsObject : EmptyObject

Convert an ArgsArray into a single object type.

Empty arguments arrays are converted to EmptyObject.

Type parameters

NameType
Argsextends ArgsArray

Defined in

server/registration.ts:449


FunctionVisibility

Ƭ FunctionVisibility: "public" | "internal"

A type representing the visibility of a Convex function.

Defined in

server/registration.ts:457


RegisteredMutation

Ƭ RegisteredMutation<Visibility, Args, Returns>: { isConvexFunction: true ; isMutation: true } & VisibilityProperties<Visibility>

A mutation function that is part of this app.

You can create a mutation by wrapping your function in mutationGeneric or internalMutationGeneric and exporting it.

Type parameters

NameType
Visibilityextends FunctionVisibility
Argsextends DefaultFunctionArgs
ReturnsReturns

Defined in

server/registration.ts:480


RegisteredQuery

Ƭ RegisteredQuery<Visibility, Args, Returns>: { isConvexFunction: true ; isQuery: true } & VisibilityProperties<Visibility>

A query function that is part of this app.

You can create a query by wrapping your function in queryGeneric or internalQueryGeneric and exporting it.

Type parameters

NameType
Visibilityextends FunctionVisibility
Argsextends DefaultFunctionArgs
ReturnsReturns

Defined in

server/registration.ts:509


RegisteredAction

Ƭ RegisteredAction<Visibility, Args, Returns>: { isConvexFunction: true ; isAction: true } & VisibilityProperties<Visibility>

An action that is part of this app.

You can create an action by wrapping your function in actionGeneric or internalActionGeneric and exporting it.

Type parameters

NameType
Visibilityextends FunctionVisibility
Argsextends DefaultFunctionArgs
ReturnsReturns

Defined in

server/registration.ts:538


PublicHttpAction

Ƭ PublicHttpAction: Object

An HTTP action that is part of this app's public API.

You can create public HTTP actions by wrapping your function in httpActionGeneric and exporting it.

Type declaration

NameType
isHttptrue

Defined in

server/registration.ts:567


UnvalidatedFunction

Ƭ UnvalidatedFunction<Ctx, Args, Returns>: (ctx: Ctx, ...args: Args) => Returns | { handler: (ctx: Ctx, ...args: Args) => Returns }

Deprecated

-- See the type definition for MutationBuilder or similar for the types used for defining Convex functions.

The definition of a Convex query, mutation, or action function without argument validation.

Convex functions always take a context object as their first argument and an (optional) args object as their second argument.

This can be written as a function like:

import { query } from "./_generated/server";

export const func = query(({ db }, { arg }) => {...});

or as an object like:

import { query } from "./_generated/server";

export const func = query({
handler: ({ db }, { arg }) => {...},
});

See ValidatedFunction to add argument validation.

Type parameters

NameType
CtxCtx
Argsextends ArgsArray
ReturnsReturns

Defined in

server/registration.ts:605


ReturnValueForOptionalValidator

Ƭ ReturnValueForOptionalValidator<ReturnsValidator>: [ReturnsValidator] extends [Validator<any, any, any>] ? ValidatorTypeToReturnType<Infer<ReturnsValidator>> : [ReturnsValidator] extends [PropertyValidators] ? ValidatorTypeToReturnType<ObjectType<ReturnsValidator>> : any

There are multiple syntaxes for defining a Convex function:

 - query(async (ctx, args) => {...})
- query({ handler: async (ctx, args) => {...} })
- query({ args: { a: v.string }, handler: async (ctx, args) => {...} } })
- query({ args: { a: v.string }, returns: v.string(), handler: async (ctx, args) => {...} } })

In each of these, we want to correctly infer the type for the arguments and return value, preferring the type derived from a validator if it's provided.

To avoid having a separate overload for each, which would show up in error messages, we use the type params -- ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs.

The type for ReturnValue and OneOrZeroArgs are constrained by the type or ArgsValidator and ReturnsValidator if they're present, and inferred from any explicit type annotations to the arguments or return value of the function.

Below are a few utility types to get the appropriate type constraints based on an optional validator.

Additional tricks:

Type parameters

NameType
ReturnsValidatorextends Validator<any, any, any> | PropertyValidators | void

Defined in

server/registration.ts:707


ArgsArrayForOptionalValidator

Ƭ ArgsArrayForOptionalValidator<ArgsValidator>: [ArgsValidator] extends [Validator<any, any, any>] ? OneArgArray<Infer<ArgsValidator>> : [ArgsValidator] extends [PropertyValidators] ? OneArgArray<ObjectType<ArgsValidator>> : ArgsArray

Type parameters

NameType
ArgsValidatorextends GenericValidator | PropertyValidators | void

Defined in

server/registration.ts:715


DefaultArgsForOptionalValidator

Ƭ DefaultArgsForOptionalValidator<ArgsValidator>: [ArgsValidator] extends [Validator<any, any, any>] ? [Infer<ArgsValidator>] : [ArgsValidator] extends [PropertyValidators] ? [ObjectType<ArgsValidator>] : OneArgArray

Type parameters

NameType
ArgsValidatorextends GenericValidator | PropertyValidators | void

Defined in

server/registration.ts:723


MutationBuilder

Ƭ MutationBuilder<DataModel, Visibility>: <ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(mutation: { args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericMutationCtx<DataModel>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericMutationCtx<DataModel>, ...args: OneOrZeroArgs) => ReturnValue) => RegisteredMutation<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Type parameters

NameType
DataModelextends GenericDataModel
Visibilityextends FunctionVisibility

Type declaration

▸ <ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(mutation): RegisteredMutation<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Internal type helper used by Convex code generation.

Used to give mutationGeneric a type specific to your data model.

Type parameters
NameType
ArgsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnValueextends any = any
OneOrZeroArgsextends ArgsArray | OneArgArray<Infer<ArgsValidator>> | OneArgArray<Expand<{ [Property in string | number | symbol]?: Exclude<Infer<ArgsValidator[Property]>, undefined> } & { [Property in string | number | symbol]: Infer<ArgsValidator[Property]> }>> = DefaultArgsForOptionalValidator<ArgsValidator>
Parameters
NameType
mutation{ args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericMutationCtx<DataModel>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericMutationCtx<DataModel>, ...args: OneOrZeroArgs) => ReturnValue
Returns

RegisteredMutation<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Defined in

server/registration.ts:737


MutationBuilderWithTable

Ƭ MutationBuilderWithTable<DataModel, Visibility>: <ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(mutation: { args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericMutationCtxWithTable<DataModel>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericMutationCtxWithTable<DataModel>, ...args: OneOrZeroArgs) => ReturnValue) => RegisteredMutation<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Type parameters

NameType
DataModelextends GenericDataModel
Visibilityextends FunctionVisibility

Type declaration

▸ <ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(mutation): RegisteredMutation<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Internal type helper used by Convex code generation.

Used to give mutationGeneric a type specific to your data model.

Type parameters
NameType
ArgsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnValueextends any = any
OneOrZeroArgsextends ArgsArray | OneArgArray<Infer<ArgsValidator>> | OneArgArray<Expand<{ [Property in string | number | symbol]?: Exclude<Infer<ArgsValidator[Property]>, undefined> } & { [Property in string | number | symbol]: Infer<ArgsValidator[Property]> }>> = DefaultArgsForOptionalValidator<ArgsValidator>
Parameters
NameType
mutation{ args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericMutationCtxWithTable<DataModel>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericMutationCtxWithTable<DataModel>, ...args: OneOrZeroArgs) => ReturnValue
Returns

RegisteredMutation<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Defined in

server/registration.ts:830


QueryBuilder

Ƭ QueryBuilder<DataModel, Visibility>: <ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(query: { args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericQueryCtx<DataModel>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericQueryCtx<DataModel>, ...args: OneOrZeroArgs) => ReturnValue) => RegisteredQuery<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Type parameters

NameType
DataModelextends GenericDataModel
Visibilityextends FunctionVisibility

Type declaration

▸ <ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(query): RegisteredQuery<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Internal type helper used by Convex code generation.

Used to give queryGeneric a type specific to your data model.

Type parameters
NameType
ArgsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnValueextends any = any
OneOrZeroArgsextends ArgsArray | OneArgArray<Infer<ArgsValidator>> | OneArgArray<Expand<{ [Property in string | number | symbol]?: Exclude<Infer<ArgsValidator[Property]>, undefined> } & { [Property in string | number | symbol]: Infer<ArgsValidator[Property]> }>> = DefaultArgsForOptionalValidator<ArgsValidator>
Parameters
NameType
query{ args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericQueryCtx<DataModel>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericQueryCtx<DataModel>, ...args: OneOrZeroArgs) => ReturnValue
Returns

RegisteredQuery<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Defined in

server/registration.ts:923


QueryBuilderWithTable

Ƭ QueryBuilderWithTable<DataModel, Visibility>: <ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(query: { args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericQueryCtxWithTable<DataModel>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericQueryCtxWithTable<DataModel>, ...args: OneOrZeroArgs) => ReturnValue) => RegisteredQuery<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Type parameters

NameType
DataModelextends GenericDataModel
Visibilityextends FunctionVisibility

Type declaration

▸ <ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(query): RegisteredQuery<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Internal type helper used by Convex code generation.

Used to give queryGeneric a type specific to your data model.

Type parameters
NameType
ArgsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnValueextends any = any
OneOrZeroArgsextends ArgsArray | OneArgArray<Infer<ArgsValidator>> | OneArgArray<Expand<{ [Property in string | number | symbol]?: Exclude<Infer<ArgsValidator[Property]>, undefined> } & { [Property in string | number | symbol]: Infer<ArgsValidator[Property]> }>> = DefaultArgsForOptionalValidator<ArgsValidator>
Parameters
NameType
query{ args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericQueryCtxWithTable<DataModel>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericQueryCtxWithTable<DataModel>, ...args: OneOrZeroArgs) => ReturnValue
Returns

RegisteredQuery<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Defined in

server/registration.ts:1012


ActionBuilder

Ƭ ActionBuilder<DataModel, Visibility>: <ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(func: { args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericActionCtx<DataModel>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericActionCtx<DataModel>, ...args: OneOrZeroArgs) => ReturnValue) => RegisteredAction<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Type parameters

NameType
DataModelextends GenericDataModel
Visibilityextends FunctionVisibility

Type declaration

▸ <ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(func): RegisteredAction<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Internal type helper used by Convex code generation.

Used to give actionGeneric a type specific to your data model.

Type parameters
NameType
ArgsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnValueextends any = any
OneOrZeroArgsextends ArgsArray | OneArgArray<Infer<ArgsValidator>> | OneArgArray<Expand<{ [Property in string | number | symbol]?: Exclude<Infer<ArgsValidator[Property]>, undefined> } & { [Property in string | number | symbol]: Infer<ArgsValidator[Property]> }>> = DefaultArgsForOptionalValidator<ArgsValidator>
Parameters
NameType
func{ args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericActionCtx<DataModel>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericActionCtx<DataModel>, ...args: OneOrZeroArgs) => ReturnValue
Returns

RegisteredAction<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Defined in

server/registration.ts:1101


HttpActionBuilder

Ƭ HttpActionBuilder: (func: (ctx: GenericActionCtx<any>, request: Request) => Promise<Response>) => PublicHttpAction

Type declaration

▸ (func): PublicHttpAction

Internal type helper used by Convex code generation.

Used to give httpActionGeneric a type specific to your data model and functions.

Parameters
NameType
func(ctx: GenericActionCtx<any>, request: Request) => Promise<Response>
Returns

PublicHttpAction

Defined in

server/registration.ts:1196


RoutableMethod

Ƭ RoutableMethod: typeof ROUTABLE_HTTP_METHODS[number]

A type representing the methods supported by Convex HTTP actions.

HEAD is handled by Convex by running GET and stripping the body. CONNECT is not supported and will not be supported. TRACE is not supported and will not be supported.

Defined in

server/router.ts:31


RouteSpecWithPath

Ƭ RouteSpecWithPath: Object

A type representing a route to an HTTP action using an exact request URL path match.

Used by HttpRouter to route requests to HTTP actions.

Type declaration

NameTypeDescription
pathstringExact HTTP request path to route.
methodRoutableMethodHTTP method ("GET", "POST", ...) to route.
handlerPublicHttpActionThe HTTP action to execute.

Defined in

server/router.ts:56


RouteSpecWithPathPrefix

Ƭ RouteSpecWithPathPrefix: Object

A type representing a route to an HTTP action using a request URL path prefix match.

Used by HttpRouter to route requests to HTTP actions.

Type declaration

NameTypeDescription
pathPrefixstringAn HTTP request path prefix to route. Requests with a path starting with this value will be routed to the HTTP action.
methodRoutableMethodHTTP method ("GET", "POST", ...) to route.
handlerPublicHttpActionThe HTTP action to execute.

Defined in

server/router.ts:78


RouteSpec

Ƭ RouteSpec: RouteSpecWithPath | RouteSpecWithPathPrefix

A type representing a route to an HTTP action.

Used by HttpRouter to route requests to HTTP actions.

Defined in

server/router.ts:101


SchedulableFunctionReference

Ƭ SchedulableFunctionReference: FunctionReference<"mutation" | "action", "public" | "internal">

A FunctionReference that can be scheduled to run in the future.

Schedulable functions are mutations and actions that are public or internal.

Defined in

server/scheduler.ts:11


GenericSchema

Ƭ GenericSchema: Record<string, TableDefinition>

A type describing the schema of a Convex project.

This should be constructed using defineSchema, defineTable, and v.

Defined in

server/schema.ts:667


DataModelFromSchemaDefinition

Ƭ DataModelFromSchemaDefinition<SchemaDef>: MaybeMakeLooseDataModel<{ [TableName in keyof SchemaDef["tables"] & string]: SchemaDef["tables"][TableName] extends TableDefinition<infer DocumentType, infer Indexes, infer SearchIndexes, infer VectorIndexes> ? Object : never }, SchemaDef["strictTableNameTypes"]>

Internal type used in Convex code generation!

Convert a SchemaDefinition into a GenericDataModel.

Type parameters

NameType
SchemaDefextends SchemaDefinition<any, boolean>

Defined in

server/schema.ts:847


SystemTableNames

Ƭ SystemTableNames: TableNamesInDataModel<SystemDataModel>

Defined in

server/schema.ts:905


StorageId

Ƭ StorageId: string

A reference to a file in storage.

This is used in the StorageReader and StorageWriter which are accessible in Convex queries and mutations via QueryCtx and MutationCtx respectively.

Defined in

server/storage.ts:11


FileStorageId

Ƭ FileStorageId: GenericId<"_storage"> | StorageId

Defined in

server/storage.ts:12


FileMetadata

Ƭ FileMetadata: Object

Metadata for a single file as returned by storage.getMetadata.

Type declaration

NameTypeDescription
storageIdStorageIdID for referencing the file (eg. via storage.getUrl)
sha256stringHex encoded sha256 checksum of file contents
sizenumberSize of the file in bytes
contentTypestring | nullContentType of the file if it was provided on upload

Defined in

server/storage.ts:18


SystemFields

Ƭ SystemFields: Object

The fields that Convex automatically adds to documents, not including _id.

This is an object type mapping field name to field type.

Type declaration

NameType
_creationTimenumber

Defined in

server/system_fields.ts:11


IdField

Ƭ IdField<TableName>: Object

The _id field that Convex automatically adds to documents.

Type parameters

NameType
TableNameextends string

Type declaration

NameType
_idGenericId<TableName>

Defined in

server/system_fields.ts:19


WithoutSystemFields

Ƭ WithoutSystemFields<Document>: Expand<BetterOmit<Document, keyof SystemFields | "_id">>

A Convex document with the system fields like _id and _creationTime omitted.

Type parameters

NameType
Documentextends GenericDocument

Defined in

server/system_fields.ts:28


WithOptionalSystemFields

Ƭ WithOptionalSystemFields<Document>: Expand<WithoutSystemFields<Document> & Partial<Pick<Document, keyof SystemFields | "_id">>>

A Convex document with the system fields like _id and _creationTime optional.

Type parameters

NameType
Documentextends GenericDocument

Defined in

server/system_fields.ts:37


SystemIndexes

Ƭ SystemIndexes: Object

The indexes that Convex automatically adds to every table.

This is an object mapping index names to index field paths.

Type declaration

NameType
by_id["_id"]
by_creation_time["_creationTime"]

Defined in

server/system_fields.ts:48


IndexTiebreakerField

Ƭ IndexTiebreakerField: "_creationTime"

Convex automatically appends "_creationTime" to the end of every index to break ties if all of the other fields are identical.

Defined in

server/system_fields.ts:61


VectorSearch

Ƭ VectorSearch<DataModel, TableName, IndexName>: (tableName: TableName, indexName: IndexName, query: VectorSearchQuery<NamedTableInfo<DataModel, TableName>, IndexName>) => Promise<{ _id: GenericId<TableName> ; _score: number }[]>

Type parameters

NameType
DataModelextends GenericDataModel
TableNameextends TableNamesInDataModel<DataModel>
IndexNameextends VectorIndexNames<NamedTableInfo<DataModel, TableName>>

Type declaration

▸ (tableName, indexName, query): Promise<{ _id: GenericId<TableName> ; _score: number }[]>

Parameters
NameType
tableNameTableName
indexNameIndexName
queryVectorSearchQuery<NamedTableInfo<DataModel, TableName>, IndexName>
Returns

Promise<{ _id: GenericId<TableName> ; _score: number }[]>

Defined in

server/vector_search.ts:55


Expand

Ƭ Expand<ObjectType>: ObjectType extends Record<any, any> ? { [Key in keyof ObjectType]: ObjectType[Key] } : never

Hack! This type causes TypeScript to simplify how it renders object types.

It is functionally the identity for object types, but in practice it can simplify expressions like A & B.

Type parameters

NameType
ObjectTypeextends Record<any, any>

Defined in

type_utils.ts:12


BetterOmit

Ƭ BetterOmit<T, K>: { [Property in keyof T as Property extends K ? never : Property]: T[Property] }

An Omit<> type that:

  1. Applies to each element of a union.
  2. Preserves the index signature of the underlying type.

Type parameters

NameType
TT
Kextends keyof T

Defined in

type_utils.ts:24

anyApi

Const anyApi: AnyApi

A utility for constructing FunctionReferences in projects that are not using code generation.

You can create a reference to a function like:

const reference = anyApi.myModule.myFunction;

This supports accessing any path regardless of what directories and modules are in your project. All function references are typed as AnyFunctionReference.

If you're using code generation, use api from convex/_generated/api instead. It will be more type-safe and produce better auto-complete in your editor.

Defined in

server/api.ts:431


Const paginationOptsValidator: VObject<{ id: undefined | number ; endCursor: undefined | null | string ; maximumRowsRead: undefined | number ; maximumBytesRead: undefined | number ; numItems: number ; cursor: null | string }, { numItems: VFloat64<number, "required"> ; cursor: VUnion<null | string, [VString<string, "required">, VNull<null, "required">], "required", never> ; endCursor: VUnion<undefined | null | string, [VString<string, "required">, VNull<null, "required">], "optional", never> ; id: VFloat64<undefined | number, "optional"> ; maximumRowsRead: VFloat64<undefined | number, "optional"> ; maximumBytesRead: VFloat64<undefined | number, "optional"> }, "required", "id" | "numItems" | "cursor" | "endCursor" | "maximumRowsRead" | "maximumBytesRead">

A Validator for PaginationOptions.

Use this as the args validator in paginated query functions so that clients can pass pagination options.

Example

import { query } from "./_generated/server";
import { paginationOptsValidator } from "convex/server";
import { v } from "convex/values";

export const listMessages = query({
args: {
channelId: v.id("channels"),
paginationOpts: paginationOptsValidator,
},
handler: async (ctx, args) => {
return await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
.order("desc")
.paginate(args.paginationOpts);
},
});

On the client, use usePaginatedQuery from "convex/react":

const { results, status, loadMore } = usePaginatedQuery(
api.messages.listMessages,
{ channelId },
{ initialNumItems: 25 },
);

See

https://docs.convex.dev/database/pagination

Defined in

server/pagination.ts:163


ROUTABLE_HTTP_METHODS

Const ROUTABLE_HTTP_METHODS: readonly ["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"]

A list of the methods supported by Convex HTTP actions.

HEAD is handled by Convex by running GET and stripping the body. CONNECT is not supported and will not be supported. TRACE is not supported and will not be supported.

Defined in

server/router.ts:14

getFunctionName

getFunctionName(functionReference): string

Get the name of a function from a FunctionReference.

The name is a string like "myDir/myModule:myFunction". If the exported name of the function is "default", the function name is omitted (e.g. "myDir/myModule").

Parameters

NameTypeDescription
functionReferenceAnyFunctionReferenceA FunctionReference to get the name of.

Returns

string

A string of the function's name.

Defined in

server/api.ts:78


makeFunctionReference

makeFunctionReference<type, args, ret>(name): FunctionReference<type, "public", args, ret>

FunctionReferences generally come from generated code, but in custom clients it may be useful to be able to build one manually.

Real function references are empty objects at runtime, but the same interface can be implemented with an object for tests and clients which don't use code generation.

Type parameters

NameType
typeextends FunctionType
argsextends DefaultFunctionArgs = any
retany

Parameters

NameTypeDescription
namestringThe identifier of the function. E.g. path/to/file:functionName

Returns

FunctionReference<type, "public", args, ret>

Defined in

server/api.ts:122


filterApi

filterApi<API, Predicate>(api): FilterApi<API, Predicate>

Given an api of type API and a FunctionReference subtype, return an api object containing only the function references that match.

const q = filterApi<typeof api, FunctionReference<"query">>(api)

Type parameters

Name
API
Predicate

Parameters

NameType
apiAPI

Returns

FilterApi<API, Predicate>

Defined in

server/api.ts:305


createFunctionHandle

createFunctionHandle<Type, Args, ReturnType>(functionReference): Promise<FunctionHandle<Type, Args, ReturnType>>

Create a serializable reference to a Convex function. Passing a this reference to another component allows that component to call this function during the current function execution or at any later time. Function handles are used like api.folder.function FunctionReferences, e.g. ctx.scheduler.runAfter(0, functionReference, args).

A function reference is stable across code pushes but it's possible the Convex function it refers to might no longer exist.

This is a feature of components, which are in beta. This API is unstable and may change in subsequent releases.

Type parameters

NameType
Typeextends FunctionType
Argsextends DefaultFunctionArgs
ReturnTypeReturnType

Parameters

NameType
functionReferenceFunctionReference<Type, "public" | "internal", Args, ReturnType>

Returns

Promise<FunctionHandle<Type, Args, ReturnType>>

Defined in

server/components/index.ts:54


defineComponent

defineComponent<Exports>(name): ComponentDefinition<Exports>

Define a component, a piece of a Convex deployment with namespaced resources.

The default the default export of a module like "cool-component/convex.config.js" is a `@link ComponentDefinition}, but during component definition evaluation this is its type instead.

@param name Name must be alphanumeric plus underscores. Typically these are lowercase with underscores like "onboarding_flow_tracker".

This is a feature of components, which are in beta. This API is unstable and may change in subsequent releases.

Type parameters

NameType
Exportsextends ComponentExports = any

Parameters

NameType
namestring

Returns

ComponentDefinition<Exports>

Defined in

server/components/index.ts:371


defineApp

defineApp(): AppDefinition

Attach components, reuseable pieces of a Convex deployment, to this Convex app.

This is a feature of components, which are in beta. This API is unstable and may change in subsequent releases.

Returns

AppDefinition

Defined in

server/components/index.ts:397


componentsGeneric

componentsGeneric(): AnyChildComponents

Returns

AnyChildComponents

Defined in

server/components/index.ts:452


getFunctionAddress

getFunctionAddress(functionReference): { functionHandle: string = functionReference; name?: undefined ; reference?: undefined = referencePath } | { functionHandle?: undefined = functionReference; name: any ; reference?: undefined = referencePath } | { functionHandle?: undefined = functionReference; name?: undefined ; reference: string = referencePath }

Parameters

NameType
functionReferenceany

Returns

{ functionHandle: string = functionReference; name?: undefined ; reference?: undefined = referencePath } | { functionHandle?: undefined = functionReference; name: any ; reference?: undefined = referencePath } | { functionHandle?: undefined = functionReference; name?: undefined ; reference: string = referencePath }

Defined in

server/components/paths.ts:20


cronJobs

cronJobs(): Crons

Create a CronJobs object to schedule recurring tasks.

// convex/crons.js
import { cronJobs } from 'convex/server';
import { api } from "./_generated/api";

const crons = cronJobs();
crons.weekly(
"weekly re-engagement email",
{
hourUTC: 17, // (9:30am Pacific/10:30am Daylight Savings Pacific)
minuteUTC: 30,
},
api.emails.send
)
export default crons;

Returns

Crons

Defined in

server/cron.ts:180


mutationGeneric

mutationGeneric<ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(mutation): RegisteredMutation<"public", ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Define a mutation in this Convex app's public API.

You should generally use the mutation function from "./_generated/server".

Mutations can read from and write to the database, and are accessible from the client. They run transactionally, all database reads and writes within a single mutation are atomic and isolated from other mutations.

Example

import { mutation } from "./_generated/server";
import { v } from "convex/values";

export const createTask = mutation({
args: { text: v.string() },
returns: v.id("tasks"),
handler: async (ctx, args) => {
const taskId = await ctx.db.insert("tasks", {
text: args.text,
completed: false,
});
return taskId;
},
});

Best practice: Always include args and returns validators on all mutations. If the function doesn't return a value, use returns: v.null(). Argument validation is critical for security since public mutations are exposed to the internet.

Common mistake: Mutations cannot call third-party APIs or use fetch. They must be deterministic. Use actions for external API calls.

Common mistake: Do not use mutation for sensitive internal functions that should not be called by clients. Use internalMutation instead.

See

https://docs.convex.dev/functions/mutation-functions

Type parameters

NameType
ArgsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnValueextends any = any
OneOrZeroArgsextends ArgsArray | OneArgArray<Infer<ArgsValidator>> | OneArgArray<Expand<{ [Property in string | number | symbol]?: Exclude<Infer<ArgsValidator[Property]>, undefined> } & { [Property in string | number | symbol]: Infer<ArgsValidator[Property]> }>> = DefaultArgsForOptionalValidator<ArgsValidator>

Parameters

NameType
mutation{ args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericMutationCtx<any>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericMutationCtx<any>, ...args: OneOrZeroArgs) => ReturnValue

Returns

RegisteredMutation<"public", ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

The wrapped mutation. Include this as an export to name it and make it accessible.

Defined in

server/registration.ts:741


internalMutationGeneric

internalMutationGeneric<ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(mutation): RegisteredMutation<"internal", ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Define a mutation that is only accessible from other Convex functions (but not from the client).

You should generally use the internalMutation function from "./_generated/server".

Internal mutations can read from and write to the database but are not exposed as part of your app's public API. They can only be called by other Convex functions using ctx.runMutation or by the scheduler. Like public mutations, they run transactionally.

Example

import { internalMutation } from "./_generated/server";
import { v } from "convex/values";

// This mutation can only be called from other Convex functions:
export const markTaskCompleted = internalMutation({
args: { taskId: v.id("tasks") },
returns: v.null(),
handler: async (ctx, args) => {
await ctx.db.patch("tasks", args.taskId, { completed: true });
return null;
},
});

Best practice: Use internalMutation for any mutation that should not be directly callable by clients, such as write-back functions from actions or scheduled background work. Reference it via the internal object: await ctx.runMutation(internal.myModule.markTaskCompleted, { taskId }).

See

https://docs.convex.dev/functions/internal-functions

Type parameters

NameType
ArgsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnValueextends any = any
OneOrZeroArgsextends ArgsArray | OneArgArray<Infer<ArgsValidator>> | OneArgArray<Expand<{ [Property in string | number | symbol]?: Exclude<Infer<ArgsValidator[Property]>, undefined> } & { [Property in string | number | symbol]: Infer<ArgsValidator[Property]> }>> = DefaultArgsForOptionalValidator<ArgsValidator>

Parameters

NameType
mutation{ args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericMutationCtx<any>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericMutationCtx<any>, ...args: OneOrZeroArgs) => ReturnValue

Returns

RegisteredMutation<"internal", ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

The wrapped mutation. Include this as an export to name it and make it accessible.

Defined in

server/registration.ts:741


queryGeneric

queryGeneric<ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(query): RegisteredQuery<"public", ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Define a query in this Convex app's public API.

You should generally use the query function from "./_generated/server".

Queries can read from the database and are accessible from the client. They are reactive, when used with useQuery in React, the component automatically re-renders whenever the underlying data changes. Queries cannot modify the database. Query results are automatically cached by the Convex client and kept consistent via WebSocket subscriptions.

Example

import { query } from "./_generated/server";
import { v } from "convex/values";

export const listTasks = query({
args: { completed: v.optional(v.boolean()) },
returns: v.array(v.object({
_id: v.id("tasks"),
_creationTime: v.number(),
text: v.string(),
completed: v.boolean(),
})),
handler: async (ctx, args) => {
if (args.completed !== undefined) {
return await ctx.db
.query("tasks")
.withIndex("by_completed", (q) => q.eq("completed", args.completed))
.collect();
}
return await ctx.db.query("tasks").collect();
},
});

Best practice: Always include args and returns validators. Use .withIndex() instead of .filter() for efficient database queries. Queries should be fast since they run on every relevant data change.

Common mistake: Queries are pure reads, they cannot write to the database, call external APIs, or schedule functions. Use actions for HTTP calls and mutations for database writes and scheduling.

See

https://docs.convex.dev/functions/query-functions

Type parameters

NameType
ArgsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnValueextends any = any
OneOrZeroArgsextends ArgsArray | OneArgArray<Infer<ArgsValidator>> | OneArgArray<Expand<{ [Property in string | number | symbol]?: Exclude<Infer<ArgsValidator[Property]>, undefined> } & { [Property in string | number | symbol]: Infer<ArgsValidator[Property]> }>> = DefaultArgsForOptionalValidator<ArgsValidator>

Parameters

NameType
query{ args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericQueryCtx<any>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericQueryCtx<any>, ...args: OneOrZeroArgs) => ReturnValue

Returns

RegisteredQuery<"public", ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

The wrapped query. Include this as an export to name it and make it accessible.

Defined in

server/registration.ts:927


internalQueryGeneric

internalQueryGeneric<ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(query): RegisteredQuery<"internal", ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Define a query that is only accessible from other Convex functions (but not from the client).

You should generally use the internalQuery function from "./_generated/server".

Internal queries can read from the database but are not exposed as part of your app's public API. They can only be called by other Convex functions using ctx.runQuery. This is useful for loading data in actions or for helper queries that shouldn't be client-facing.

Example

import { internalQuery } from "./_generated/server";
import { v } from "convex/values";

// Only callable from other Convex functions:
export const getUser = internalQuery({
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("users", args.userId);
},
});

Best practice: Use internalQuery for data-loading in actions via ctx.runQuery(internal.myModule.getUser, { userId }).

See

https://docs.convex.dev/functions/internal-functions

Type parameters

NameType
ArgsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnValueextends any = any
OneOrZeroArgsextends ArgsArray | OneArgArray<Infer<ArgsValidator>> | OneArgArray<Expand<{ [Property in string | number | symbol]?: Exclude<Infer<ArgsValidator[Property]>, undefined> } & { [Property in string | number | symbol]: Infer<ArgsValidator[Property]> }>> = DefaultArgsForOptionalValidator<ArgsValidator>

Parameters

NameType
query{ args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericQueryCtx<any>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericQueryCtx<any>, ...args: OneOrZeroArgs) => ReturnValue

Returns

RegisteredQuery<"internal", ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

The wrapped query. Include this as an export to name it and make it accessible.

Defined in

server/registration.ts:927


actionGeneric

actionGeneric<ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(func): RegisteredAction<"public", ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Define an action in this Convex app's public API.

Actions can call third-party APIs, use Node.js libraries, and perform other side effects. Unlike queries and mutations, actions do not have direct database access (ctx.db is not available). Instead, use ctx.runQuery and ctx.runMutation to read and write data.

You should generally use the action function from "./_generated/server".

Actions are accessible from the client and run outside of the database transaction, so they are not atomic. They are best for integrating with external services.

Example

// Add "use node"; at the top of the file if using Node.js built-in modules.
import { action } from "./_generated/server";
import { v } from "convex/values";
import { internal } from "./_generated/api";

export const generateSummary = action({
args: { text: v.string() },
returns: v.string(),
handler: async (ctx, args) => {
// Call an external API:
const response = await fetch("https://api.example.com/summarize", {
method: "POST",
body: JSON.stringify({ text: args.text }),
});
const { summary } = await response.json();

// Write results back via a mutation:
await ctx.runMutation(internal.myModule.saveSummary, {
text: args.text,
summary,
});

return summary;
},
});

Best practice: Minimize the number of ctx.runQuery and ctx.runMutation calls from actions. Each call is a separate transaction, so splitting logic across multiple calls introduces the risk of race conditions. Try to batch reads/writes into single query/mutation calls.

"use node" runtime: Actions run in Convex's default JavaScript runtime, which supports fetch and most NPM packages. Only add "use node"; at the top of the file if a third-party library specifically requires Node.js built-in APIs, it is a last resort, not the default. Node.js actions have slower cold starts, and only actions can be defined in "use node" files (no queries or mutations), so prefer the default runtime whenever possible.

Common mistake: Do not try to access ctx.db in an action, it is not available. Use ctx.runQuery and ctx.runMutation instead.

See

https://docs.convex.dev/functions/actions

Type parameters

NameType
ArgsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnValueextends any = any
OneOrZeroArgsextends ArgsArray | OneArgArray<Infer<ArgsValidator>> | OneArgArray<Expand<{ [Property in string | number | symbol]?: Exclude<Infer<ArgsValidator[Property]>, undefined> } & { [Property in string | number | symbol]: Infer<ArgsValidator[Property]> }>> = DefaultArgsForOptionalValidator<ArgsValidator>

Parameters

NameTypeDescription
func{ args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericActionCtx<any>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericActionCtx<any>, ...args: OneOrZeroArgs) => ReturnValueThe function. It receives a GenericActionCtx as its first argument.

Returns

RegisteredAction<"public", ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

The wrapped function. Include this as an export to name it and make it accessible.

Defined in

server/registration.ts:1105


internalActionGeneric

internalActionGeneric<ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs>(func): RegisteredAction<"internal", ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

Define an action that is only accessible from other Convex functions (but not from the client).

You should generally use the internalAction function from "./_generated/server".

Internal actions behave like public actions (they can call external APIs and use Node.js libraries) but are not exposed in your app's public API. They can only be called by other Convex functions using ctx.runAction or via the scheduler.

Example

import { internalAction } from "./_generated/server";
import { v } from "convex/values";

export const sendEmail = internalAction({
args: { to: v.string(), subject: v.string(), body: v.string() },
returns: v.null(),
handler: async (ctx, args) => {
// Call an external email service (fetch works in the default runtime):
await fetch("https://api.email-service.com/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(args),
});
return null;
},
});

Best practice: Use internalAction for background work scheduled from mutations: await ctx.scheduler.runAfter(0, internal.myModule.sendEmail, { ... }). Only use ctx.runAction from another action if you need to cross runtimes (e.g., default Convex runtime to Node.js). Otherwise, extract shared code into a helper function.

"use node" runtime: Only add "use node"; at the top of the file as a last resort when a third-party library requires Node.js APIs. Node.js actions have slower cold starts, and only actions can be defined in "use node" files (no queries or mutations).

See

https://docs.convex.dev/functions/internal-functions

Type parameters

NameType
ArgsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnsValidatorextends void | Validator<any, "required", any> | PropertyValidators
ReturnValueextends any = any
OneOrZeroArgsextends ArgsArray | OneArgArray<Infer<ArgsValidator>> | OneArgArray<Expand<{ [Property in string | number | symbol]?: Exclude<Infer<ArgsValidator[Property]>, undefined> } & { [Property in string | number | symbol]: Infer<ArgsValidator[Property]> }>> = DefaultArgsForOptionalValidator<ArgsValidator>

Parameters

NameTypeDescription
func{ args?: ArgsValidator ; returns?: ReturnsValidator ; handler: (ctx: GenericActionCtx<any>, ...args: OneOrZeroArgs) => ReturnValue } | (ctx: GenericActionCtx<any>, ...args: OneOrZeroArgs) => ReturnValueThe function. It receives a GenericActionCtx as its first argument.

Returns

RegisteredAction<"internal", ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>

The wrapped function. Include this as an export to name it and make it accessible.

Defined in

server/registration.ts:1105


httpActionGeneric

httpActionGeneric(func): PublicHttpAction

Define a Convex HTTP action.

HTTP actions handle raw HTTP requests and return HTTP responses. They are registered by routing URL paths to them in convex/http.ts using HttpRouter. Like regular actions, they can call external APIs and use ctx.runQuery / ctx.runMutation but do not have direct ctx.db access.

Example

// convex/http.ts
import { httpRouter } from "convex/server";
import { httpAction } from "./_generated/server";

const http = httpRouter();

http.route({
path: "/api/webhook",
method: "POST",
handler: httpAction(async (ctx, request) => {
const body = await request.json();
// Process the webhook payload...
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}),
});

export default http;

Best practice: HTTP actions are registered at the exact path specified. For example, path: "/api/webhook" registers at /api/webhook.

See

https://docs.convex.dev/functions/http-actions

Parameters

NameTypeDescription
func(ctx: GenericActionCtx<GenericDataModel>, request: Request) => Promise<Response>The function. It receives a GenericActionCtx as its first argument, and a Request object as its second.

Returns

PublicHttpAction

The wrapped function. Route a URL path to this function in convex/http.ts.

Defined in

server/impl/registration_impl.ts:719


paginationResultValidator<T>(itemValidator): VObject<{ splitCursor: undefined | null | string ; pageStatus: undefined | null | "SplitRecommended" | "SplitRequired" ; page: T["type"][] ; continueCursor: string ; isDone: boolean }, { page: VArray<T["type"][], T, "required"> ; continueCursor: VString<string, "required"> ; isDone: VBoolean<boolean, "required"> ; splitCursor: VUnion<undefined | null | string, [VString<string, "required">, VNull<null, "required">], "optional", never> ; pageStatus: VUnion<undefined | null | "SplitRecommended" | "SplitRequired", [VLiteral<"SplitRecommended", "required">, VLiteral<"SplitRequired", "required">, VNull<null, "required">], "optional", never> }, "required", "page" | "continueCursor" | "isDone" | "splitCursor" | "pageStatus">

A Validator factory for PaginationResult.

Create a validator for the result of calling paginate with a given item validator.

For example:

const paginationResultValidator = paginationResultValidator(v.object({
_id: v.id("users"),
_creationTime: v.number(),
name: v.string(),
}));

Type parameters

NameType
Textends Validator<Value, "required", string>

Parameters

NameTypeDescription
itemValidatorTA validator for the items in the page

Returns

VObject<{ splitCursor: undefined | null | string ; pageStatus: undefined | null | "SplitRecommended" | "SplitRequired" ; page: T["type"][] ; continueCursor: string ; isDone: boolean }, { page: VArray<T["type"][], T, "required"> ; continueCursor: VString<string, "required"> ; isDone: VBoolean<boolean, "required"> ; splitCursor: VUnion<undefined | null | string, [VString<string, "required">, VNull<null, "required">], "optional", never> ; pageStatus: VUnion<undefined | null | "SplitRecommended" | "SplitRequired", [VLiteral<"SplitRecommended", "required">, VLiteral<"SplitRequired", "required">, VNull<null, "required">], "optional", never> }, "required", "page" | "continueCursor" | "isDone" | "splitCursor" | "pageStatus">

A validator for the pagination result

Defined in

server/pagination.ts:192


httpRouter

httpRouter(): HttpRouter

Return a new HttpRouter object.

Returns

HttpRouter

Defined in

server/router.ts:47


defineTable

defineTable<DocumentSchema>(documentSchema): TableDefinition<DocumentSchema>

Define a table in a schema.

You can either specify the schema of your documents as an object like

defineTable({
field: v.string()
});

or as a schema type like

defineTable(
v.union(
v.object({...}),
v.object({...})
)
);

Type parameters

NameType
DocumentSchemaextends Validator<Record<string, any>, "required", any>

Parameters

NameTypeDescription
documentSchemaDocumentSchemaThe type of documents stored in this table.

Returns

TableDefinition<DocumentSchema>

A TableDefinition for the table.

Defined in

server/schema.ts:615

defineTable<DocumentSchema>(documentSchema): TableDefinition<VObject<ObjectType<DocumentSchema>, DocumentSchema>>

Define a table in a schema.

You can either specify the schema of your documents as an object like

defineTable({
field: v.string()
});

or as a schema type like

defineTable(
v.union(
v.object({...}),
v.object({...})
)
);

Type parameters

NameType
DocumentSchemaextends Record<string, GenericValidator>

Parameters

NameTypeDescription
documentSchemaDocumentSchemaThe type of documents stored in this table.

Returns

TableDefinition<VObject<ObjectType<DocumentSchema>, DocumentSchema>>

A TableDefinition for the table.

Defined in

server/schema.ts:643


defineSchema

defineSchema<Schema, StrictTableNameTypes>(schema, options?): SchemaDefinition<Schema, StrictTableNameTypes>

Define the schema of this Convex project.

This should be exported as the default export from a schema.ts file in your convex/ directory. The schema enables runtime validation of documents and provides end-to-end TypeScript type safety.

Every document in Convex automatically has two system fields:

  • _id - a unique document ID with validator v.id("tableName")
  • _creationTime - a creation timestamp with validator v.number()

You do not need to include these in your schema definition, they are added automatically.

Example

// 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(),
}).index("by_email", ["email"]),

messages: defineTable({
body: v.string(),
userId: v.id("users"),
channelId: v.id("channels"),
}).index("by_channel", ["channelId"]),

channels: defineTable({
name: v.string(),
}),

// Discriminated union table:
results: defineTable(
v.union(
v.object({ kind: v.literal("error"), message: v.string() }),
v.object({ kind: v.literal("success"), value: v.number() }),
)
),
});

Best practice: Always include all index fields in the index name. For example, an index on ["field1", "field2"] should be named "by_field1_field2".

See

https://docs.convex.dev/database/schemas

Type parameters

NameType
Schemaextends GenericSchema
StrictTableNameTypesextends boolean = true

Parameters

NameTypeDescription
schemaSchemaA map from table name to TableDefinition for all of the tables in this project.
options?DefineSchemaOptions<StrictTableNameTypes>Optional configuration. See DefineSchemaOptions for a full description.

Returns

SchemaDefinition<Schema, StrictTableNameTypes>

The schema.

Defined in

server/schema.ts:830