BTST

Calendar Plugin

Individual, group and team bookings with timezone-aware availability and fair host assignment

Full-stackReleased · Preview

Best for

Teams that need public scheduling pages with host-owned availability and booking management.

Let visitors book individual or group appointments in your application.

Real BTST Calendar showing synthetic appointments in the generated application.
Calendar presents appointment availability and bookings; provider synchronization is not demonstrated by this screen.

BTST supplies

  • Individual and group bookings with configurable duration and capacity
  • Weekly availability, date overrides, timezone-aware slots, and booking limits
  • Public booking and cancellation pages plus event type and booking management
  • Confirmation, cancellation, and application-triggered reminder hooks

You supply

  • A BTST database adapter with isolated transaction support
  • Host identities and authorization rules for management operations
  • Email delivery and a scheduler when reminders are needed
  • The application shell and deployment

You own and customize

Event types and bookings stay in your database. Your application supplies host identity, access rules, email delivery, and reminder scheduling.

Compatibility and dependencies

Maintained: Next.js 15+ App Router, React Router v7, TanStack Start.

Requires: A BTST database adapter with isolated transaction support.

External services: None required.

From registration to result

A semantic workflow, not a setup shortcut

  1. 1Set availability

    Create an event type with duration, capacity, weekly hours, and date overrides.

  2. 2Share a booking page

    Visitors select a date, timezone, and available time before confirming their booking.

  3. 3Manage bookings

    Review upcoming and past bookings and send reminders through your own scheduler.

The Calendar plugin provides public booking pages and a host dashboard. Each event type belongs to a host and defines its duration, location, capacity, timezone, availability, and booking limits. Capacity 1 gives individual appointments; a higher capacity lets several attendees book the same time slot. An opt-in team event type shares one booking link across eligible hosts and assigns each reservation to an available member.

Install @btst/plugin-calendar@1.3.0 alongside @btst/stack@6.2.0. Calendar has no dependency on other feature packages or @btst/components. The canonical registration ID, permission namespace and database identities remain unchanged.

Registration

Follow the framework installation guide, then register both halves with the canonical calendar key:

lib/stack.ts
import { createBackendStack } from "@btst/stack/api"
import { calendarBackendPlugin } from "@btst/plugin-calendar/api"

export const myStack = createBackendStack({
  basePath: "/api/data",
  plugins: { calendar: calendarBackendPlugin() },
  adapter,
  auth: serverAuth,
})

adapter is your configured BTST database adapter. Calendar writes require transactions to be enabled in the adapter configuration; unsupported or disabled transactions produce a 503 CALENDAR_TRANSACTIONS_REQUIRED error. Configure persistent adapters with isolated transactions so concurrent requests cannot exceed capacity or limits. The memory adapter supports local development and tests. Host writes are serialized through a host-row lock inside the transaction.

lib/stack-client.tsx
import { createClientStack } from "@btst/stack/client"
import { calendarClientPlugin } from "@btst/plugin-calendar/client"

export function getStackClient(queryClient, origin: string) {
  return createClientStack({
    api: { baseURL: origin, basePath: "/api/data" },
    site: { baseURL: origin, basePath: "/pages" },
    queryClient,
    plugins: { calendar: calendarClientPlugin() },
  })
}
globals.css
@import "@btst/plugin-calendar/css";

Mount the resolved client stack with StackProvider and the framework router as described in the installation guide. Shared API, site, query client, and auth services belong on the stack/provider, not in calendar overrides.

Authorization

Register calendarPermissions from @btst/plugin-calendar/permissions with your shared authorization contract. Management operations require the authenticated host identity. Public event reads, slot selection, and booking creation can allow guests; cancellation requires the booking's secret token or the owning host.

The following rules assume an identity with a string id and show the Calendar part of a defineAuthorization configuration:

