These docs describe @mrfinch/booking 0.5.x. For 0.4.x, see the component's README at v0.4.3 or this site's 0.4.2 docs.
API Reference
This page describes the component API. The reference gateway
adds host policy and sometimes uses different arguments. Your generated
components.booking types are the complete, version-matched reference.
Coming from 0.4.x? See Upgrading to 0.5.
Calling the component
Inside a Convex function, import components from ./_generated/api and call
ctx.runQuery or ctx.runMutation. Browser clients call your host wrappers.
Apply authorization before returning private data or
changing resources, and booking policy before creating
or moving a booking. The component enforces the booking rules and input checks
itself and rejects violations with coded errors.
// Inside an authorized host query:
const resource = await ctx.runQuery(components.booking.resources.getResource, {
id: "meeting-room",
});Setup and availability
| Module | Common operations |
|---|---|
resources | createResource, getResource, listResources, updateResource, deleteResource |
schedules | createSchedule, getSchedule, getDefaultSchedule, getEffectiveAvailability, date overrides |
public | createEventType, updateEventType, getEventType, getEventTypeBySlug, listEventTypes |
resource_event_types | linkResourceToEventType, hasResourceEventTypeLink, link/unlink and lookup operations |
Resource and event-type id values are your app's strings. A booking's _id is a
component document ID; its uid is used in management links. They are not interchangeable.
Resources can carry metadata: Record<string, string>; updating that field replaces
the whole map, while omitting it preserves the existing map.
The component checks setup writes:
getEventTypereturnsnullfor an unknown ID, likegetResource.- Event-type lengths, length options and slot intervals are whole minutes above 0;
buffers and notice are 0 or more,
maxFutureMinutesis above 0, andlengthInMinutesis one oflengthInMinutesOptionswhen there are any (INVALID_INPUT).updateEventTypeclearsdescription,scheduleId, buffers, notice and horizon givennull. createEventTypeon an existing ID updates it and keeps omitted fields,isActiveandorganizationIdincluded. An ID stored for another organization is rejected (ORGANIZATION_MISMATCH) instead of being moved, and the IDlegacyis reserved forcreateReservationbookings.- An event type's
scheduleIdnames an existing schedule or is""(SCHEDULE_NOT_FOUND).deleteSchedulerefuses while an event type uses the schedule (SCHEDULE_IN_USE). - A date override's
typeis"unavailable", or"custom"with at least one window. - An event type with an
organizationIdlinks only resources of that organization (ORGANIZATION_MISMATCH). deleteResourceanddeleteEventTypealso delete the ID's links, so an ID created again starts unlinked.updateResourcerefusesisFungible: truewhile active single-resource bookings hold the resource (RESOURCE_IN_USE).
Month availability
public.getMonthAvailability returns a map of date strings to booleans, for at
most 93 days per call (INVALID_INPUT beyond). Pass a schedule ID alone for
schedule-aware results; the dates are then days in the schedule's timezone:
const month = await ctx.runQuery(components.booking.public.getMonthAvailability, {
resourceId: "meeting-room",
dateFrom: "2027-03-01",
dateTo: "2027-03-31",
eventLength: 30,
slotInterval: 30,
scheduleId: "business-hours",
});Day slots
public.getDaySlots returns Array<{ time: string }> with ISO timestamp strings.
It takes the same scheduleId and reads that day's hours, date overrides included:
const slots = await ctx.runQuery(components.booking.public.getDaySlots, {
resourceId: "meeting-room",
date: "2027-03-02",
eventLength: 30,
slotInterval: 30,
scheduleId: "business-hours",
});Instead of scheduleId, you can pass the day's availableSlots together with
resourceTimezone. The reference gateway does this with the result of
schedules.getEffectiveAvailability. The slot indices represent local 15-minute
buckets, from 0 to 95; an empty array means closed.
Only a call without any schedule argument falls back to 09:00–17:00 UTC; pass real
schedule information for your application. Partial arguments throw INVALID_INPUT:
resourceTimezone alone, availableSlots without resourceTimezone or
scheduleId, or a resourceTimezone that differs from the schedule's. An unknown
scheduleId throws SCHEDULE_NOT_FOUND.
While a booker moves a booking, pass rescheduleContext: { uid, token } (the
booking's UID and management token) to both queries. Its own slots then count as
free on every resource it holds, so a new time that overlaps the current one is
offered. Anything but the token of a pending or confirmed booking with that UID
frees nothing and raises no error. excludeBookingUid frees a booking from its
UID alone: pass it only from server code that has authorized the move, never from
client arguments. Passing both throws INVALID_INPUT. The host functions guide
shows a wrapper.
The slot queries do not offer pooled resources. For a resource pool, use
multi_resource.checkMultiResourceAvailability instead.
Bookings
| Function | Purpose |
|---|---|
public.createBooking | Book one exclusive resource |
public.createProvisionalBooking | Hold an exclusive resource until your host confirms or expires it |
public.getBooking / getBookingByUid | Read the full booking from authorized host code |
public.getBookingByToken | Read a booking using its UID and management token |
public.listBookings | List bookings, filtered by organization, resource, event type, status or dates |
public.listBookingsPage | Page through one organization's, resource's or event type's bookings |
public.cancelBookingByToken | Cancel using UID and token |
public.rescheduleBooking | Move a booking using its component document ID |
public.rescheduleBookingByToken | Move using UID and token |
hooks.transitionBookingState | Administer lifecycle transitions |
public.createReservation | Legacy: book one resource without an event type and without the booking rules |
getBooking and getBookingByUid return the whole record, including the
management token and the guest's contact details, without checking any token. A
UID alone is not a secret, so return their result only to a caller who has proven
access. For anyone else, return a redacted view without those fields, as the
reference gateway does; see booking management links.
No React component calls these reads, so your public gateway need not export them.
Creation takes epoch milliseconds for start and end, a timezone, event type,
resource, booker details and location. It returns the booking document. The
event type and the resource must exist and be active, be linked, and share the
event type's organization when it has one; the resource must not be an add-on
(isStandalone: false). A timezone that Intl rejects and a booker email that
fails the component's syntax check throw INVALID_INPUT. isSendableAddress
from @mrfinch/booking/emails is that check, for your form or gateway.
The legacy createReservation checks none of these rules, only the time range,
availability and that the resource is not a pool. It stores the booking under the
reserved event type ID legacy, and such bookings keep that exemption when moved,
as long as no event type has that ID. Use createBooking wherever the booking
rules must hold.
Provisional bookings do not expire automatically. Have your host schedule a call
to public.expireProvisionalBooking when its confirmation window ends.
// Inside your mutation, AFTER authorization and host-policy validation:
const booking = await ctx.runMutation(components.booking.public.createBooking, {
eventTypeId: "quick-meeting",
resourceId: "meeting-room",
start: Date.parse("2027-03-02T15:00:00.000Z"),
end: Date.parse("2027-03-02T15:30:00.000Z"),
timezone: "America/New_York",
booker: { name: "Ada", email: "ada@example.com" },
location: { type: "inPerson", value: "Meeting Room" },
});Cancellation releases all resources held by an active booking. A repeated or invalid terminal transition does not release inventory again. Completed bookings retain historical occupancy.
Both reschedule entry points move all booking items atomically: a conflict leaves
the original booking untouched. A successful move returns a new booking with a
new UID, retaining its management token and resource quantities; the original
becomes cancelled with rescheduledToUid set. Use the returned UID for
subsequent management requests. Moves check the booking rules for every item, with
no administrator override: after deactivating or unlinking, reactivate or relink
first. Only createReservation bookings stay exempt (above). Host wrappers must
validate the new time against schedules, duration choices and notice periods too.
transitionBookingState checks the booking rules again when it confirms a booking
or submits a provisional hold as a request (pending). Cancelling, declining and
completing never check them. A booking stored with another organization than its
event type's, or none, takes the event type's organization on its next move,
transition, cancellation or expiry when all its resources belong to it, before
hooks and emails go out.
Booking lists
listBookings returns one array, newest start first. Filter it by
organizationId, resourceId, eventTypeId, status and dateFrom/dateTo
(epoch milliseconds, bounding start). Without status, provisional holds are
left out. limit must be a positive integer; omit it for no limit. Without an ID
filter, it considers only the 1,000 most recently created bookings.
listBookingsPage takes exactly one of organizationId, resourceId and
eventTypeId, plus paginationOpts and the same dateFrom, dateTo and
status filters. Pass includeProvisional: true to list provisional holds
without status. A page reads at most 1,000 bookings, so a filtered page can be
short or empty before the end: continue until isDone. Page it reactively from a
host query with usePaginatedQuery from convex-helpers/react.
In both, resourceId matches a booking's primary resource, which for a bundle is
its first item. Both return whole bookings, management tokens included: remove
them before returning results to a browser. The host functions guide
shows a paged wrapper.
Multiple resources
Use multi_resource.createMultiResourceBooking for bundles or pooled resources:
// Inside a host mutation after policy checks:
const booking = await ctx.runMutation(
components.booking.multi_resource.createMultiResourceBooking,
{
eventTypeId: "studio-session",
resources: [
{ resourceId: "studio-a", quantity: 1 },
{ resourceId: "camera-pool", quantity: 2 },
],
start: Date.parse("2027-03-02T10:00:00.000Z"),
end: Date.parse("2027-03-02T11:00:00.000Z"),
timezone: "UTC",
booker: { name: "Ada", email: "ada@example.com" },
}
);A bundle belongs to its event type's organization. organizationId is optional: a
value that differs from the event type's is rejected with ORGANIZATION_MISMATCH.
For an event type without organization, the value is used and must be the
organization of the booked resources.
The component applies the booking rules of createBooking to every item: the
event type exists and is active, and each resource exists, is active, is linked to
the event type (pools included) and belongs to its organization when it has one.
All resources belong to one organization, and at least one is standalone
(isStandalone is not false). An unknown resource ID is rejected with
RESOURCE_NOT_FOUND.
resources must contain unique IDs and positive safe-integer quantities.
Exclusive resources accept quantity 1. Pools use isFungible: true and a positive
integer quantity as capacity. Ordinary/provisional single-resource booking APIs
do not accept pools; their slot queries do not offer pooled resources.
Use checkMultiResourceAvailability with the same resource requests and time
range for a preview, getBookingWithItems to read the bundle, and
cancelMultiResourceBooking for authorized administration. Creation always checks
inventory again, regardless of an earlier availability query.
Presence
presence.heartbeat takes { resourceId, slots: string[], user, eventTypeId? }.
Each slot is a full ISO timestamp for a 15-minute bucket. user is a client
session identifier, not proof of an authenticated identity.
The React useSlotHold hook maintains heartbeats and cleanup. Presence helps
visitors see one another's selections; it is not an exclusive inventory lock.
The final booking write can still reject a conflict.
Errors
Expected failures, such as a taken slot or a wrong management token, throw
ConvexError({ code, message }). The error codes
are public contract and listed with the functions that throw them. message is
English text for logs and administrators and can contain IDs. Other failures,
such as argument validation by Convex, stay plain Errors, whose message Convex
redacts for clients in production.
A host function receives the component's ConvexError from ctx.runQuery or
ctx.runMutation. isBookingError from @mrfinch/booking recognizes one with a
known code. Map the codes your clients see to your own codes and texts, and fall
back to a generic error for the rest:
import { ConvexError } from "convex/values";
import { isBookingError, type BookingErrorCode } from "@mrfinch/booking";
const SLOT_TAKEN = "This time slot is no longer available — please pick another one.";
const CLIENT_ERRORS: Partial<Record<BookingErrorCode, [code: string, message: string]>> = {
SLOT_UNAVAILABLE: ["SLOT_NOT_AVAILABLE", SLOT_TAKEN],
QUANTITY_UNAVAILABLE: ["SLOT_NOT_AVAILABLE", SLOT_TAKEN],
BOOKING_NOT_FOUND: ["NOT_FOUND", "Booking not found."],
INVALID_TOKEN: ["INVALID_TOKEN", "Invalid booking link."],
};
export function translateComponentError(error: unknown): never {
if (isBookingError(error)) {
const mapped = CLIENT_ERRORS[error.data.code];
if (mapped) throw new ConvexError({ code: mapped[0], message: mapped[1] });
}
throw new ConvexError({ code: "BOOKING_FAILED", message: "Booking failed — please try again." });
}Call it in a catch around the component call only, so that every ConvexError
it sees is the component's. The reference gateway uses a longer table of this
shape. A host that passes component errors through unchanged sends their codes
and English texts to the browser, where the Booker shows data.message.
Internal helpers
makeInternalBookingAPI creates server-only helpers under Convex's internal
namespace. It is optional; direct components.booking.* calls are sufficient.
import { makeInternalBookingAPI } from "@mrfinch/booking";
import { components } from "./_generated/api";
export const { getResource, getDaySlots } = makeInternalBookingAPI(components.booking);The old makeBookingAPI public factory was removed in 0.4.0. Migrate browser
endpoints to authorized host wrappers.
Maintenance
The component's tables are private to it. These functions check and repair the
stored rows, usually once after an upgrade. Call them from host internal
functions, makeInternalBookingAPI or the CLI, never from clients.
| Function | Purpose |
|---|---|
maintenance.audit | Read-only: one page of one check, with its issues |
maintenance.backfillBookingOrganizations | Give bookings without an organization their event type's, when all their resources belong to it |
presence.sweepOrphanedHolds | Remove presence holds whose cleanup job was lost |
resource_event_types.deleteAllLinksForResource / deleteAllLinksForEventType | Remove links that deletes before 0.5.0 left behind |
The first three read one page per call: pass continueCursor back as cursor
until isDone (limit 1–500).
The two repairs require dryRun: true only counts, false writes.
makeInternalBookingAPI wraps the first three, not the link deletes. For example:
npx convex run --component booking maintenance:audit '{"check": "link_integrity", "limit": 200}'The maintenance guide
lists every check with its repair and the upgrade order.
maintenance.wipeAllData and wipeAllBookingData are destructive; keep reset
wrappers internal.
Frontend Hooks
Import these hooks from @mrfinch/booking/react. For hooks that query or mutate,
render beneath your Convex provider, ConvexQueryCacheProvider and
BookingProvider, as shown in the Quick Start.
useSlotHold
useSlotHold(resourceId, slotId, durationMinutes = 60, eventTypeId?) returns the
session ID string, not a loading/error object. Pass null to stop holding a
selection. It sends heartbeats every five seconds and releases on cleanup.
Presence is best effort: it does not guarantee that a booking will succeed.
"use client";
import { useSlotHold } from "@mrfinch/booking/react";
export function SlotSelection({ selectedSlot }: { selectedSlot: string | null }) {
const sessionId = useSlotHold("meeting-room", selectedSlot, 30, "quick-meeting");
return <p data-session={sessionId}>{selectedSlot ? "Slot selected" : "Choose a slot"}</p>;
}slotId is a full ISO timestamp. Duration is in minutes; a five-hour selection
sends twenty 15-minute buckets regardless of the displayed slot interval.
useConvexSlots
The positional signature is
useConvexSlots(resourceId, eventLength, slotInterval?, allDurationOptions?, enabled = true, timezone?, context?).
Call fetchSlotsForDate("YYYY-MM-DD") to select a day and
fetchMonthSlotsFor(year, month) (month 1–12) to request a month's availability;
both throw a RangeError for impossible input. The older fetchSlots(date) and
fetchMonthSlots(date) take a Date and are deprecated; timezone (default: the
browser's) only affects fetchSlots.
"use client";
import { useEffect } from "react";
import { useConvexSlots } from "@mrfinch/booking/react";
export function SlotList({ date }: { date: string }) { // "2027-03-02"
const { availableSlots, reservedSlots, isLoading, fetchSlotsForDate } =
useConvexSlots("meeting-room", 30, 30);
useEffect(() => { fetchSlotsForDate(date); }, [date, fetchSlotsForDate]);
if (isLoading) return <p>Loading slots…</p>;
return (
<ul>
{availableSlots.map((slot) => <li key={slot.time}>{slot.time}</li>)}
{reservedSlots.map((slot) => <li key={slot.time}>{slot.time} — being selected</li>)}
</ul>
);
}Returns monthSlots, availableSlots, reservedSlots, isLoading,
presenceIncomplete and the fetch functions. Slots have a time ISO string, not
slot or formatted properties. Reserved here means presence held by another
session; it does not mean a committed booking or server-enforced reservation.
presenceIncomplete is true when the slots and their duration span more than three
UTC dates, which takes bookings of about a day or longer; holds after the third
date are not shown.
context is { eventTypeId, rescheduleContext }. The hook sends it to
getMonthAvailability and getDaySlots only when BookingProvider has
availabilityContext on; presence queries never receive it.
useBookingValidation
useBookingValidation(eventType, resource, hasLink, selectedDuration, resourceId)
validates objects you already loaded. undefined means loading; null means a
missing record. It does not fetch them for you, and the EventTypeView and
ResourceView fields are enough.
"use client";
import { useBookingValidation, type EventTypeView, type ResourceView } from "@mrfinch/booking/react";
export function SelectionStatus(props: {
eventType: EventTypeView | null | undefined;
resource: ResourceView | null | undefined;
hasLink: boolean | null | undefined;
}) {
const result = useBookingValidation(
props.eventType, props.resource, props.hasLink, 30, "meeting-room"
);
if (result.status === "loading") return <p>Loading…</p>;
if (result.status === "error") return <p role="alert">{result.error?.message}</p>;
return <p>Selection is valid.</p>;
}Returns { status: "loading" | "valid" | "error", error? }. The error object
contains type, message and recovery ("select-event-type",
"select-resource" or "reset-duration"), which you map to your own routes;
recoveryPath is deprecated. There is no data field.
This catches deleted/inactive setup, removed durations and unlinked resources in
the UI. The server must independently validate every write.