> ## Documentation Index
> Fetch the complete documentation index at: https://confect.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Functions

> Define and implement Convex queries, mutations, and actions with Confect.

Confect functions are defined as a [spec and impl](https://confect.dev/concepts/spec-impl-model.md) pair. The spec declares each function's name, arguments, and return type. The impl provides the handler logic.

## Function types

| Constructor | Description |
| - | - |
| `FunctionSpec.publicQuery` | Public query function |
| `FunctionSpec.publicPaginatedQuery` | Public [paginated query](#paginated-queries) function |
| `FunctionSpec.publicMutation` | Public mutation function |
| `FunctionSpec.publicAction` | Public action function |
| `FunctionSpec.internalQuery` | Internal query function |
| `FunctionSpec.internalPaginatedQuery` | Internal [paginated query](#paginated-queries) function |
| `FunctionSpec.internalMutation` | Internal mutation function |
| `FunctionSpec.internalAction` | Internal action function |

For Node.js actions, see [Node Actions](https://confect.dev/server/node-actions.md). To integrate plain Convex functions (for use with Convex components or other libraries), see [Plain Convex Functions](https://confect.dev/server/plain-convex-functions.md).

## Defining a spec

Each function spec defines the function's name, argument fields, and returns schema. The optional `args` callback returns a `Schema.Struct` field map and defaults to `{}` when omitted, while `returns` and the optional `error` are callbacks returning schemas. All provided callbacks are evaluated lazily the first time the function is invoked. Function specs are added to a `GroupSpec` and default-exported from a `*.spec.ts` file. See [The Spec/Impl Model](https://confect.dev/concepts/spec-impl-model.md) for a full walkthrough.

```ts confect/notes.spec.ts theme={null}
import { GroupSpec, FunctionSpec } from "@confect/core";
import * as Schema from "effect/Schema";

import notes from "./_generated/tables/notes";

const list = FunctionSpec.publicQuery({
  name: "list",
  returns: () => Schema.Array(notes.Doc),
});

export default GroupSpec.make().addFunction(list);
```

Run `confect codegen` after adding or changing specs.

### Experimental context reuse

To opt a group into Convex's experimental V8 context reuse, pass
`experimental_reuseContext: true` to `GroupSpec.make`:

```ts theme={null}
export default GroupSpec.make({ experimental_reuseContext: true }).addFunction(
  list,
);
```

Reuse can avoid evaluating the module graph and registering functions on every
query or mutation. It applies to all queries and mutations in that group,
including plain Convex functions, but does not extend to child groups. Actions
are unaffected, even in a mixed group. `GroupSpec.makeNode` does not accept this
option, and codegen warns if an opted-in group contains only actions. A function
in an opted-in group cannot be named `experimental_reuseContext`, because that
name is reserved for the generated flag.

> [!WARNING]
>
> This is an experimental upstream feature, not a guarantee of lower latency or
> persistent state. Audit the group's implementation and its dependencies before
> enabling it: module-level state and values captured by handlers can survive
> across calls and across users. Never retain authentication data, database
> contexts, or other request-specific values in globals or shared closures.
> Unbounded retained state can also exhaust the runtime's memory.

Confect still constructs its request services for each invocation; the flag
does not cache an Effect `Context`, a transaction, or a function result. Context
reuse is opportunistic, so handlers must behave correctly with a fresh context
on any call. A failed execution, including a typed error returned as a
`ConvexError`, prevents that context from being saved for reuse. Cold starts,
deployments, and calls routed to other isolates can still pay module startup
costs.

### Typed errors

A spec can also declare an optional `error` schema. When it does, the corresponding handler's `Effect` error channel is typed as that schema, and the failure is decoded for callers at every call site (React hooks, JS clients, and tests). See [Error Handling](https://confect.dev/server/error-handling.md) for the full walkthrough.

```ts theme={null}
import { FunctionSpec } from "@confect/core";
import * as Schema from "effect/Schema";

import { Id } from "./_generated/id";
import notes from "./_generated/tables/notes";

class NoteNotFound extends Schema.TaggedError<NoteNotFound>()("NoteNotFound", {
  noteId: Id("notes"),
}) {}

FunctionSpec.publicQuery({
  name: "getOrFail",
  args: () => ({ noteId: Id("notes") }),
  returns: () => notes.Doc,
  error: () => NoteNotFound,
});
```

### Paginated queries

Define a paginated query with `FunctionSpec.publicPaginatedQuery` (or `internalPaginatedQuery`). Instead of `returns`, pass an `item` schema—the type of one element in a page. The optional `args` field map declares only your own arguments; Confect composes the Convex-facing schemas for you, adding the `paginationOpts` argument (with all of Convex's [pagination protocol fields](https://docs.convex.dev/database/pagination)) and wrapping `item` in a `PaginationResult` returns schema.

```ts confect/notes.spec.ts theme={null}
import { FunctionSpec } from "@confect/core";
import * as Schema from "effect/Schema";

import notes from "./_generated/tables/notes";

FunctionSpec.publicPaginatedQuery({
  name: "listByAuthor",
  args: () => ({ author: Schema.String }), // optional; omit for no extra args
  item: () => notes.Doc,
});
```

Do not declare `paginationOpts` in `args`—it is added automatically, and declaring it yourself is a type (and runtime) error.

The handler receives the decoded args including `paginationOpts`, which it typically forwards directly to [`paginate`](https://confect.dev/server/database/reading#paginate):

```ts confect/notes.impl.ts theme={null}
FunctionImpl.make(
  databaseSchema,
  notes,
  "listByAuthor",
  ({ author, paginationOpts }) =>
    Effect.gen(function* () {
      const reader = yield* DatabaseReader;

      return yield* reader
        .table("notes")
        .index("by_creation_time", "desc")
        .paginate(paginationOpts, (q) => q.eq(q.field("author"), author));
    }).pipe(Effect.orDie),
);
```

Paginated queries support the optional `error` schema like any other function. On the client, consume them with [`usePaginatedQuery`](https://confect.dev/clients/react#usepaginatedquery).

## Implementing functions

Each function impl contains a handler that implements the function's logic. Function impls are composed into group impls using Effect layers.

The handler receives the decoded arguments as its first parameter and returns an `Effect`. Use the generated [services](https://confect.dev/concepts/services.md) (like `DatabaseReader`, `DatabaseWriter`, `Auth`, etc.) inside your handler to interact with Convex.

```ts confect/notes.impl.ts theme={null}
import { FunctionImpl, GroupImpl } from "@confect/server";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";

import databaseSchema from "./_generated/schema";
import { DatabaseReader } from "./_generated/services";
import notes from "./notes.spec";

const list = FunctionImpl.make(databaseSchema, notes, "list", () =>
  Effect.gen(function* () {
    const reader = yield* DatabaseReader;

    return yield* reader
      .table("notes")
      .index("by_creation_time", "desc")
      .collect();
  }).pipe(Effect.orDie),
);

export default GroupImpl.make(databaseSchema, notes).pipe(
  Layer.provide(list),
  GroupImpl.finalize,
);
```

`GroupImpl.finalize` is the per-group completeness check: it only typechecks once every function declared by the spec has been provided to the group layer.

> [!NOTE]
>
> Convex bundles a deployment into a single artifact, but a function's cold
> start only evaluates the module graph reachable from its entry point. Confect
> emits one Convex module per group, so cold-starting a function only evaluates
> its own group's spec, impl, and the tables it touches. To keep that cold start
> fast, import Effect from its submodule paths (`import * as Schema from
>     "effect/Schema"`) rather than the `effect` barrel in your `confect/` files—a
> barrel import pulls the whole `Schema` namespace into the module graph your
> function evaluates at cold start, even when you use only a small part of it.

## Logging

Use `Effect.log*` in your handlers. Confect routes logs through Convex's console
methods so their severity is preserved in the dashboard and log streams. This
applies to queries, mutations, actions, Node actions, and HTTP routes.

| Effect level | Console method | Convex severity |
| - | - | - |
| Trace and Debug | `console.debug` | `DEBUG` |
| Info | `console.info` | `INFO` |
| Warn | `console.warn` | `WARN` |
| Error and Fatal | `console.error` | `ERROR` |

`Effect.log` uses Info unless you change Effect's current log level. The default
minimum level is Info, so Debug and Trace remain hidden until you enable them:

```ts theme={null}
import * as Effect from "effect/Effect";
import * as References from "effect/References";

const debugOperation = Effect.logTrace("Entering operation").pipe(
  Effect.provideService(References.MinimumLogLevel, "Trace"),
);
```

`"Trace"` is a diagnostic severity, not a request to print a stack trace. Confect
doesn't call `console.trace` for Trace logs.

Each log payload retains the original Effect level, messages, cause, annotations,
log spans, timestamp, and fiber ID. Convex renders this payload as a string; it
doesn't promote the payload's properties into structured log-stream fields.

Confect preserves Effect's tracer logger and any additional loggers. To replace
the default output for a handler, provide your own `Logger.layer` inside its
effect. Use `Logger.layer([])` to disable logging there. The default logger is
also available as `ConvexLogger.logger` from `@confect/server/ConvexLogger`;
`ConvexLogger.layer` replaces only Effect's default console logger, leaving custom
loggers and the minimum level unchanged.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.