permissions: [calendarPermissions] as const,
rules: ({ calendar }) => [
  calendar.eventType.list.when(({ identity, facts }) =>
    identity !== null && (!facts.hostId || identity.id === facts.hostId)),
  calendar.eventType.create.when(({ identity, facts }) =>
    identity !== null && (!facts.hostId || identity.id === facts.hostId)),
  calendar.eventType.read.when(({ identity, facts }) =>
    facts.public || identity?.id === facts.hostId),
  calendar.eventType.update.when(({ identity, facts }) =>
    identity?.id === facts.hostId),
  calendar.eventType.delete.when(({ identity, facts }) =>
    identity?.id === facts.hostId),
  calendar.availability.read.allow(),
  calendar.booking.create.allow(),
  calendar.booking.list.when(({ identity, facts }) =>
    identity !== null && (!facts.hostId || identity.id === facts.hostId)),
  calendar.booking.read.when(({ identity, facts }) =>
    facts.tokenValid || identity?.id === facts.hostId),
  calendar.booking.cancel.when(({ identity, facts }) =>
    facts.tokenValid || identity?.id === facts.hostId),
  calendar.booking.reschedule.when(({ facts }) => facts.tokenValid),
  calendar.booking.remind.when(({ identity, facts }) =>
    identity?.id === facts.hostId),
  calendar.connection.list.when(({ identity, facts }) =>
    identity !== null && (!facts.hostId || identity.id === facts.hostId)),
  calendar.connection.connect.when(({ identity, facts }) =>
    identity !== null && (!facts.hostId || identity.id === facts.hostId)),
  calendar.connection.manage.when(({ identity, facts }) =>
    identity?.id === facts.hostId),
  calendar.sync.retry.when(({ identity, facts }) =>
    identity?.id === facts.hostId),
],

The backend derives hostId from the authenticated request identity for host operations. Trusted server jobs may explicitly supply hostId when creating event types or listing a host's records. Keep cancellation URLs private: anyone holding the token can view, cancel, or reschedule that booking. Rescheduling uses the same private cancelToken; a booking ID alone does not grant access.

Availability and limits

  • duration is an integer number of minutes, including custom durations.
  • timezone is an IANA timezone such as America/New_York.
  • weeklyAvailability contains { dayOfWeek, start, end } rules. Sunday is 0; times use HH:mm in the event type's timezone.
  • dateOverrides contains { date, intervals } entries. Each date replaces the weekly rules for that local date. An empty intervals array blocks the day; nonempty intervals add one-off availability.
  • capacity limits attendees sharing a slot. Existing host appointments also prevent overlapping bookings across event types.
  • limits accepts optional perHour, perDay, perWeek, and total positive counts per event type. Counts include each confirmed or pending-payment attendee reservation, using calendar periods in the host timezone; total counts all active reservations. Cancellations release availability and limits.

The public page interprets the selected date in the visitor's selected timezone and displays slot times there. The backend validates the slot again on booking, including availability, capacity, limits, and whether its start is in the future.

Team event types

Create one individual event type for each eligible host's availability, then reference those event IDs in the team's teamAvailabilityIds array. Each profile supplies its host's current timezone, weekly availability and date overrides. The team event supplies the booking duration, location, price, capacity and limits. Profiles must belong to distinct hosts and cannot themselves be team event types. An empty or omitted array preserves individual event behavior.

await myStack.trusted.calendar.createEventType({
  hostId: "team-manager",
  slug: "team-consultation",
  name: "Team consultation",
  duration: 30,
  capacity: 1,
  timezone: "UTC",
  teamAvailabilityIds: [alexAvailabilityEventId, samAvailabilityEventId],
})

The event owner manages the team link. Applications must explicitly authorize calendar.team.manage in addition to ordinary event creation or editing. The permission receives the optional hostId and eventTypeId, eligibleHostIds, and availabilityEventTypeIds; validate every member against your application's team membership and management rules. For example, add this rule to your existing shared authorization configuration:

calendar.team.manage.when(async ({ identity, facts }) => {
  if (!identity) return false
  const ownerId = facts.hostId ?? identity.id
  return await teams.canManageCalendar(identity.id, ownerId) &&
    await teams.includesEveryHost(ownerId, facts.eligibleHostIds)
}),

teams represents your application's membership service. Do not grant this permission based only on the event owner's identity. Without an explicit rule, team creation and membership changes are denied. Removing the team configuration also requires team-management authorization. Trusted server calls retain their existing explicit trust boundary. Request creation derives ownership from the authenticated identity; update facts contain the stored owner's hostId.

Public slots contain at least one available eligible member. Each member's own bookings, callback busy intervals and connected-provider intervals are checked in that member's timezone. Booking locks the relevant hosts in a consistent order, then reloads membership and revalidates availability inside the transaction. capacity applies per assigned member: group attendees can share a member's exact slot up to that limit. Team limits apply per member, using each member's timezone and that member's active reservations for this team event. Individual events retain their existing capacity and overlap rules. Public reads expose isTeam without the private availability references, and public booking input cannot choose a host or edit membership.

