# Foldkit Source: https://confect.dev/clients/foldkit Use Confect's Foldkit bindings to call your functions from a Foldkit app. `@confect/foldkit` bridges Confect into [Foldkit](https://foldkit.dev), The Elm Architecture in TypeScript powered by Effect. It maps Confect's client surface onto Foldkit's three integration seams: an application-scoped `Client` becomes a [resource](https://foldkit.dev/core/resources), reactive queries become [Subscription](https://foldkit.dev/core/subscriptions) entries, and queries, mutations, and actions become [Commands](https://foldkit.dev/core/commands). Args and return values are encoded and decoded through the [Effect Schemas](/concepts/schema-restrictions) in your [function specs](/concepts/spec-impl-model), and every failure is folded into a Message, so Command and Subscription error channels stay `never` as Foldkit requires. Functions are referenced via `refs` (from `confect/_generated/refs`) instead of Convex's `api` object, the same as with the other Confect clients. The bindings work with Confect functions only—refs for [plain Convex functions](/server/plain-convex-functions) carry no schemas, so they aren't accepted. ## Installation ```bash theme={null} pnpm add @confect/foldkit @confect/js @confect/core foldkit@^0.170.0 effect@~4.1.0 @effect/platform-browser@~4.1.0 ``` > [!NOTE] > > Use Foldkit 0.170.x with Effect and `@effect/platform-browser` 4.1.x. These > ranges accept patch updates but exclude new minor versions until the adapter > has verified them. The same Effect version also satisfies Confect's server and > CLI; no peer-dependency override is needed. ## Setup Pass the `Client` layer to your application's `resources`. The client combines the WebSocket API with the pagination-session allocator, lives for the lifetime of the app, and closes the WebSocket at teardown. ```ts src/entry.ts theme={null} import * as Confect from "@confect/foldkit"; import { Runtime } from "foldkit"; import { Model } from "./model"; import { init, update } from "./update"; import { view } from "./view"; import { subscriptions } from "./subscription"; const application = Runtime.makeApplication({ Model, init, update, view, subscriptions, resources: Confect.Client.layer(import.meta.env.VITE_CONVEX_URL), container: document.getElementById("root"), }); Runtime.run(application); ``` Commands and subscription entries built by `@confect/foldkit` require the `Confect.Client.Client` service, which this layer satisfies. `init` and `update` return records: `{ model, commands }`, with `commands` omitted when there are none. Updates that emit an OutMessage to a parent use `Update.ReturnWithOutMessage` and may also include `outMessage`. ## Reactive queries as Subscriptions `Subscription.reactiveQuery` builds a complete Foldkit subscription entry for a query ref. Its dependencies are the query args wrapped in an `Option` extracted from your Model: `None` closes the subscription, a change from one `Some` to another resubscribes with the new args, and structurally equal args leave the subscription running (dependency equivalence is derived from the ref's `args` schema). Declare your Messages with `defineMessageUnion` and use constructors on the `Message` namespace. In these examples, `Note` is your app's schema for a decoded note, matching the query's return schema: ```ts src/model.ts theme={null} import * as Schema from "effect/Schema"; import { defineMessageUnion } from "foldkit/message"; import { Note } from "./note"; export const Model = Schema.Struct({ selectedNoteId: Schema.Option(Schema.String), }); export type Model = typeof Model.Type; export const Message = defineMessageUnion({ SucceededGetNote: { note: Note }, FailedGetNote: { message: Schema.String }, SucceededGetNotes: { notes: Schema.Array(Note) }, FailedGetNotes: { message: Schema.String }, }); export type Message = typeof Message.Type; ``` ```ts src/subscription.ts theme={null} import * as Confect from "@confect/foldkit"; import * as Option from "effect/Option"; import * as Subscription from "foldkit/subscription"; import refs from "../confect/_generated/refs"; import { Message, type Model } from "./model"; export const subscriptions = Subscription.make< Model, Message, Confect.Client.Client >()(() => ({ note: Confect.Subscription.reactiveQuery()(refs.public.notes.get, { args: (model) => Option.map(model.selectedNoteId, (noteId) => ({ noteId })), onSuccess: (note) => Message.SucceededGetNote({ note }), onError: (error) => Message.FailedGetNote({ message: String(error) }), }), })); ``` `onSuccess` receives the decoded return value on every server update; `onError` receives the ref's decoded typed error (see [Error Handling](/server/error-handling)), a transport-level `WebSocketClientError`, or a `SchemaError`. Errors are emitted as Messages without ending the reactive query: Convex handles retryable infrastructure failures itself, and the same subscription can produce a later value if its query result recovers. Queries without args may omit the `args` extractor, which leaves the subscription always open: ```ts theme={null} Confect.Subscription.reactiveQuery()(refs.public.notes.list, { onSuccess: (notes) => Message.SucceededGetNotes({ notes }), onError: (error) => Message.FailedGetNotes({ message: String(error) }), }); ``` ### Custom entries When an entry needs extra dependencies or custom gating, write it by hand and use `Subscription.reactiveQueryStream` as its `dependenciesToStream` body: ```ts theme={null} import * as Confect from "@confect/foldkit"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as Subscription from "foldkit/subscription"; import refs from "../confect/_generated/refs"; import { Message, type Model } from "./model"; Subscription.make()((entry) => ({ note: entry( { noteId: Schema.Option(Schema.String) }, { modelToDependencies: (model) => ({ noteId: model.selectedNoteId }), dependenciesToStream: ({ noteId }) => Option.match(noteId, { onNone: () => Stream.empty, onSome: (selectedNoteId) => Confect.Subscription.reactiveQueryStream(refs.public.notes.get, { onSuccess: (note) => Message.SucceededGetNote({ note }), onError: (error) => Message.FailedGetNote({ message: String(error) }), })({ noteId: selectedNoteId }), }), }, ), })); ``` ## Commands `Command.query`, `Command.mutation`, and `Command.action` build Foldkit Command definitions whose Command args are the ref's args. `messages` declares the Messages the Command can produce—the same declaration Foldkit's own `Command.define` takes—and the handlers must produce instances of them. Call the definition from `update` to construct a Command instance—nothing runs until the Foldkit runtime executes it. Add `ClickedSave: {}`, `SucceededSaveNote: { noteId: Schema.String }`, and `FailedSaveNote: { message: Schema.String }` to your Message union, and a `draft: Schema.String` field to your Model: ```ts src/command.ts theme={null} import * as Confect from "@confect/foldkit"; import refs from "../confect/_generated/refs"; import { Message } from "./model"; export const SaveNote = Confect.Command.mutation( "SaveNote", refs.public.notes.insert, { messages: [Message.SucceededSaveNote, Message.FailedSaveNote], onSuccess: (noteId) => Message.SucceededSaveNote({ noteId }), onError: (error) => Message.FailedSaveNote({ message: String(error) }), }, ); ``` Add this handler to `Message.match` in `update`. Command-producing updates use `Update.Return` so their resource requirement reaches the runtime: ```ts theme={null} ClickedSave: () => ({ model, commands: [SaveNote({ text: model.draft })], }), ``` Follow Foldkit's [naming convention](https://foldkit.dev/core/commands): Commands are verb-first imperatives, result Messages are past-tense facts (`SucceededSaveNote`/`FailedSaveNote`). `onError` receives the same error union as subscriptions—`Confect.Command.Error` names it when you want to factor a handler out. ### Interruption Pass `interrupt` to make a factory-built Command [interruptible](https://foldkit.dev/core/commands). The returned definition gains an `Interrupt` constructor that builds an ordinary Command: it stops every in-flight invocation and results in `toMessage(outcome)`, where the outcome is `Interrupted` (at least one invocation was stopped—its result Messages are guaranteed never to dispatch) or `NotFound` (nothing was in flight). `interrupt: true` keys every invocation by the Command name—right when at most one invocation is meaningfully in flight. For the following examples, extend your Message union with `SucceededSaveDraft: { noteId: Schema.String }`, `FailedSaveDraft: { message: Schema.String }`, `SucceededDeleteNote: {}`, `FailedDeleteNote: { message: Schema.String }`, and `ClickedCancel: {}`. The cancellation result variants `CompletedCancelSaveDraft` and `CompletedCancelDeleteNote` both have `{ outcome: FoldkitCommand.Interruptible.Outcome }` fields, where `FoldkitCommand` is imported from `foldkit/command`: ```ts theme={null} export const SaveDraft = Confect.Command.mutation( "SaveDraft", refs.public.notes.insert, { messages: [Message.SucceededSaveDraft, Message.FailedSaveDraft], onSuccess: (noteId) => Message.SucceededSaveDraft({ noteId }), onError: (error) => Message.FailedSaveDraft({ message: String(error) }), interrupt: true, }, ); ``` Build the interrupt Command from its `Message.match` update handler: ```ts theme={null} ClickedCancel: () => ({ model, commands: [ SaveDraft.Interrupt((outcome) => Message.CompletedCancelSaveDraft({ outcome })), ], }), ``` `interrupt: { keyFields, toKey }` derives the key from the ref's args, so concurrent invocations can be interrupted independently. `Interrupt` then requires the key args: ```ts theme={null} export const DeleteNote = Confect.Command.mutation( "DeleteNote", refs.public.notes.delete, { messages: [Message.SucceededDeleteNote, Message.FailedDeleteNote], onSuccess: () => Message.SucceededDeleteNote(), onError: (error) => Message.FailedDeleteNote({ message: String(error) }), interrupt: { keyFields: ["noteId"], toKey: ({ noteId }) => noteId, }, }, ); export const cancelDelete = (model: Model, noteId: string) => ({ model, commands: [ DeleteNote.Interrupt({ noteId }, (outcome) => Message.CompletedCancelDeleteNote({ outcome }), ), ], }); ``` > [!NOTE] > > Interruption stops the client-side Effect and guarantees the invocation's > result Messages never dispatch—it does not cancel the Convex function on the > server. Once a mutation or action is on the wire, it runs to completion; > interruption means its result is ignored. Foldkit also runs a batch of > Commands concurrently with no ordering guarantee, so to cancel and replace, > dispatch the replacement from the Interrupt's result Message rather than > returning both Commands in one batch. ### Effect helpers `Command.queryEffect`, `Command.mutationEffect`, and `Command.actionEffect` return an execute body—an `Effect` whose failures are already folded into Messages—for hand-written `Command.define` calls. Reach for them when the Command needs a custom args schema or several calls in one Command: ```ts theme={null} import * as Confect from "@confect/foldkit"; import * as FoldkitCommand from "foldkit/command"; import * as Schema from "effect/Schema"; import refs from "../confect/_generated/refs"; import { Message } from "./model"; const saveNote = Confect.Command.mutationEffect(refs.public.notes.insert, { onSuccess: (noteId) => Message.SucceededSaveDraft({ noteId }), onError: (error) => Message.FailedSaveDraft({ message: String(error) }), }); export const SaveDraft = FoldkitCommand.define("SaveDraft", { args: { text: Schema.String, localDraftId: Schema.String }, messages: [Message.SucceededSaveDraft, Message.FailedSaveDraft], execute: ({ text }) => saveNote({ text }), }); ``` ## Query state in the Model Foldkit's [`AsyncData`](https://foldkit.dev/core/async-data) is the idiomatic Model representation for query state. Map errors to a view-ready schema type in your `onError` handler, then handle the result Messages with `Message.match` in `update`. This example replaces the earlier Model with a list-only Model: ```ts src/model.ts theme={null} import { AsyncData } from "foldkit"; import { defineMessageUnion } from "foldkit/message"; import * as Schema from "effect/Schema"; import { Note } from "./note"; export const Notes = AsyncData.Schema(Schema.Array(Note), Schema.String); export const Model = Schema.Struct({ notes: Notes.schema }); export type Model = typeof Model.Type; export const initialModel = Model.make({ notes: Notes.Idle() }); export const Message = defineMessageUnion({ SucceededGetNotes: { notes: Schema.Array(Note) }, FailedGetNotes: { message: Schema.String }, }); export type Message = typeof Message.Type; ``` ```ts src/update.ts theme={null} import type * as Update from "foldkit/update"; import { modifyFields } from "foldkit/struct"; import { Message, Model, Notes, initialModel } from "./model"; export const init = (): Update.Return => ({ model: initialModel, }); export const update = (model: Model, message: Message) => Message.match>(message, { SucceededGetNotes: ({ notes }) => ({ model: modifyFields(model, { notes: () => Notes.Success({ data: notes }), }), }), FailedGetNotes: ({ message: errorMessage }) => ({ model: modifyFields(model, { notes: () => Notes.Failure({ error: errorMessage }), }), }), }); ``` ## Paginated queries `PaginatedQuery` navigates a [paginated query](/server/functions#paginated-queries) one page at a time—next and previous—over Convex's cursor-based pagination. The machine lives in your Model and is the single source of truth for one live, reactive page subscription. Navigation and page-split handling are pure Model transitions, and `Subscription.paginatedQuery` keeps the subscription in sync with them. `PaginatedQuery.make` takes the ref and returns the machine's Model and correlated-settlement schemas together with its operations. The machine uses the same vocabulary as Foldkit's `AsyncData`: `Idle`, `Loading`, `Refreshing`, `Success`, `Failure`, and `Stale`. `Refreshing` and `Stale` retain the complete last good page. ```ts src/model.ts theme={null} import * as Confect from "@confect/foldkit"; import { defineMessageUnion } from "foldkit/message"; import * as Schema from "effect/Schema"; import refs from "../confect/_generated/refs"; export const Notes = Confect.PaginatedQuery.make(refs.public.notes.paginate); export const Model = Schema.Struct({ notes: Notes.schema, }); export type Model = typeof Model.Type; export const initialModel = Model.make({ notes: Notes.idle }); export const Message = defineMessageUnion({ OpenedNotes: { channel: Schema.String }, SettledGetNotesPage: { settlement: Notes.settlement }, ClickedNextPage: {}, ClosedNotes: {}, }); export type Message = typeof Message.Type; ``` Wire the subscription entry to the machine state: ```ts src/subscription.ts theme={null} import * as Confect from "@confect/foldkit"; import * as Subscription from "foldkit/subscription"; import { Message, Model, Notes } from "./model"; export const subscriptions = Subscription.make< Model, Message, Confect.Client.Client >()(() => ({ notesPage: Confect.Subscription.paginatedQuery()(Notes, { state: (model) => model.notes, onSettled: (settlement) => Message.SettledGetNotesPage({ settlement }), }), })); ``` When an active machine has no pagination id, the subscription allocates one from the application-scoped `Client`, opens the Convex query, and includes the id in its first `Result`-based settlement. `settle` installs the id and result atomically. Allocation is not a separate application event, and installing the id does not restart the live subscription. Like `AsyncData.settle`, a success becomes `Success`; a failure becomes `Stale` when a page is held and `Failure` otherwise. The request carries a logical generation as well as its cursor and page identity, so outcomes superseded by navigation, new args, close/reopen, or reset are ignored. All public machine operations remain pure: ```ts src/update.ts theme={null} import * as Confect from "@confect/foldkit"; import * as Match from "effect/Match"; import * as Option from "effect/Option"; import type * as Update from "foldkit/update"; import { modifyFields } from "foldkit/struct"; import { Message, Model, Notes, initialModel } from "./model"; export const init = (): Update.Return => ({ model: initialModel, }); export const update = (model: Model, message: Message) => Message.match>(message, { OpenedNotes: ({ channel }) => { const notes = Match.value(model.notes).pipe( Match.tag("Idle", (idle) => Notes.init(idle, { channel }, { initialNumItems: 20 }), ), Match.tag("Active", (active) => Notes.reinitialize(active, { channel }, { initialNumItems: 20 }), ), Match.exhaustive, ); return { model: modifyFields(model, { notes: () => notes }) }; }, SettledGetNotesPage: ({ settlement }) => ({ model: modifyFields(model, { notes: Confect.PaginatedQuery.settle(settlement), }), }), ClickedNextPage: () => { const notes = Match.value(model.notes).pipe( Match.tag("Idle", (idle) => idle), Match.tag("Active", (active) => Option.getOrElse(Confect.PaginatedQuery.next(active), () => active), ), Match.exhaustive, ); return { model: modifyFields(model, { notes: () => notes }) }; }, ClosedNotes: () => { const notes = Match.value(model.notes).pipe( Match.tag("Idle", (idle) => idle), Match.tag("Active", Confect.PaginatedQuery.close), Match.exhaustive, ); return { model: modifyFields(model, { notes: () => notes }) }; }, }); ``` `getPage` and `getItems` return `Option`s because the initial load can have no data. Once a page succeeds, they keep returning that page while the next one loads and after a refresh fails. `Page.number` is the page being displayed; `targetPageNumber` is the page currently requested, which can differ during a navigation: ```ts theme={null} import * as Confect from "@confect/foldkit"; import * as Match from "effect/Match"; import * as Option from "effect/Option"; import type { Model } from "./model"; export const describePage = (state: Model["notes"]) => { const items = Option.getOrElse( Confect.PaginatedQuery.getItems(state), () => [], ); const label = Match.value(state).pipe( Match.tag("Idle", () => "Closed"), Match.tag("Active", (active) => Option.match(Confect.PaginatedQuery.getPage(active), { onNone: () => `Loading page ${Confect.PaginatedQuery.targetPageNumber(active)}`, onSome: (page) => `Page ${page.number}`, }), ), Match.exhaustive, ); const nextDisabled = !Confect.PaginatedQuery.canNext(state); const prevDisabled = !Confect.PaginatedQuery.canPrev(state); return { items, label, nextDisabled, prevDisabled }; }; ``` `isIdle`, `isLoading`, `isRefreshing`, `isSuccess`, `isFailure`, and `isStale` are refinements; `isPending`, `hasPage`, `hasError`, and the exhaustive `match` cover the common view branches. A `Failure` or `Stale` does not close the subscription: Convex query errors are deterministic rather than manually retryable, and the live query may recover after its data, arguments, authentication, or deployment changes. Failed settlements carry an exhaustive error union: `FunctionError` wraps an error declared by the query or its middleware, `WebSocketClientError` represents an unexpected client failure, and `SchemaError` is carried directly from argument encoding or result decoding. Convex's `InvalidCursor` pseudo-error is also represented explicitly in settlements, but `settle` handles it internally by starting a fresh session at page one while retaining the displayed page. `first` is ordinary navigation back to page one within the current session. `reset` purely requests a fresh session at page one while retaining the displayed page, and `reinitialize` changes query args or page options and starts again from page one. `close` returns to `Idle` while retaining a generation tombstone, so a later `init` cannot accept a late first settlement from an earlier identical session. Options use Convex's names: `initialNumItems` is required, while `maximumRowsRead` and `maximumBytesRead` are optional positive integers. When you navigate forward, the page you leave is pinned to the range it displayed—from its cursor to its continuation cursor—so going back reloads exactly that range, however the data has moved since. This is what keeps consecutive pages gap-free and duplicate-free for [stream-paginated queries](/server/database/streams#paginating-a-stream), which have no query journal to remember page ranges. A newly requested, unpinned page is a live window requesting `initialNumItems` documents from its cursor. A page revisited through a pinned range, or pinned by a split, instead retains its boundaries and may contain more or fewer documents as data changes. > [!NOTE] > > Convex may signal that a page has grown too large by recommending or requiring > a page split. The machine handles the full protocol transparently: the current > page is pinned to end at the split point and reloads as a range query, and the > next page picks up from there. Users see at most a brief reload of the current > page—never a torn or incomplete one. If a reactive terminal page becomes > empty, the machine automatically retreats to the previous page. ## Authentication `setAuth` is available on the `Client` service. Wire it up as a Command. Add `CompletedSetAuth: {}` to your Message union; `fetchToken` should return an Effect that produces a token (or `null` when signed out) with no typed errors: ```ts theme={null} import * as Confect from "@confect/foldkit"; import * as Effect from "effect/Effect"; import * as FoldkitCommand from "foldkit/command"; import { Message } from "./model"; import { fetchToken } from "./auth"; export const SetAuth = FoldkitCommand.define("SetAuth", { messages: [Message.CompletedSetAuth], execute: Effect.flatMap(Confect.Client.Client, (client) => client.setAuth(({ forceRefreshToken }) => fetchToken(forceRefreshToken)), ).pipe(Effect.as(Message.CompletedSetAuth())), }); ``` ## Not yet covered An infinite-scroll, load-more counterpart to `@confect/react`'s `usePaginatedQuery` (a growing list of concurrently-live pages) is not yet built in. `PaginatedQuery` covers page-at-a-time navigation; for a growing list, paginated refs can be called through the underlying [`WebSocketClient`](/clients/js/websocket) service directly. # HTTP Source: https://confect.dev/clients/js/http Call your Confect functions over HTTP from any JavaScript runtime. `HttpClient` is an [Effect service](https://effect.website/docs/requirements-management/services/) that wraps Convex's [`ConvexHttpClient`](https://docs.convex.dev/api/classes/browser.ConvexHttpClient). It provides `query`, `mutation`, and `action` methods that accept refs and automatically encode args and decode return values through the schemas defined in your function specs. It works in any JavaScript runtime that supports `fetch`. ## Setup Create the `HttpClient` layer by passing your Convex deployment URL. ```ts theme={null} import { HttpClient } from "@confect/js"; import * as Effect from "effect/Effect"; const HttpClientLive = HttpClient.layer("https://example-123.convex.cloud"); ``` The layer can then be provided to any Effect that uses the `HttpClient` service. ## Calling functions Use the `HttpClient` service inside `Effect.gen` to call your functions with refs, the same way you would with `@confect/react` hooks or `@confect/test`. ```ts theme={null} import { HttpClient } from "@confect/js"; import * as Effect from "effect/Effect"; import refs from "./confect/_generated/refs"; const program = Effect.gen(function* () { const client = yield* HttpClient.HttpClient; const notes = yield* client.query(refs.public.notes.list); const noteId = yield* client.mutation(refs.public.notes.insert, { text: "Hello from the server", }); const result = yield* client.action(refs.public.random.getNumber); }); ``` Each method returns an `Effect` that can fail with `HttpClientError` (wrapping transport-level errors) or `ParseResult.ParseError` (if schema encoding or decoding fails). ## Typed errors When a ref's spec declares an `error` schema, the decoded error is added to the returned `Effect`'s error channel alongside `HttpClientError` and `ParseError`. See [Error Handling](/server/error-handling) for how to declare error schemas. ```ts theme={null} import { HttpClient } from "@confect/js"; import * as Effect from "effect/Effect"; import refs from "./confect/_generated/refs"; const lookup = Effect.gen(function* () { const client = yield* HttpClient.HttpClient; return yield* client.query(refs.public.notes.getOrFail, { noteId }); }); // Effect.Effect ``` Recover from a typed failure with `Effect.catchTag` (or any other `Effect` error combinator). ```ts theme={null} lookup.pipe( Effect.catchTag("NoteNotFound", (error) => Effect.succeed(`Note ${error.noteId} not found.`), ), ); ``` ## Authentication Set or clear the auth token before making authenticated requests. ```ts theme={null} Effect.gen(function* () { const client = yield* HttpClient.HttpClient; yield* client.setAuth(token); const identity = yield* client.query(refs.public.auth.getIdentity); yield* client.clearAuth; }); ``` ## Running programs Provide the `HttpClient` layer when running your program. ```ts theme={null} import { HttpClient } from "@confect/js"; import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; const HttpClientLive = HttpClient.layer("https://example-123.convex.cloud"); const program = Effect.gen(function* () { const client = yield* HttpClient.HttpClient; const notes = yield* client.query(refs.public.notes.list); yield* Console.log(notes); }); Effect.runPromise(program.pipe(Effect.provide(HttpClientLive))); ``` ## Differences from `ConvexHttpClient` | `ConvexHttpClient` | `HttpClient` | | - | - | | Functions referenced via `api.module.fn` | Functions referenced via `refs` | | Args passed directly to Convex as-is | Args are schema-encoded from `Type` to `Encoded` before sending | | Return values received directly as-is | Return values are schema-decoded from `Encoded` to `Type` | | Methods return `Promise` | Methods return `Effect` with typed errors | # WebSocket Source: https://confect.dev/clients/js/websocket Call your Confect functions and subscribe to reactive queries over a persistent WebSocket connection. `WebSocketClient` is an [Effect service](https://effect.website/docs/requirements-management/services/) that wraps Convex's [`ConvexClient`](https://docs.convex.dev/api/classes/browser.ConvexClient). It provides the same `query`, `mutation`, and `action` methods as [`HttpClient`](/clients/js/http), plus `reactiveQuery` and `reactiveQueryResult` methods that return [`Stream`](https://effect.website/docs/stream/introduction/) values. It works in any JavaScript environment that supports `WebSocket`. The WebSocket connection is managed as a [scoped resource](https://effect.website/docs/resource-management/scope/)—it is opened when the layer is provided and closed automatically when the scope ends. ## Setup Create the `WebSocketClient` layer by passing your Convex deployment URL. ```ts theme={null} import { WebSocketClient } from "@confect/js"; const WebSocketClientLive = WebSocketClient.layer( "https://example-123.convex.cloud", ); ``` The layer can then be provided to any Effect that uses the `WebSocketClient` service. The underlying WebSocket connection is closed automatically when the layer's scope ends—there is no need to close it manually. ## Calling functions Use the `WebSocketClient` service inside `Effect.gen` to call your functions with refs, the same way you would with `HttpClient`, `@confect/react` hooks, or `@confect/test`. ```ts theme={null} import { WebSocketClient } from "@confect/js"; import * as Effect from "effect/Effect"; import refs from "./confect/_generated/refs"; const program = Effect.gen(function* () { const client = yield* WebSocketClient.WebSocketClient; const notes = yield* client.query(refs.public.notes.list); const noteId = yield* client.mutation(refs.public.notes.insert, { text: "Hello from the server", }); const result = yield* client.action(refs.public.random.getNumber); }); ``` Each method returns an `Effect` that can fail with `WebSocketClientError` (wrapping transport-level errors) or `ParseResult.ParseError` (if schema encoding or decoding fails). ## Reactive queries `reactiveQuery` subscribes to a query over the WebSocket connection and returns a `Stream` that emits a new value whenever the query result changes on the server. ```ts theme={null} import { WebSocketClient } from "@confect/js"; import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; import * as Stream from "effect/Stream"; import refs from "./confect/_generated/refs"; const program = Effect.gen(function* () { const client = yield* WebSocketClient.WebSocketClient; yield* client .reactiveQuery(refs.public.notes.list) .pipe(Stream.runForEach((notes) => Console.log(notes))); }); ``` The underlying WebSocket subscription is cleaned up automatically when the stream's scope ends (for example, when the consuming Effect is interrupted or when an operator like `Stream.take` completes). ## Typed errors When a ref's spec declares an `error` schema, the decoded error is added to the error channel of `query`, `mutation`, `action`, and `reactiveQuery` alongside `WebSocketClientError` and `ParseError`. See [Error Handling](/server/error-handling) for how to declare error schemas. ```ts theme={null} import { WebSocketClient } from "@confect/js"; import * as Effect from "effect/Effect"; import refs from "./confect/_generated/refs"; const lookup = Effect.gen(function* () { const client = yield* WebSocketClient.WebSocketClient; return yield* client.query(refs.public.notes.getOrFail, { noteId }); }); // Effect.Effect ``` `reactiveQuery` uses the ordinary `Stream` error channel, so a query failure terminates that stream. Use `reactiveQueryResult` when an error should instead be one event in a continuing subscription. It emits `Result` values and keeps the underlying Convex listener open, allowing a later query result to recover naturally: ```ts theme={null} import { WebSocketClient } from "@confect/js"; import * as Effect from "effect/Effect"; import * as Result from "effect/Result"; import * as Stream from "effect/Stream"; import refs from "./confect/_generated/refs"; const lookups = Effect.gen(function* () { const client = yield* WebSocketClient.WebSocketClient; return client .reactiveQueryResult(refs.public.notes.getOrFail, { noteId }) .pipe( Stream.map( Result.match({ onSuccess: (note) => `Found: ${note.text}`, onFailure: (error) => `Lookup failed: ${String(error)}`, }), ), ); }); ``` ## Authentication Set the authentication token provider before making authenticated requests. `setAuth` accepts an Effect-returning function that is called whenever a token is needed or expires. ```ts theme={null} Effect.gen(function* () { const client = yield* WebSocketClient.WebSocketClient; yield* client.setAuth( ({ forceRefreshToken }) => Effect.promise(() => getToken({ forceRefreshToken })), (isAuthenticated) => Console.log(`Auth state changed: ${isAuthenticated}`), ); const identity = yield* client.query(refs.public.auth.getIdentity); }); ``` The optional second argument is a function that receives the current `isAuthenticated` status and returns an `Effect` to run whenever the authentication state changes. ## Running programs Provide the `WebSocketClient` layer when running your program. ```ts theme={null} import { WebSocketClient } from "@confect/js"; import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; import * as Stream from "effect/Stream"; const WebSocketClientLive = WebSocketClient.layer( "https://example-123.convex.cloud", ); const program = Effect.gen(function* () { const client = yield* WebSocketClient.WebSocketClient; yield* client.reactiveQuery(refs.public.notes.list).pipe( Stream.take(10), Stream.runForEach((notes) => Console.log(notes)), ); }); Effect.runPromise(program.pipe(Effect.provide(WebSocketClientLive))); ``` ## Differences from `ConvexClient` | `ConvexClient` | `WebSocketClient` | | - | - | | Functions referenced via `api.module.fn` | Functions referenced via `refs` | | Args passed directly to Convex as-is | Args are schema-encoded from `Type` to `Encoded` before sending | | Return values received directly as-is | Return values are schema-decoded from `Encoded` to `Type` | | `query`/`mutation`/`action` return `Promise` | `query`/`mutation`/`action` return `Effect` with typed errors | | `onUpdate` uses callbacks and returns an unsubscribe function | Reactive-query methods return a `Stream` with automatic cleanup | | Must call `close()` manually | Connection closed automatically when the layer's scope ends | | `setAuth` takes a `Promise`-returning callback | `setAuth` takes an `Effect`-returning function | # React Source: https://confect.dev/clients/react Use Confect's React hooks to call your functions from the client. `@confect/react` provides drop-in replacements for Convex's React hooks. Each hook automatically encodes your args and decodes return values through the [Effect Schemas](/concepts/schema-restrictions) defined in your [function specs](/concepts/spec-impl-model). You work with the Schema `Type` (decoded) values on both sides—the hooks handle the round-trip to Convex's `Encoded` representation transparently. Functions are referenced via `refs` (from `confect/_generated/refs`) instead of Convex's `api` object. Each ref carries the `args`, `returns`, and (optionally) `error` schemas from the corresponding function spec, which is what enables the automatic encoding and decoding. ## Setup The React provider setup is the same as vanilla Convex. ```tsx src/main.tsx theme={null} import { ConvexProvider, ConvexReactClient } from "convex/react"; import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; const convexClient = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL); ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( , ); ``` ## `useQuery` Encodes args using the spec's `args` schema, passes them to Convex, and decodes the result using the spec's `returns` schema. Returns a `QueryResult`—a tagged union with `Loading`, `Success`, and `Failure` variants. Given this spec: ```ts confect/notes.spec.ts theme={null} import { FunctionSpec, GroupSpec } from "@confect/core"; import * as Schema from "effect/Schema"; import notes from "./_generated/tables/notes"; export default GroupSpec.make().addFunction( FunctionSpec.publicQuery({ name: "list", returns: () => Schema.Array(notes.Doc), }), ); ``` The hook accepts `{}` (the `Type` of `Schema.Struct({})`) as args and returns a `QueryResult`. Match it with `QueryResult.match`: ```tsx theme={null} import { QueryResult, useQuery } from "@confect/react"; import refs from "../confect/_generated/refs"; const NoteList = () => { const notes = useQuery(refs.public.notes.list, {}); return QueryResult.match(notes, { onLoading: () =>