Fairness: among eligible available members, select the host with the fewest lifetime reservations for this team event, including cancelled and pending-payment reservations; break ties by host ID. A cancellation releases capacity and active booking limits but keeps its assignment in the fairness count. Members who are unavailable receive no assignment for that slot. Adding a host starts from that host's existing assignment history for this event; removing and adding the same host does not erase that history.

Send an optional secret idempotencyKey of 32–200 characters with a booking request to retry it safely. Repeating the same event, key and reservation payload returns the original booking, including its assigned host, without another fairness assignment. Reusing the key for different reservation details returns 409. Treat the key as a bearer secret because a successful retry returns the private booking token. The booking UI generates a key and retains it across retries of the same submission. A changed reservation gets a new key.

Bookings persist the assigned hostId and availability profile reference. Rescheduling retains that host and profile, rechecks the same scheduling and payment rules, and does not change the fairness count. Removing a host from the team stops new assignments without changing existing reservations. A deleted, deactivated or otherwise unavailable profile cannot supply a new reschedule slot; the original reservation remains valid and can still be cancelled. Pausing a profile makes that host unavailable for new team bookings. Switching an event between individual and team modes, including removing its final profile, is rejected while it has upcoming active bookings. Cancel those reservations first, or pause the existing team event instead. Updating the eligible members within team mode remains supported with existing bookings.

In the event editor, enable Assign bookings across a team and enter one individual availability event ID per line. The host dashboard shows availability event IDs, team host counts, and the assigned host on authorized booking rows. Members see their own assigned bookings through the existing host-scoped dashboard; team ownership does not grant access to other hosts' booking details or provider connections. Removing a member never transfers their existing bookings to the manager.

Team schema migration

Apply the exported calendarSchema migration before serving the updated endpoints. Add nullable text teamAvailabilityIds on calendarEventType and nullable text availabilityEventTypeId, requestKey, and requestFingerprint on calendarBooking. Preserve the unique index on requestKey and the existing host-lock and cancellation-token indexes. requestKey and requestFingerprint are private retry state; do not return them from application booking APIs. Existing null team configuration is treated as an individual event; existing bookings keep their stored host and need no assignment backfill. No existing booking rows are rewritten. Keep transaction support enabled for both team and individual writes.

External busy intervals

Pass an optional getBusyIntervals(hostId, range) callback in CalendarBackendConfig (also exported as CalendarBackendOptions):

calendarBackendPlugin({
  getBusyIntervals: async (hostId, range) => {
    const events = await externalCalendar.listBusy(hostId, range)
    return events.map((event) => ({
      start: new Date(event.start),
      end: new Date(event.end),
    }))
  },
})

Both the requested range and returned intervals use absolute Date instants, with exclusive ends. The range includes padding for viewer timezone offsets and event duration; query all external events overlapping it. Any overlap blocks a slot, including partial overlaps. Adjacent intervals do not block one another. Booking and rescheduling fetch busy intervals again inside the host transaction. Provider failures or invalid intervals reject the request rather than showing or reserving unchecked times. Your integration owns credentials and provider access; external calendar changes cannot be locked by the BTST database transaction.

Optional Google and Microsoft connections

Configure providers on the backend only. The server exports googleCalendarAdapter, microsoftCalendarAdapter, CalendarProviderCredentials, and the smaller CalendarProviderAdapter contract from @btst/plugin-calendar/api. No adapter or credential configuration belongs in calendarClientPlugin or StackProvider.

lib/stack.ts
import {
  calendarBackendPlugin,
  googleCalendarAdapter,
  microsoftCalendarAdapter,
  type CalendarProviderCredentials,
} from "@btst/plugin-calendar/api"

// These are application services, backed by your encrypted server credential store.
const googleCredentials: CalendarProviderCredentials = {
  connect: async ({ hostId, request }) => {
    const account = await googleAccounts.claimVerifiedGrant({ hostId, request })
    return { accountId: account.id, label: account.email }
  },
  getAccessToken: async (connection) =>
    googleAccounts.loadAndRefreshToken(connection.hostId, connection.accountId),
  disconnect: async (connection) =>
    googleAccounts.revokeAndDeleteGrant(connection.hostId, connection.accountId),
}

calendarBackendPlugin({
  calendarProviders: {
    google: googleCalendarAdapter(googleCredentials),
    microsoft: microsoftCalendarAdapter(microsoftCredentials),
  },
})

googleAccounts and microsoftCredentials represent your application's services; BTST does not supply an OAuth callback or credential vault. Register a Google or Microsoft application, configure its redirect URI and calendar read/write permissions, and complete consent in your application before connecting from the Calendar dashboard. Bind the authorization request and callback to the signed-in host, validate OAuth state and PKCE where applicable, and save access/refresh tokens encrypted on the server. The connect callback must claim only that host's already-verified grant; it must not accept a browser-supplied account identifier as proof of ownership.

getAccessToken runs for each provider request. Your credential service loads the correct host/account, refreshes expired credentials, stores rotated refresh tokens, and throws if refresh fails or consent was revoked. disconnect revokes the grant and removes stored credentials. It must be idempotent: already-revoked grants or already-deleted credentials count as success, including a retry after a lost response. Provider tokens are never persisted in Calendar rows or returned through Calendar API responses. Provider errors are replaced with a generic sync failure so token-bearing error messages do not reach the browser. Use a nonsecret label, because it is shown to the host.

The host dashboard offers enabled providers, connection/disconnection, and calendar selection. A connected provider without a selected calendar blocks availability until the host selects one or disconnects. Register the connection and sync permissions shown above. Request identity determines the host; connection and retry operations verify ownership of the stored row.

Schema and deployment

Apply your adapter's schema migration when upgrading the plugin, before serving Calendar endpoints, even if providers are not configured. Calendar checks the new tables to detect existing connections whose adapter configuration was removed. Standalone installations keep these tables empty. The exported calendarSchema adds these models; existing booking fields are unchanged and id is supplied by the adapter:

ModelFields
calendarConnectionhostId, unique connectionKey, provider, private accountId, label, nullable calendarId / calendarName, status
calendarSynchostId, bookingId, connectionId, calendarId, unique syncKey, nullable eventId, state, nullable error, attempts, updatedAt

Preserve the unique indexes and transaction support. Calendar stores only the server account reference, selected calendar, and booking/event mapping. The application's credential table is separate and is never part of the client schema. Installations without calendarProviders retain standalone scheduling, arbitrary getBusyIntervals callbacks, and manual .ics downloads.

Availability, freshness, and provider changes

Each availability read, booking, and reschedule fetches provider events again; there is no built-in busy-time cache, webhook subscription, or background polling. Provider intervals pass through the same absolute-instant validation as getBusyIntervals, and both sources are combined. Invalid intervals, unavailable providers, failed credential refresh, and incomplete provider responses reject the request. A provider failure never makes unchecked time available. Provider calls use a 15-second timeout. Your application may add a cache or webhook-driven refresh behind a custom adapter only if it still fails closed when freshness is unknown.

Mirrored event IDs are excluded from external busy intervals because BTST already counts those reservations, including group capacity. Other external busy events block booking as usual. Google all-day events are interpreted in the calendar's timezone; timed events and Microsoft responses become absolute instants. See the provider references for Google event reads and Microsoft calendar events.

Synchronization is outbound: provider edits/deletions never confirm payment, change local booking ownership/capacity, reschedule, or cancel a BTST booking. The local reservation remains authoritative. A host retry reapplies the local confirmed time to an existing event. If a known mapped event was deleted in Google or Microsoft, the update fails visibly instead of silently recreating it; the host must resolve the provider event or disconnect. Hosts must use BTST to change the reservation. External writes cannot be locked by the BTST database transaction, so no integration can eliminate the race between the last provider availability read and an unrelated external edit.

Booking synchronization and retry

Confirmed create, reschedule, payment confirmation, and cancellation queue durable sync work in the booking transaction. Pending-payment holds are not mirrored as confirmed appointments. After commit, Calendar attempts the provider change and records pending, synced, or failed with an attempt count and update time. A provider failure preserves the local booking and leaves work visible in the host dashboard; it does not undo a confirmed reservation. The owning host can retry, or a trusted application job can call:

await myStack.trusted.calendar.retryCalendarSync({ id: syncId })