Loading…

, onSuccess: (notes) => (
    {notes.map((note) => (
  • {note.text}
  • ))}
), }); }; ``` `QueryResult` also exposes the lower-level predicates `QueryResult.isLoading`, `QueryResult.isSuccess`, and `QueryResult.isFailure` for cases where pattern matching is awkward. ### Typed errors When the ref's spec declares an `error` schema, `useQuery` returns `QueryResult` and `QueryResult.match` requires an `onFailure` handler that receives the decoded typed error. See [Error Handling](/server/error-handling) for how to declare error schemas. ```tsx theme={null} import { QueryResult, useQuery } from "@confect/react"; import refs from "../confect/_generated/refs"; const NoteLookup = ({ noteId }: { noteId: string }) => { const lookup = useQuery(refs.public.notes.getOrFail, { noteId }); return (
{QueryResult.match(lookup, { onLoading: () => "Looking up…", onSuccess: (note) => `Found: ${note.text}`, onFailure: (error) => `Note ${error.noteId} not found.`, })}
); }; ``` Failures that are not declared in the `error` schema are not surfaced as `Failure`. They propagate the same way they do with `convex/react`'s `useQuery` (typically reaching the nearest [error boundary](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)). ### Skipping queries Pass `"skip"` instead of args to disable the query subscription. The hook returns a `Loading` variant whose `skipped` flag is `true`, which lets you distinguish a query that is genuinely in flight from one sitting idle because no args have been provided. ```tsx theme={null} import { QueryResult, useQuery } from "@confect/react"; import refs from "../confect/_generated/refs"; const NoteDetail = ({ selectedId }: { selectedId: string | undefined }) => { const note = useQuery( refs.public.notes.get, selectedId !== undefined ? { id: selectedId } : "skip", ); return QueryResult.match(note, { onLoading: (skipped) =>

{skipped ? "Select a note" : "Loading…"}

, onSuccess: (note) =>

{note.text}

, }); }; ``` ## `usePaginatedQuery` Loads data reactively from a [paginated query](/server/functions#paginated-queries), mirroring the ergonomics of `usePaginatedQuery` from `convex/react`. The ref must come from a spec defined with `FunctionSpec.publicPaginatedQuery`—passing any other ref fails at runtime with an error pointing at the constructor. Args are encoded using the spec's user-args schema (`paginationOpts` is managed by the hook, not the caller), and each loaded page is decoded using the spec's `item` schema. Pass `"skip"` instead of args to disable the query, like `useQuery`. Returns a `PaginatedQueryResult`. The loaded variants—`LoadingFirstPage`, `LoadingMore`, `CanLoadMore`, and `Exhausted`—all carry `results` and `isLoading`, and `CanLoadMore` additionally carries `loadMore`, so the common UI needs only field access and a couple of predicates: ```tsx theme={null} import { PaginatedQueryResult, usePaginatedQuery } from "@confect/react"; import refs from "../confect/_generated/refs"; const PaginatedNoteList = () => { const notes = usePaginatedQuery( refs.public.notes.listByAuthor, { author: "ada" }, { initialNumItems: 10 }, ); return (
    {notes.results.map((note) => (
  • {note.text}
  • ))}
{notes.isLoading &&

Loading…

} {PaginatedQueryResult.isCanLoadMore(notes) && ( )}
); }; ``` `loadMore` lives only on `CanLoadMore`, the one state it can make progress from—the underlying Convex hook exposes it on every status, but calling it while a page is in flight, once the list is exhausted, or after a failure is an intentional no-op there. Narrowing with `isCanLoadMore` (or `match`'s `onCanLoadMore`) makes that statically apparent instead of silently dropping the call. `PaginatedQueryResult` also provides `match` for exhaustive pattern matching, and the predicates `isLoadingFirstPage`, `isLoadingMore`, `isExhausted`, `isLoading`, and `isFailure`. ### Typed errors When the spec declares an `error` schema, the result type gains a `Failure` variant carrying the decoded typed error—errors are values, consistent with `useQuery`. Narrow with `PaginatedQueryResult.isFailure` (or handle `onFailure` in `match`) to reach it: ```tsx theme={null} const notes = usePaginatedQuery( refs.public.notes.listOrFail, {}, { initialNumItems: 10 }, ); if (PaginatedQueryResult.isFailure(notes)) { // `results` holds the pages loaded before the failure, so they can still // be rendered alongside the error. return (

Failed to load more: {notes.error.reason}

); } // notes: narrowed to the non-`Failure` variants—isLoading is available too. ``` Every variant carries `results`, `Failure` included: when a later page fails, the pages already loaded are not discarded. Without an `error` schema, the `Failure` variant is excluded from the type entirely, so no narrowing is needed. Failures not declared in the `error` schema are thrown during render and propagate to the nearest [error boundary](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary). > [!NOTE] > > `usePaginatedQuery` requires `convex` 1.36.0 or newer. ## `useStreamPaginatedQuery` Loads data reactively from a paginated query whose handler paginates a [query stream](/server/database/streams#paginating-a-stream) with `QueryStream.paginate`. Those pages are not tracked by Convex's query journal, which `usePaginatedQuery` relies on to keep pages consistent as data changes, so this hook maintains that guarantee itself: every loaded page is pinned to a fixed index range by echoing its `continueCursor` back as the next subscription's `endCursor`. Adjacent pages always meet exactly, a document is never shown twice or lost between pages, and a page that outgrows `initialNumItems` is split in two when the server supplies a `splitCursor`. The call shape and the result are the same as `usePaginatedQuery`: args are encoded with the spec's user-args schema, pages are decoded with its `item` schema, `"skip"` disables the query, and the result is a `PaginatedQueryResult` with a `Failure` variant when the spec declares an `error` schema. ```tsx theme={null} import { PaginatedQueryResult, useStreamPaginatedQuery } from "@confect/react"; import refs from "../confect/_generated/refs"; const Feed = () => { const feed = useStreamPaginatedQuery( refs.public.notes.feed, {}, { initialNumItems: 10 }, ); return (
    {feed.results.map((note) => (
  • {note.text}
  • ))}
{feed.isLoading &&

Loading…

} {PaginatedQueryResult.isCanLoadMore(feed) && ( )}
); }; ``` The options also accept `maximumRowsRead` and `maximumBytesRead`, per-page read budgets forwarded to the server. When a budget stops a stream at a safe boundary, the server returns a partial page with `SplitRequired`, and the hook splits it. If the budget prevents safe progress or an interior split of a pinned page, `QueryStream.paginate` fails with `ReadBudgetExceededError` instead; the hook cannot resolve that by splitting. Increase the budget or reduce the query's reads. These budgets do not cover arbitrary I/O inside callbacks or guarantee that a query stays within Convex's limits; see [Read budgets](/server/database/streams#read-budgets). When the server fails a page with `paginationError: "InvalidCursor"`, the hook restarts pagination from the first page rather than failing. Stream queries emit this signal for malformed cursors, unsupported cursor versions, or mismatched runtime key-field layouts—not every change to query semantics. See [Cursor handling](/server/database/streams#cursor-handling). > [!NOTE] > > `useStreamPaginatedQuery` also works with paginated queries that use the > built-in `paginate`, since it only relies on the `endCursor` protocol field. > It subscribes to one query per loaded page. ## `useMutation` Returns a function that encodes args using the spec's `args` schema, calls the Convex mutation, and decodes the result using the spec's `returns` schema. The returned promise's shape depends on whether the spec declares an `error` schema. ### Without an `error` schema The function returns `Promise`, matching `convex/react`'s `useMutation`. Undeclared failures still reject the promise. ```ts confect/notes.spec.ts theme={null} import { Id } from "./_generated/id"; FunctionSpec.publicMutation({ name: "insert", args: () => ({ text: Schema.String }), returns: () => Id("notes"), }); ``` ```tsx theme={null} import { useMutation } from "@confect/react"; import refs from "../confect/_generated/refs"; const InsertNote = () => { const insertNote = useMutation(refs.public.notes.insert); return ( ); }; ``` ### With an `error` schema When the spec declares an `error` schema, the function returns `Promise>`. Unwrap with `Result.match` (or another `Result` combinator) to handle both branches. Undeclared failures still reject the promise. ```ts confect/notes.spec.ts theme={null} import { Id } from "./_generated/id"; FunctionSpec.publicMutation({ name: "deleteOrFail", args: () => ({ noteId: Id("notes") }), returns: () => Schema.Null, error: () => Schema.Union([NoteNotFound, Forbidden]), }); ``` ```tsx theme={null} import { useMutation } from "@confect/react"; import * as Result from "effect/Result"; import refs from "../confect/_generated/refs"; const DeleteNote = ({ noteId }: { noteId: string }) => { const deleteOrFail = useMutation(refs.public.notes.deleteOrFail); const handleClick = async () => { const result = await deleteOrFail({ noteId }); Result.match(result, { onFailure: (error) => console.error(error._tag, error), onSuccess: () => console.log("deleted"), }); }; return ; }; ``` ## `useAction` Same shape as `useMutation`: returns `Promise` when the ref has no `error` schema, and `Promise>` when it does. ```ts confect/random.spec.ts theme={null} FunctionSpec.publicAction({ name: "getNumber", returns: () => Schema.Number, }); ``` ```tsx theme={null} import { useAction } from "@confect/react"; import refs from "../confect/_generated/refs"; const RandomNumber = () => { const getRandom = useAction(refs.public.random.getNumber); const handleClick = () => { void getRandom({}).then(console.log); }; return ; }; ``` ## Differences from vanilla Convex hooks | Vanilla Convex | Confect | | - | - | | Functions referenced via `api.module.fn` | Functions referenced via `refs` | | Args passed directly to Convex as-is | Args are schema-encoded from `Type` to `Encoded` before sending to Convex | | Return values received directly from Convex as-is | Return values are schema-decoded from `Encoded` to `Type` before returning | | `useQuery` returns `T \| undefined` | `useQuery` returns `QueryResult` | | Cannot distinguish loading from skipped | `Loading` carries a `skipped: boolean` flag | | `useMutation`/`useAction` always return `Promise` | Refs with an `error` schema return `Promise>`; refs without one still return `Promise` | | `usePaginatedQuery` throws query errors during render | `usePaginatedQuery` returns `PaginatedQueryResult` with declared errors as a `Failure` variant | | Pass `"skip"` to disable query subscription | Same—pass `"skip"` to disable query subscription | # File Naming Conventions Source: https://confect.dev/concepts/file-naming-conventions Recommended patterns for organizing spec, impl, and related files in your confect directory. Confect requires a small number of fixed entry-point files in your `confect/` directory (see [Project Structure](/concepts/project-structure)). Beyond those, organize your API as colocated `*.spec.ts`/`*.impl.ts` pairs, one pair per group. The group's name is the file's path within `confect/` (its stem for top-level groups, the dot-joined directory path for nested groups). ## Spec and impl files Name each group's spec and impl with `.spec.ts` and `.impl.ts` suffixes. Each file must default-export its `GroupSpec` or `GroupImpl`; additional named exports on `.spec.ts` (for example error classes) are fine. A complete pair looks like this. The impl default-imports its sibling spec, passes it to `FunctionImpl.make` and `GroupImpl.make`, and finalizes the resulting layer with `GroupImpl.finalize`: ```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); ``` ```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, ); ``` Run `confect codegen` after adding or changing specs and impls. > [!NOTE] > > A file's path within `confect/` determines the public Convex API path it > produces—`confect/notes_and_random/notes.spec.ts` becomes > `api.notes_and_random.notes.list` for the public query above. Renaming a file > or directory renames the API path, so treat these paths as part of your API's > contract. > [!WARNING] > > Some test runners (such as Vitest and Jest) treat `.spec.ts` files as test > files by default. If your test runner is picking up Confect spec files, > configure it to exclude them. For example, in Vitest you can add > `"**/*.spec.ts"` to the `test.exclude` array in your config. ## Native Convex functions When a group wraps [native Convex functions](/server/plain-convex-functions) (for use with components or other libraries), place the plain function definitions in a file named after the group—without a suffix. This puts all three files for a group side by side: ``` confect/ workpool.ts ← native Convex function definitions workpool.spec.ts ← spec (type-only imports from workpool.ts) workpool.impl.ts ← impl (runtime imports from workpool.ts) ``` ## Middleware [Middleware](/server/middleware) is declared and implemented as a `*.spec.ts`/`*.impl.ts` pair too, but it belongs to no single group, so it lives in the reserved `confect/middleware/` directory—one pair per middleware, each named after the middleware in PascalCase. Confect does not scan that directory for groups, so nothing is emitted into `convex/` for it. ``` confect/ middleware/ RequireUser.spec.ts ← declaration: MiddlewareSpec.MiddlewareSpec (client-safe) RequireUser.impl.ts ← implementation: MiddlewareImpl layer (server-only) ``` Each spec module default-exports its middleware and names the errors and services it provides as named exports; each impl module default-exports its layer, the same shape as a group impl. ## Node actions [Node action](/server/node-actions) groups follow the same `.spec.ts`/`.impl.ts` naming and nesting conventions as any other group. A group is Node-runtime when its spec is built with `GroupSpec.makeNode()` (rather than `GroupSpec.make()`); its impl is otherwise identical to a non-node impl, passing the database schema from `_generated/schema`. Confect emits Convex's `"use node"` directive into the generated module based on the spec. ``` confect/ email.spec.ts email.impl.ts ``` ## Nested groups When a group contains subgroups, place each subgroup's `.spec.ts`/`.impl.ts` pair inside a subdirectory named after the parent group. The parent group itself does not need a spec or impl file—it is composed from its subgroups by their paths. ``` confect/ billing/ invoices.spec.ts ← group path billing.invoices invoices.impl.ts subscriptions.spec.ts ← group path billing.subscriptions subscriptions.impl.ts ``` ## Full example Putting it all together, a project using all of these conventions might look like this: **confect** **\_generated** **convexSchema.ts** **refs.ts** **schema.ts** **services.ts** **spec.ts** **registeredFunctions** **env.ts** **notes\_and\_random** **notes.ts** **random.ts** **workpool.ts** **email.ts** **tables** **notes.ts** **users.ts** **id.ts** **notes\_and\_random** **notes.spec.ts** **notes.impl.ts** **random.spec.ts** **random.impl.ts** **middleware** **RequireUser.spec.ts** **RequireUser.impl.ts** **tables** **notes.ts** **users.ts** **email.spec.ts** **email.impl.ts** **env.spec.ts** **env.impl.ts** **http.ts** **workpool.ts** **workpool.spec.ts** **workpool.impl.ts** # Packages Source: https://confect.dev/concepts/packages Understand the packages that make up the Confect ecosystem. | Package | Description | | - | - | | [`@confect/core`](https://www.npmjs.com/package/@confect/core) | Shared specs and schemas used by all Confect packages | | [`@confect/cli`](https://www.npmjs.com/package/@confect/cli) | Developer tooling for codegen and sync | | [`@confect/server`](https://www.npmjs.com/package/@confect/server) | Backend bindings to the Convex platform | | [`@confect/js`](https://www.npmjs.com/package/@confect/js) | JavaScript client bindings for any JS runtime | | [`@confect/react`](https://www.npmjs.com/package/@confect/react) | Client-side bindings for React apps | | [`@confect/foldkit`](https://www.npmjs.com/package/@confect/foldkit) | Client-side bindings for Foldkit apps | | [`@confect/test`](https://www.npmjs.com/package/@confect/test) | Utilities for testing Confect apps without a live Convex backend | # Project Structure Source: https://confect.dev/concepts/project-structure Understand the structure of a Confect project. **confect** **\_generated** **components.ts** **convexSchema.ts** **docs.ts** **id.ts** **refs.ts** **schema.ts** **services.ts** **spec.ts** **registeredFunctions** **env.ts** **notes\_and\_random** **notes.ts** **random.ts** **workpool.ts** **tables** **notes.ts** **users.ts** **notes\_and\_random** **notes.spec.ts** **notes.impl.ts** **random.spec.ts** **random.impl.ts** **middleware** **RequireUser.spec.ts** **RequireUser.impl.ts** **tables** **notes.ts** **users.ts** **auth.ts** **crons.ts** **env.spec.ts** **env.impl.ts** **http.ts** **workpool.spec.ts** **workpool.impl.ts** **convex** ## `confect/` ### `_generated/` #### `components.ts` Contains a typed `components` registry with one entry per Convex [component](https://docs.convex.dev/components) installed via `app.use(...)` in `convex/convex.config.ts`. Use it wherever a component client expects a component reference (e.g. `new Workpool(components.workpool, ...)`). Unlike the `components` export of `convex/_generated/api`, this file is safe to import from your impl files' import graphs. See [Components](/server/components). #### `convexSchema.ts` Contains the Convex deploy-time `SchemaDefinition` (a single `defineSchema({...})` call) assembled from every `confect/tables/*.ts` module. `convex/schema.ts` re-exports its default so Convex's CLI and `convex-test` find it where they expect. You should never import this file directly from your own code—use `_generated/schema.ts` for runtime needs. #### `docs.ts` Contains a named TypeScript `interface` for each table's document—`NotesDoc`, `UsersDoc`, etc.—plus a `Docs` registry mapping each table name to its interface. These are pure types (no runtime code): use them to annotate a value with a table's document type, e.g. `const note: NotesDoc = …`. The `Docs` registry is what lets the `DatabaseReader`/`DatabaseWriter` services hand documents back under their named types. See [Document types](/server/database/schema#document-types). #### `id.ts` Exports an `Id` schema constructor and an `Id` TypeScript type. Use `Id("users")` for a schema in table fields, spec `args`, or `returns`; use `Id<"users">` to annotate an ID value. Both accept your declared table names and Convex system table names (`"_storage"` and `"_scheduled_functions"`), catching unknown names at compile time. The exported `TableNames` union contains only your declared tables. See [Document IDs](/server/database/schema#document-ids) for import examples. #### `registeredFunctions/` Contains one module per group (for example `registeredFunctions/notes_and_random/notes.ts`), each exporting that group's functions in a form the Convex CLI can consume. These modules are consumed by the generated `convex/` files; you should not need to import them directly. #### `refs.ts` Contains a single default `Refs` export, which is a map of your Convex functions and their [function names](https://docs.convex.dev/api/modules/server#getfunctionname) and args/returns `Schema`s. Use this to invoke your Convex functions from the client or inside Convex functions using the `*Runner` services (`QueryRunner`, `MutationRunner`, and `ActionRunner`). #### `schema.ts` Contains the runtime `DatabaseSchema`—the codec-lookup view of your tables. Impls import it and pass it to `FunctionImpl.make`/`GroupImpl.make`. It is generated from `confect/tables/*.ts` and intentionally avoids any `convex/server` import so a runtime cold start never evaluates `defineSchema(...)`. Each table's field-schema is constructed lazily on the first access to its `Fields` or `Doc` and then cached, so a function only pays the schema-construction cost at cold start for the tables it actually touches via `db.table(name)`. Use this when a test or a non-codegen-generated module needs to refer to your `DatabaseSchema` type or value. #### `tables/` Contains one wrapper module per user-authored table (for example `tables/notes.ts` for `confect/tables/notes.ts`). Each wrapper applies the filename-derived table name to the `Table` defined in `confect/tables/.ts` and re-exports it as the default. Specs, impls, and other consumers should default-import from `confect/_generated/tables/` to reach a table's `Doc`, `Fields`, and `tableName` properties—for example, `import notes from "../_generated/tables/notes"` and then `notes.Doc`. These wrappers are client-safe: they do not import `@confect/server`, so a spec that uses `notes.Doc` can ship in `_generated/refs.ts` without pulling the server package into the browser. #### `services.ts` Contains Effect service wrappers for Convex platform capabilities, scoped to your app's database schema. Use these in your function implementation handlers. See [Services](/concepts/services) for a full list. #### `spec.ts` Contains your assembled Confect spec—every function group, of any runtime (including Node action groups)—used to build `refs.ts`. ### `auth.ts` Optional Corresponds 1:1 with `convex/auth.config.ts`. Use this to [configure auth](https://docs.convex.dev/auth). ### `crons.ts` Optional Expects a default `CronJobs` export defining your [cron jobs](/server/cron-jobs). ### `http.ts` Optional Expects a default Convex `HttpRouter` export. Construct this using Confect's `HttpRouter.make` and Effect's `effect/http`/`effect/http-api` modules. ### `tables/` Required Defines your database tables, one file per table. The **filename is the table name**—`confect/tables/notes.ts` defines a table called `notes`—so filenames must be valid JS identifiers and may not start with `_` (Convex reserves underscore-prefixed names for system tables). Each module **must default-export a `Table`** (built with `Table.make(...)` from `@confect/core`); codegen reads `module.default`, validates the filename, and applies it as the table name to produce `_generated/tables/.ts`. Other modules import from the wrapper, not directly from `tables/`. Codegen also scans this directory to produce `_generated/schema.ts` (runtime), `_generated/convexSchema.ts` (deploy), and `_generated/id.ts` (the cross-table `Id` constructor). See [Schema](/server/database/schema). ### `middleware/` Optional Defines your [middleware](/server/middleware), as a `.spec.ts`/`.impl.ts` pair per middleware. Like `tables/`, this directory name is reserved: Confect does not scan it for function groups, so its spec/impl pairs declare and implement middleware rather than a group, and no `convex/` module is emitted for them. Middleware is shared across groups, which is why it lives here rather than inside any one group's spec. ### `*.spec.ts`/`*.impl.ts` Required Your Convex API is defined as colocated `*.spec.ts`/`*.impl.ts` pairs, one pair per group. Each file's path within `confect/` becomes the group's name. See [File Naming Conventions](/concepts/file-naming-conventions) and [The Spec/Impl Model](/concepts/spec-impl-model). ## Rules * Your `confect/` directory should always be a sibling of your `convex/` directory. * The `confect/_generated/` directory is generated by the Confect CLI. You should never modify files in this directory directly. * Spec modules are bundled into your client, so nothing a `*.spec.ts` reaches may value-import `@confect/server`, including `tables/` and `_generated/`. Import `Table` from `@confect/core`, and use `import type` when you only need server types. `confect codegen` enforces this. * Confect treats the `convex` directory as a codegen target. While using Confect, you should never modify files in the `convex` folder directly, except for `tsconfig.json` and `convex.config.ts`. # Schema Restrictions Source: https://confect.dev/concepts/schema-restrictions Understand the restrictions on Effect schemas that can be used in Confect. Not every Effect `Schema` is valid for use in Confect. Remember that an Effect `Schema` looks like this: ```typescript theme={null} type Schema ``` For `Schema`s used in Confect: * `Type` represents the value that you'll be operating on in your code. Any TypeScript type is permitted here. * `Encoded` represents the value that is stored in the database or serialized as the argument/output of a Convex function. This must be a valid [Convex value](https://docs.convex.dev/database/types#convex-values). * `Context` is not currently supported. It should always be `never`. ## Function argument fields Convex functions always receive an object, so Confect function specs declare `args` as a `Schema.Struct` field map rather than as an arbitrary schema: ```typescript theme={null} FunctionSpec.publicQuery({ name: "byAuthor", args: () => ({ author: Schema.String }), returns: () => Schema.Array(Schema.String), }); ``` Confect lazily wraps that field map in `Schema.Struct`. A full schema such as `args: () => Schema.String` or `args: () => Schema.Struct(...)` is therefore not accepted. Top-level struct checks and annotations cannot be attached directly to function args; if you need a cross-field check, nest the checked struct under an argument field. For a function with no arguments, omit `args`; Confect defaults it to an empty field map (`{}`). ## Additional caveats ### Optional-property safety Confect requires `strict: true` in your TypeScript configuration. `exactOptionalPropertyTypes: true` is optional but recommended. See [Effect Schema's explanation of `exactOptionalPropertyTypes`](https://effect.website/docs/v4/schema/introduction#the-exactoptionalpropertytypes-option) for how it affects optional properties and schema validation. ### No-op returns from Convex functions Unlike the vanilla APIs, Convex functions defined with Confect may not return `undefined` or `void`—use `null` (`Schema.Null` as the `returns` validator) instead. Convex coerces `undefined`/`void` returns to `null` anyways—this just makes that more explicit. ```typescript ✅ theme={null} FunctionSpec.publicQuery({ name: "myQuery", returns: () => Schema.Null, }); ``` ```typescript ❌ theme={null} FunctionSpec.publicQuery({ name: "myQuery", returns: () => Schema.Undefined, }); ``` ```typescript ❌ theme={null} FunctionSpec.publicQuery({ name: "myQuery", returns: () => Schema.Void, }); ``` # Services Source: https://confect.dev/concepts/services Understand which Effect services Confect provides. Confect exposes Effect services that wrap Convex platform capabilities. These services are generated in `confect/_generated/services.ts` and are available when implementing your Confect functions and [HTTP endpoint handlers](/server/http-api). ```ts theme={null} import { ActionRunner, Auth, DatabaseReader, DatabaseWriter, DocumentIds, ExecutionMetadata, MutationRunner, QueryRunner, RequestMetadata, Scheduler, Storage, TransactionMetadata, VectorSearch, } from "./_generated/services"; ``` ## Database ### `DatabaseReader` Query Mutation Read documents from the database. ### `DatabaseWriter` Mutation Insert, edit, and delete documents from the database. ### `DocumentIds` Query Mutation Parse an ID for a known table or identify its table. Each method returns an `Effect` containing an `Option`; none fetches a document. The generated service is typed to your schema, including the `_storage` and `_scheduled_functions` system tables. See [Validate document IDs](/server/database/reading#validate-document-ids) for examples. ## Function invocation ### `QueryRunner` Query Mutation Action HTTP Action Run Confect queries with `runQuery(ref, args, options?)`: ```ts theme={null} import * as Effect from "effect/Effect"; import refs from "./_generated/refs"; import { QueryRunner } from "./_generated/services"; const firstNote = Effect.gen(function* () { const { runQuery } = yield* QueryRunner; return yield* runQuery(refs.public.notes_and_random.notes.getFirst, {}); }); ``` The `transactionLimits` option is available inside queries and mutations. The `useStaleSnapshot` option is available only inside mutations, even when you pass `false`. Actions and HTTP handlers can call `runQuery` without these options. See [Transaction controls](#transaction-controls). ### `MutationRunner` Mutation Action HTTP Action Run Confect mutations with `runMutation(ref, args, options?)`. Obtain the method with `const { runMutation } = yield* MutationRunner`. The `transactionLimits` option is available only inside mutations. Actions and HTTP handlers can call `runMutation` without this option. ### `ActionRunner` Action HTTP Action Run Confect actions with `runAction(ref, args)`. Obtain the method with `const { runAction } = yield* ActionRunner`. This method has no options parameter. For all three runners, `args` is optional when the referenced function takes no arguments. Pass `{}` as the second argument when supplying options to a no-argument query or mutation. ### Transaction controls Pass transaction options to a runner method to control a nested call, not the entire enclosing handler: ```ts theme={null} import * as Effect from "effect/Effect"; import refs from "./_generated/refs"; import { QueryRunner } from "./_generated/services"; const boundedRead = Effect.gen(function* () { const { runQuery } = yield* QueryRunner; return yield* runQuery( refs.public.notes_and_random.notes.getFirst, {}, { transactionLimits: { documentsRead: 100 } }, ); }); ``` `transactionLimits` accepts Convex's `TransactionLimits` fields, including `documentsRead`, `bytesRead`, and `databaseQueries`. Each field sets a maximum for the nested call. Convex caps these values at its platform transaction limits. Use [`TransactionMetadata.getMetrics()`](/server/metadata#transaction-metrics) to inspect usage and remaining limits. | Method and options | Available in | | - | - | | `runQuery(ref, args, { transactionLimits })` | Queries and mutations | | `runQuery(ref, args, { useStaleSnapshot })`, optionally with `transactionLimits` | Mutations | | `runMutation(ref, args, { transactionLimits })` | Mutations | In actions and HTTP handlers, omit options or pass `undefined` rather than an empty options object. `useStaleSnapshot: true` reads from a recent database snapshot that might not be up to date when the mutation commits. Passing `useStaleSnapshot: false` still requires a mutation context. > [!WARNING] > > Stale snapshots can introduce race conditions. Use them only when stale reads > are safe for your operation, such as reading immutable records from an > append-only table. Prefer ordinary reads otherwise. ## Storage ### `Storage` Query Mutation Action HTTP Action Use one service for file storage. The available operations depend on the function's context: | Operations | Available in | | - | - | | `getUrl` | Queries, mutations, actions, and HTTP actions | | `generateUploadUrl`, `delete` | Mutations, actions, and HTTP actions | | `get`, `store` | Actions and HTTP actions | See [Storage](/server/storage) for examples and return types. > [!NOTE] > > `StorageWriter` and `StorageActionWriter` may appear in operation > requirements. Confect supplies them automatically; new code only needs to > import `Storage`. The existing storage service exports and generated aliases > remain available for compatibility. ## Authentication ### `Auth` Query Mutation Action HTTP Action Access the current user's identity. ## Scheduling ### `Scheduler` Mutation Action HTTP Action Schedule Confect functions to run after a delay or at a specific time. ## Metadata ### `ExecutionMetadata` Query Mutation Action HTTP Action Read metadata about the current function and deployment. ### `RequestMetadata` Mutation Action HTTP Action Read metadata about the request that triggered the current execution. ### `TransactionMetadata` Query Mutation Read transaction usage and remaining limits. See [Metadata](/server/metadata) for examples of all three services. ## Search ### `VectorSearch` Action Query vector indexes for semantic similarity search. ## Convex context ### `QueryCtx` Query Raw Convex query context. ### `MutationCtx` Mutation Raw Convex mutation context. ### `ActionCtx` Action Raw Convex action context. # The Spec/Impl Model Source: https://confect.dev/concepts/spec-impl-model Understand how Confect separates function interfaces from their implementations. Your Confect API is broken up into two parts: a **spec** and its implementation (or **impl**). ## Spec A spec defines the interface of your Confect API. It is made up of group specs and function specs. Each function spec defines the function's name, argument fields, and returns schema—but not the function's logic. The optional `args` callback returns a `Schema.Struct` field map and defaults to `{}` when omitted; `returns` and the optional `error` are callbacks returning schemas. Provided callbacks are evaluated lazily on first invocation. Specs are built using `@confect/core`, which means they can be shared between the server and client. This separation is what enables end-to-end schema decoding and encoding: the client knows the exact shape of every function's arguments and return value without importing any server code. Each group spec is the default export of a `*.spec.ts` file. The group's name comes from the file's path—its stem for top-level groups, or the dot-joined directory path for nested groups: ```ts confect/notes_and_random/notes.spec.ts theme={null} import { GroupSpec, FunctionSpec } from "@confect/core"; import * as Schema from "effect/Schema"; import notes from "../_generated/tables/notes"; export default GroupSpec.make().addFunction( FunctionSpec.publicQuery({ name: "list", returns: () => Schema.Array(notes.Doc), }), ); ``` ## Impl An impl provides the logic for each function declared in your spec. Each impl is the default export of a `*.impl.ts` file colocated with its sibling spec. It default-imports that sibling spec, passes it to `FunctionImpl.make` and `GroupImpl.make`, and finalizes the resulting layer with `GroupImpl.finalize`: ```ts confect/notes_and_random/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` rejects, at compile time, any pipeline that has not provided a `FunctionImpl` for every function declared by the spec. This guarantees that the group is fully implemented before it is handed to the generated `convex/` module. Run `confect codegen` after adding or changing specs and impls. # Introduction Source: https://confect.dev/getting-started/introduction Confect deeply integrates Effect with Convex for end-to-end type-safe full-stack apps. Confect is a framework that deeply integrates [Effect](https://effect.website) with [Convex](https://convex.dev). It's more than just Effect bindings! Confect allows you to: * Define your Convex database schema using Effect schemas. * Write Convex function args and returns validators using Effect's schema library. * Use Confect functions to automatically decode and encode your data according to your Effect schema definitions for end-to-end rich types, from client to function to database (and back). * Use Effect's HTTP API modules to define your HTTP API(s). Includes interactive OpenAPI documentation powered by [Scalar](https://github.com/scalar/scalar). * Access Convex platform capabilities via Effect services. ## Prerequisites It's recommended that you have some familiarity with both Effect and Convex, including the vanilla `convex` APIs, before getting started with Confect. > [card] [Effect documentation](https://effect.website/docs) > > Learn about Effect's core concepts. > [card] [Convex documentation](https://docs.convex.dev) > > Learn about Convex's platform and APIs. ## Supported platforms Confect requires Node.js 24 or later, and runs on Linux, macOS, and Windows. > [!NOTE] > > On Windows, the `confect` CLI (`confect codegen`, `confect dev`) runs > natively. Convex's own [local > deployments](https://docs.convex.dev/cli/local-deployments)—anonymous > development and self-hosting—depend on a `convex-local-backend` binary that > Convex does not publish for Windows, so those workflows need WSL or Docker. > Developing against a Convex cloud deployment is unaffected. ## Next steps > [card] [Quickstart](/getting-started/quickstart) > > Install Confect and build your first app. # Quickstart Source: https://confect.dev/getting-started/quickstart Install Confect and build a type-safe Convex app with Effect schemas in minutes. ## Prerequisites Use Node.js 24 or later and an existing React + TypeScript app. The client examples below use [Vite](https://vite.dev/guide/) and its `VITE_CONVEX_URL` environment variable. Run all commands from your app's root directory. ## Installation ```bash pnpm theme={null} pnpm add effect convex @confect/core @confect/server @confect/cli @confect/react ``` ```bash npm theme={null} npm install effect convex @confect/core @confect/server @confect/cli @confect/react ``` ```bash yarn theme={null} yarn add effect convex @confect/core @confect/server @confect/cli @confect/react ``` ```bash bun theme={null} bun add effect convex @confect/core @confect/server @confect/cli @confect/react ``` > [!NOTE] > > If pnpm reports ignored build scripts for `esbuild`, run `pnpm approve-builds` > and approve only `esbuild`, then rerun `pnpm install`. Keep this approval > scoped to your project rather than enabling all dependency scripts. The commands below use `pnpm exec` to run the locally installed CLIs. With npm, use `npx` instead; with Yarn, use `yarn`; with Bun, use `bunx`. ## TypeScript configuration Confect requires `strict: true` in the TypeScript configuration that covers your Confect files. `exactOptionalPropertyTypes: true` is optional but recommended: ```json tsconfig.json theme={null} { "compilerOptions": { "strict": true, "exactOptionalPropertyTypes": true } } ``` See [Effect Schema's explanation of `exactOptionalPropertyTypes`](https://effect.website/docs/v4/schema/introduction#the-exactoptionalpropertytypes-option) for how it affects optional properties and schema validation. ## Usage **1. Set up your Convex dev deployment** Initialize your development deployment and the `convex/` directory, then exit after the first successful sync: ```bash theme={null} pnpm exec convex dev --once ``` Follow the prompts to configure your deployment. See Convex's [local deployment guide](https://docs.convex.dev/cli/local-deployments) if you want to develop locally without an account. **2. Define your database schema** > [!NOTE] > > Not every Effect `Schema` is valid for use in Confect. See > [Schema Restrictions](/concepts/schema-restrictions) for more > information about what's permitted and what's not. Define a table—one file per table under `confect/tables/`, where the **filename is the table name** (so filenames must be valid JS identifiers and may not start with `_`). Each file **must default-export** a `Table`; codegen reads `module.default` and applies the filename as the table name. From other modules (e.g. specs), default-import the codegen-emitted wrapper at `confect/_generated/tables/` to reach the table's derived `Schema`s (`notes.Doc`, `notes.Fields`). ```ts confect/tables/notes.ts theme={null} import { Table } from "@confect/core"; import * as Schema from "effect/Schema"; export default Table.make(() => Schema.Struct({ text: Schema.String, }), ); ``` Codegen will assemble every `confect/tables/*.ts` into a `DatabaseSchema` (in `confect/_generated/schema.ts`) and a Convex deploy `SchemaDefinition` (in `confect/_generated/convexSchema.ts`) for you—you never write a `confect/schema.ts`. It also emits a `confect/_generated/id.ts` module exporting a type-safe `Id` constructor (`Id("notes")`) for cross-table references. **3. Generate your table bindings** Before adding a function spec, generate the table schemas and services that your specs and implementations will import: ```bash theme={null} pnpm exec confect codegen ``` This creates `confect/_generated/`, including `id.ts`, `tables/notes.ts`, `schema.ts`, and `services.ts`. This tutorial generates table bindings before you write the functions. If your table, spec, and implementation files are already complete, one codegen run can generate everything without this separate step. **4. Define your Confect API spec** Create a `GroupSpec` and add some functions to it. ```ts confect/notes.spec.ts theme={null} import { FunctionSpec, GroupSpec } from "@confect/core"; import * as Schema from "effect/Schema"; import { Id } from "./_generated/id"; import notes from "./_generated/tables/notes"; export default GroupSpec.make() .addFunction( FunctionSpec.publicQuery({ name: "list", returns: () => Schema.Array(notes.Doc), }), ) .addFunction( FunctionSpec.publicMutation({ name: "create", args: () => ({ text: Schema.String }), returns: () => Id("notes"), }), ); ``` **5. Implement your Confect functions** Create a `GroupImpl` and implement its functions. Each spec needs a sibling implementation before you run codegen again; otherwise codegen reports a missing implementation. ```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, DatabaseWriter } 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), ); const create = FunctionImpl.make(databaseSchema, notes, "create", ({ text }) => Effect.gen(function* () { const writer = yield* DatabaseWriter; return yield* writer.table("notes").insert({ text }); }).pipe(Effect.orDie), ); export default GroupImpl.make(databaseSchema, notes).pipe( Layer.provide(list), Layer.provide(create), GroupImpl.finalize, ); ``` `GroupImpl.finalize` only typechecks once every function declared by the spec has a corresponding `FunctionImpl`, so it acts as a per-group completeness check. Generate the function refs and Convex functions now that both the spec and implementation exist: ```bash theme={null} pnpm exec confect codegen ``` **6. Start your Confect app** Keep Confect's generated files in sync as you edit: ```bash theme={null} pnpm exec confect dev ``` In another terminal, start your Convex dev deployment: ```bash theme={null} pnpm exec convex dev ``` **7. Call your Confect functions from your React app** Set `VITE_CONVEX_URL` in your Vite app's environment to the development deployment URL printed by Convex. Set up the Convex React client and provider: ```tsx src/main.tsx theme={null} import { ConvexProvider, ConvexReactClient } from "convex/react"; import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; const convexClient = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL); ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( , ); ``` Use Confect's React hooks alongside your Confect public refs to call your Confect functions. ```tsx src/App.tsx theme={null} import { QueryResult, useMutation, useQuery } from "@confect/react"; import * as Array from "effect/Array"; import { useState } from "react"; import refs from "../confect/_generated/refs"; const App = () => { const notes = useQuery(refs.public.notes.list, {}); const createNote = useMutation(refs.public.notes.create); const [newNote, setNewNote] = useState(""); return (
    {QueryResult.match(notes, { onLoading: () =>

    Loading…

    , onSuccess: (notes) => Array.map(notes, (note) => (
  • {note.text}
  • )), })}