The stable sync key and persisted event ID identify the same external appointment across retries. Google uses a deterministic event ID; Microsoft uses a stable transaction ID and a searchable private property. An uncertain create is reconciled before another create is attempted. Custom CalendarProviderAdapter.ensureEvent implementations must provide the same reconciliation guarantee, and deleteEvent must accept an already-deleted event. See Google event creation for its event-ID semantics.

There is no automatic retry scheduler. Run retries from the host dashboard or an application-owned job, after reconnecting if credentials failed. Selecting a different calendar with existing booking mappings requires disconnection first; changing a selection does not silently move existing events. Disconnection first deletes mapped provider events idempotently and commits a disconnecting state before invoking your credential revocation callback. The operation then clears selection and sync mappings and marks the connection disconnected. If revocation fails or its response is lost, the host can choose Retry disconnect; this skips token-dependent event cleanup and retries only revocation and finalization. Availability remains blocked while disconnection is incomplete, and reconnect/selection is refused until it finishes. Reconnection requires calendar selection again and mirrors upcoming confirmed bookings. Removing adapter configuration without disconnecting does not bypass provider checks: persisted active connections continue to block unchecked availability.

Opt-in waitlists for full group slots

Enable waitlistEnabled: true on a group event type with capacity > 1 and no team assignment. Team assignment and waitlists cannot be combined: an event with nonempty teamAvailabilityIds rejects waitlistEnabled: true. Team group bookings remain supported without waitlists.

Configure hooks.onWaitlistVerification and hooks.onWaitlistOffer to deliver private verification and offer links. Both hooks are required before join requests are accepted. Existing event types default to disabled. Full slots then appear separately in availability.waitlistSlots; ordinary available slots remain in slots. Waitlists apply only to the exact selected start/end pair. They do not bypass host availability, external busy intervals, booking limits, access rules, or future-start validation.

calendarBackendPlugin({
  hooks: {
    onWaitlistVerification: async (entry) => {
      await mail.send({
        to: entry.email,
        subject: "Verify your waitlist request",
        url: `https://example.com/pages/calendar/waitlist/${entry.token}`,
      })
    },
    onWaitlistOffer: async (entry) => {
      await mail.send({
        to: entry.email,
        subject: "A place is available",
        url: `https://example.com/pages/calendar/waitlist/${entry.token}`,
      })
    },
  },
})

mail is your application-owned delivery service, not a required package or provider. An optional Notifications integration can deliver to an authenticated recipient's private inbox instead, after resolving their account from a verified email mapping. Never send these links to the host or a public activity feed. The codegen examples demonstrate recipient-only delivery for seeded demo users.

Verified identity and ordering

Joining returns a generic { success: true } response without an entry ID or management token. The attendee must follow the delivered secret link and press Verify email and join waitlist; merely opening the link does not verify it. The verified identity is the normalized email address for the event type and exact slot, established by possession of the emailed secret. Normalization lowercases the address; the existing booking email validation rejects surrounding whitespace. It does not merge provider aliases or remove +tags. Names are display values, not identity.

Only one active entry is allowed for that identity and slot. Repeated joins resend the same private verification link without creating another place in the queue. An attendee who already holds a confirmed or pending-payment booking for the slot cannot obtain another place through the waitlist. This policy does not change the normal booking API's existing attendee policy. An attendee with an outstanding offer must use the private offer link; they cannot create another direct reservation or reschedule another booking into that same slot while the offer holds capacity.

Verified entries are offered places in first-in, first-out order by verification time, then entry ID for ties within the same millisecond. Unverified requests have no priority. Entries expire after 24 hours or at the slot start, whichever comes first. Each offer lasts at most 15 minutes and cannot extend beyond the slot start. The customer page shows verification, waiting, offered, accepted, cancelled, and expired states, and lets the attendee leave or explicitly accept an offer. An accepted entry offers View booking to recover the normal private booking-management flow after a reload.

The host dashboard lists the owning host's entries and offer states without management tokens. Other attendees cannot list or inspect the queue.

Capacity and payment

Booking cancellation can promote the next eligible entry. An offer reserves one place under the same host transaction lock as ordinary bookings; a direct booking cannot take that reserved place. An offer never silently confirms a booking or charges an attendee. Acceptance rechecks normal booking rules and creates the ordinary booking response, including checkout where configured. Paid acceptance creates a pending_payment hold, whose capacity remains reserved until the normal payment or cancellation flow completes. Expiring an offer does not expire a booking that has already been accepted.

Cancelling or expiring an unaccepted offer releases its reservation once. Repeated cancellation and dispatch calls cannot release another attendee's capacity. Expired and otherwise ineligible entries are skipped before promotion. Existing application-owned handling of abandoned payment holds still applies.

If external availability cannot be validated during promotion, that entry stays waiting and receives no offer. The dispatcher retries eligibility on a later run. This does not roll back an otherwise valid cancellation, payment failure, or refund that releases capacity. Ordinary booking, rescheduling, and offer acceptance still reject requests when their own availability cannot be validated.

Scheduling, delivery, and retry

Your application owns scheduling. Run a trusted job for each host to expire entries/offers, promote eligible waiting entries, and retry pending offer delivery:

await myStack.trusted.calendar.dispatchWaitlist({ hostId })

This operation has no public HTTP route. Do not expose it through an unauthenticated job endpoint. Delivery hooks run after the committed transition. A failed onWaitlistOffer callback leaves delivery pending for retry; ordinary booking, cancellation, and payment operations preserve their response and continue their booking lifecycle hooks. The trusted dispatchWaitlist operation reports offer delivery errors to the calling job, so it can monitor failures and retry. Already committed offers remain reserved until accepted, cancelled, or expired.

Make delivery idempotent by entry ID and offer expiry: a retry after an uncertain response can deliver the same offer again. Calendar adds no hosted worker, mail provider, or Notifications dependency. Without a running dispatch job, timed expiry does not itself send the next offer; schedule it at the cadence your product requires.

Authorization, privacy, and abuse controls

Waitlists reuse existing Calendar permission descriptors, so existing application rules continue to apply. Join, verification, and acceptance require calendar.booking.create with authoritative event/host facts. Private reads use calendar.booking.read; cancellation uses calendar.booking.cancel, with tokenValid: true and the entry ID as bookingId for a valid secret. Host listing uses calendar.booking.list. There is no additional waitlist permission namespace. Applications that restrict booking creation should account for its use during email verification and offer acceptance as well as initial booking.

Treat the management URL as a bearer secret. Anyone possessing it can inspect that entry, verify its email, leave, or accept its offer. Keep it out of logs, analytics URLs, shared screenshots, referrers, and host responses. Invalid tokens must not expose other entries. Apply your existing booking availability/access rules to waitlist entry points as well; enabling waitlists does not grant access to otherwise restricted events.

Add rate limiting at your application boundary for join, verification, token lookups, cancellation, and acceptance. Limit repeated delivery requests by IP and normalized email/event/slot, and retain the generic join response. Calendar does not add a global rate limiter or claim that secret links prevent spam. Apply your retention policy to expired/cancelled entry names and email addresses.

Migration

Before deploying the new endpoints, apply your adapter's schema migration for nullable calendarEventType.waitlistEnabled and the new calendarWaitlist model. Existing event types remain disabled when the field is absent/null. The model stores event/host identifiers, slot instants, attendee details, a unique secret token, state, entry/offer expiry, creation/verification times, accepted booking ID, and delivery state. Preserve the unique token index, host locks, and isolated transactions. No existing booking rows need backfilling. Deploy schema changes before enabling event waitlists, then start your application-owned dispatcher.

Prices and payment holds

Event types accept optional price and currency fields. Supply both or neither: price is a nonnegative integer in minor currency units (2500 means USD 25.00), and currency is a three-letter uppercase currency code such as USD. Omit both or set both to null to remove pricing. A zero price creates a free booking. Existing databases need the two nullable columns on calendarEventType.

Positive prices create pending_payment bookings. These hold capacity, block overlapping host events, and count toward booking limits just like confirmed bookings. They can be rescheduled or cancelled using the private booking token. Rescheduling preserves their payment status. Pending bookings do not fire confirmation hooks or qualify for confirmed-booking reminders.

Configure an optional shared PaymentAdapter to create hosted checkout or a client secret without installing Ecommerce:

import { stripeAdapter } from "@btst/stack/payments"

calendarBackendPlugin({
  paymentAdapter: stripeAdapter(stripeSecret, webhookSecret, {
    successUrl: "https://example.com/pages/calendar/book/consultation",
    cancelUrl: "https://example.com/pages/calendar/book/consultation",
  }),
})

Send signed provider events to POST /calendar/webhook under your API base path, preserving the original raw request body. Bookings snapshot the amount, currency and provider before checkout. Verified success changes pending_payment to confirmed; failure or a full refund cancels the reservation and releases capacity under the host lock. Retries validate the same payment reference and cannot confirm a cancelled booking. Browser redirects never confirm payment.

The reservation response adds checkout with redirectUrl or clientSecret. The UI opens hosted checkout; supply overrides.calendar.renderPayment(checkout) on StackProvider for a provider SDK form using a client secret. The private booking link can resume checkout via POST /calendar/cancel/:token/checkout, and offers a payment status check. Hosted checkout saves the private token in session storage before redirecting; returning to the public booking page restores the management route. Hosted redirects require session storage. When it is unavailable, checkout stays on the current page so the attendee can save the private link; enable browser storage before retrying payment. Checkout initialization failure returns a pending booking with checkoutError, preserving both the held slot and its management token. Retry uses the same payment identity and caches a successfully created checkout. Ordinary booking reads expose hasCheckout, and redact private provider state and credentials.

Confirmation/cancellation hooks run after the payment transition and retry on verified webhook re-delivery when they fail. Make them idempotent by booking ID; external effects cannot be committed atomically with the database. Abandoned holds still require application-owned cancellation; automatic expiry is not included. Add a nullable private payment text column to calendarBooking in your schema migration before enabling adapter payments.

Without paymentAdapter, existing host-managed paid holds remain supported. After your own server verifies payment, call:

await myStack.trusted.calendar.confirmBookingPayment({ id: bookingId })

This operation has no HTTP route and rejects request-scoped calls. It cannot confirm adapter-managed checkouts, which require their signed webhook. It fires onAfterConfirmBooking once for the transition, and repeated calls are idempotent.

Routes

With site.basePath: "/pages", the client registers:

PathPurpose
/pages/calendarEvent types and upcoming/past booking dashboard
/pages/calendar/events/newCreate an event type
/pages/calendar/events/:id/editEdit availability, limits, and event details
/pages/calendar/book/:slugPublic booking page
/pages/calendar/cancel/:tokenBooking details and cancellation
/pages/calendar/reschedule/:tokenChoose a replacement time with the booking token
/pages/calendar/waitlist/:tokenVerify, inspect, cancel, or accept a private waitlist entry

API routes are relative to api.basePath, for example /api/data:

MethodPathPurpose
GET/calendar/connectionsList enabled providers, owned connections, and sync states
POST/calendar/connectionsConnect an application-verified grant with { provider: "google" } or { provider: "microsoft" }
GET/calendar/connections/:id/calendarsList writable calendars for an owned connection
PATCH/calendar/connections/:idSelect a provider calendar with { calendarId }
DELETE/calendar/connections/:idDisconnect the owned provider account
POST/calendar/sync/:id/retryRetry an owned persisted sync entry
GET, POST/calendar/eventsList or create host event types
GET, PATCH, DELETE/calendar/events/:idRead, update, or delete an event type
GET/calendar/book/:slugRead an active public event type
GET/calendar/book/:slug/slots?date=YYYY-MM-DD&timezone=UTCList available slots
POST/calendar/book/:slugConfirm a booking with { start, timezone, name, email }
POST/calendar/book/:slug/waitlistRequest verification for a full group slot with { start, timezone, name, email }
GET/calendar/waitlist?eventTypeId=...List the owning host’s entries without private tokens
GET/calendar/waitlist/:tokenRead the private entry
POST/calendar/waitlist/:token/verifyVerify email and enter the ordered queue
POST/calendar/waitlist/:token/cancelLeave the waitlist and release an unaccepted offer
POST/calendar/waitlist/:token/acceptAccept a live offer through normal booking/payment rules
GET/calendar/bookings?period=upcomingList host bookings; also accepts past or all
POST/calendar/bookings/:id/cancelCancel a booking as its owning host
GET, POST/calendar/cancel/:tokenRead or cancel a booking using its token
GET/calendar/reschedule/:token/slots?date=YYYY-MM-DD&timezone=UTCAvailable replacement times, excluding this booking's reservation
POST/calendar/reschedule/:tokenMove the booking using { start, timezone }

Slot responses contain { date, timezone, slots }; each slot has UTC start and end timestamps and a remaining capacity. A confirmed booking includes its cancelToken. Show or deliver the cancellation link to the attendee. Host dashboard responses omit the token value; hosts cancel through the protected booking ID endpoint.

Rescheduling and calendar invites

The confirmation links to booking management, where an attendee can reschedule an upcoming active booking. A successful move keeps the booking ID and token and releases the previous time. A failed move leaves the original booking intact. The replacement is validated with the same host lock, external busy intervals, timezone rules, group capacity and limits as a new booking. The existing booking is excluded from those counts during replacement validation. Cancelled or past bookings cannot be moved; deactivated event types offer no replacement times.

Confirmation, booking management, the host dashboard and reschedule confirmation provide a Download calendar invite (.ics) link. The file uses UTC instants (including across DST changes), a stable booking UID, escaped text and folded UTF-8 lines following RFC 5545. Pending holds export as TENTATIVE; cancelled bookings export as CANCELLED. Files contain no booking token. Downloads are manual snapshots, not calendar subscriptions or automatic update notifications. Server applications can also import generateBookingInvite(booking) from @btst/plugin-calendar/api; the client entry is @btst/plugin-calendar/client/hooks.

Lifecycle hooks and reminders

Pass hooks to calendarBackendPlugin({ hooks }) to connect confirmation and cancellation to your own email or notification service. onAfterConfirmBooking receives the confirmed booking, and onAfterCancelBooking receives the cancelled booking. Hooks run after the corresponding booking write.

onAfterRescheduleBooking(booking, previous) receives the committed replacement and original booking. Confirmed moves also fire onAfterConfirmBooking; moving a pending-payment hold only fires the reschedule hook. Repeating a move with the same instants and timezone fires neither hook. Post-commit hook failures do not undo the reservation, so delivery and retry handling belong to the application.

Calendar does not run a scheduler or deliver email. From your application-owned scheduled job, call:

await myStack.trusted.calendar.remindBooking({ id: bookingId })

This invokes onBeforeRemindBooking and onAfterRemindBooking for a confirmed upcoming booking. Your scheduler owns delivery timing and deduplication.

Customization

Import calendar hooks from @btst/plugin-calendar/client/hooks, query keys from @btst/plugin-calendar/query-keys, and page components from @btst/plugin-calendar/client/components. Eject the page UI through the btst-calendar shadcn registry item and pass replacement pages through the client plugin's pageComponents option.

The plugin excludes round-robin assignment, provider-origin booking changes, payment processing, video conferencing, recurring bookings, and workflow automation.

Confirmation notification context

Calendar 1.1 keeps both onAfterRescheduleBooking and the existing onAfterConfirmBooking notification after moving a confirmed booking. The latter receives an optional second argument { reason: "rescheduled" }. Initial booking and trusted payment confirmation keep their existing one-argument calls. Use this context to avoid counting a reschedule as another initial confirmation, while continuing to notify attendees of their new time.

Affiliate payment attribution

Calendar 1.2 adds optional hooks.capturePaymentAttribution({ request }) when an adapter-backed paid booking is created. The private payment snapshot survives checkout recovery. A verified paid onAfterConfirmBooking context includes payment: { amount, currency, attribution } using the original booked price. Free and host-managed confirmations omit payment context. Reschedule notifications retain reason: "rescheduled" and create no new conversion. See Affiliate's conversion bridge for optional commission recording without a Calendar dependency on Affiliate.

Page-scoped presentation

Set overrides.calendar.pageOverrides on StackProvider. calendarBooking and calendarReschedule support TimePicker, which receives CalendarTimePickerProps exported from @btst/plugin-calendar/client: the selected date, timezone and start time, their change callbacks, slots query result, and optional capacity.

overrides={{
  calendar: {
    pageOverrides: {
      calendarBooking: { TimePicker: MyBookingTimePicker },
    },
  },
}}

This customizes booking time selection while rescheduling retains the built-in picker. Custom pickers should clear the selected start when changing date or timezone and use the supplied slots and callbacks; booking submission, availability queries, and payment remain page-owned. Missing components use the built-in picker. renderPayment and whole-page replacements retain their existing behavior. Standalone pickers do not inherit page overrides.

The dashboard, event editors, and cancellation page do not select a time and have no TimePicker slot.