OpenBooking / Docs / Recipes
Guide

Recipes

Last updated 2026-10-17 · Edit on GitHub

Copy-paste starting points. Every snippet uses the published @openbooking-sh/* packages.

1. A booking backend in one file #

npm install @openbooking-sh/server @openbooking-sh/provider-memory
// server.ts: run with `npx tsx server.ts`
import { createOpenBookingApp, listen } from '@openbooking-sh/server';
import { MemoryBookingProvider, type MemoryProviderConfig } from '@openbooking-sh/provider-memory';

const salon: MemoryProviderConfig = {
  name: 'Studio Nord',
  venues: [
    {
      venue: {
        id: 'studio-nord',
        name: 'Studio Nord',
        timezone: 'Europe/Oslo',
        currency: 'NOK',
        address: {
          street_address: 'Eksempelgata 12',
          postal_code: '0550',
          address_locality: 'Oslo',
          address_country: 'NO',
        },
      },
      currency: 'NOK',
      // Who or what gets booked. Tags let customers ask for someone by name.
      resources: [
        {
          id: 'maria',
          venue_id: 'studio-nord',
          kind: 'staff',
          name: 'Maria',
          capacity: { min: 1, max: 1 },
          tags: ['maria'],
        },
        {
          id: 'jonas',
          venue_id: 'studio-nord',
          kind: 'staff',
          name: 'Jonas',
          capacity: { min: 1, max: 1 },
          tags: ['jonas'],
        },
      ],
      offerings: [
        {
          id: 'haircut',
          venue_id: 'studio-nord',
          name: 'Haircut',
          duration_minutes: 45,
          price_per_person: { amount: 65000, currency: 'NOK' }, // minor units: 650.00 NOK
          resource_kinds: ['staff'],
          cancellation: {
            refundability: 'refundable',
            free_until_hours_before: 24,
            late_fee_per_person: 32500,
            no_show_fee_per_person: 32500,
          },
          deposit: null,
        },
      ],
      // Weekday 0 = Sunday … 6 = Saturday. Missing = closed.
      opening_hours: {
        2: [{ open: '09:00', close: '18:00' }],
        3: [{ open: '09:00', close: '18:00' }],
        4: [{ open: '09:00', close: '18:00' }],
        5: [{ open: '09:00', close: '18:00' }],
        6: [{ open: '10:00', close: '16:00' }],
      },
      slot_interval_minutes: 15,
      buffer_minutes: 10, // break between appointments with the same person
      min_lead_minutes: 60,
      max_days_ahead: 60,
    },
  ],
};

const { app } = createOpenBookingApp({
  provider: new MemoryBookingProvider(salon),
  baseUrl: process.env.BASE_URL ?? 'http://localhost:3000',
  studio: { token: process.env.STUDIO_TOKEN }, // Studio is open without a token on localhost only
});
await listen(app, { port: 3000 });

You get:

2. Keep bookings in Postgres #

npm install @openbooking-sh/postgres
import { connectPostgres, migrate, postgresStores } from '@openbooking-sh/postgres';

const db = connectPostgres(process.env.DATABASE_URL!);
await migrate(db); // creates and upgrades tables; safe on every start
const stores = postgresStores(db);

const { app } = createOpenBookingApp({
  provider: new MemoryBookingProvider(salon, { store: stores.bookings }),
  serviceOptions: { idempotencyStore: stores.idempotency },
  studio: { token: process.env.STUDIO_TOKEN, activity: stores.activity },
  baseUrl: process.env.BASE_URL!,
});

Holds are reserved under a per-resource lock, so two servers can never sell the same time.

3. Deploy to Vercel #

Export the app as a Vercel Function and send every path to it:

// api/index.ts
const handle = (request: Request) => app.fetch(request);
export const GET = handle;
export const POST = handle;
export const PUT = handle;
export const DELETE = handle;
export const OPTIONS = handle;
// vercel.json
{ "rewrites": [{ "source": "/(.*)", "destination": "/api" }] }

Set BASE_URL to your public URL, plus STUDIO_TOKEN and DATABASE_URL.

4. Add booking to an existing website #

One line, before </body>:

<script src="https://your-booking-backend.example.com/book/embed.js" async></script>

What it does:

Options on the tag: data-label, data-color, data-position="left", data-button="none", data-structured-data="off", data-agents="off".

On hosted OpenBooking, the snippet is https://app.openbooking.sh/b/<business>/embed.js.

5. Connect an existing booking system #

Implement BookingProvider from @openbooking-sh/core. The engine handles agent safety (consent, idempotency, hold expiry, cancellation rules); you translate to your system:

import type { BookingProvider } from '@openbooking-sh/core';

export class MySystemProvider implements BookingProvider {
  readonly info = { name: 'My booking system' };
  async listVenues() {
    /* your locations */
  }
  async searchAvailability(query, ctx) {
    /* free slots with price and cancellation policy */
  }
  async createHold(req, ctx) {
    /* reserve atomically until req.expires_at */
  }
  async confirmHold(req, ctx) {
    /* turn the hold into a booking; re-check expiry */
  }
  async getBooking(id, ctx) {
    /* … */
  }
  async cancelBooking(req, ctx) {
    /* release a hold or cancel with req.fee / req.refund */
  }
}

The contract:

@openbooking-sh/provider-memory and @openbooking-sh/provider-calcom are complete examples.

Test it with @openbooking-sh/conformance (npm install -D @openbooking-sh/conformance vitest):

import { describeProviderConformance } from '@openbooking-sh/conformance/vitest';

describeProviderConformance('MySystemProvider', {
  create: () => new MySystemProvider(testConfig), // a fresh, empty provider per test
  now: new Date('2030-06-03T08:00:00Z'), // before the date you search
  query: { date: '2030-06-04', party_size: { total: 1 } }, // must return open slots
});

The suite never assumes one place per slot: it books a slot until the provider answers slot_unavailable, then checks that parallel holds cannot go past that point. query must return an open slot, and another slot at a different time once the first is full.

6. Get webhooks when bookings change #

Send booking.held, booking.confirmed, booking.updated, booking.cancelled and booking.expired to your CRM, SMS sender or own database:

const { app, webhooks } = createOpenBookingApp({
  provider,
  baseUrl: process.env.BASE_URL!,
  webhooks: {
    endpoints: [{ url: 'https://crm.example.com/hooks', secret: process.env.WEBHOOK_SECRET! }],
  },
});
// On Vercel and other serverless hosts, let retries finish after the response:
// waitUntil(webhooks!.idle());

Each delivery is a JSON POST with an openbooking-signature header (t=…,v1=…, HMAC-SHA256) and an openbooking-event-id header. Verify it on the receiving side with the raw body:

import { verifyWebhook } from '@openbooking-sh/core';

const body = await request.text();
if (!(await verifyWebhook(body, request.headers.get('openbooking-signature'), secret))) {
  return new Response('bad signature', { status: 401 });
}
const event = JSON.parse(body); // { id, type, created_at, data: { booking, actor } }

Failed deliveries are retried after 2 s, 15 s and 60 s. Events reach each endpoint in the order they happened, so a failing endpoint holds back its later events until the earlier one succeeds or gives up. Delivery is at least once, so dedupe on event.id. Retries (same idempotency key) and no-op cancels don't send events. Payloads include customer details, so never point a webhook at an analytics or logging service. Without the server, createWebhooks() returns a listener for service.on().

7. Take deposits with Stripe #

A slot can require a deposit at confirmation. Give the service a payment provider and the engine handles the rest:

import { StripePayments } from '@openbooking-sh/payments-stripe';

const service = new BookingService({
  provider,
  payments: new StripePayments({
    secretKey: process.env.STRIPE_SECRET_KEY!, // sk_test_… while you try it
    successUrl: 'https://example.com/booked',
    cancelUrl: 'https://example.com/book',
  }),
});
  1. confirm_booking without a token fails with payment_required. The error carries a payment_url (a Stripe Checkout page) and a payment_token. The agent gives the user the link.
  2. After the user pays, confirm_booking again with that payment_token. The engine asks Stripe whether the session was paid, for this booking, for the deposit amount. Only then is the booking confirmed, and the payment reference is kept on it. Tokens an agent makes up are refused.
  3. Cancelling refunds what the cancellation terms say (the whole deposit before the free-cancellation deadline, the deposit minus the late fee after it). If Stripe is down, the booking is still cancelled and cancel_booking replies refund_failed; calling it again retries, and the idempotency key means the customer is never refunded twice.
  4. If the customer pays after the hold expired, the payment is refunded and the agent gets hold_expired.

Staff taking a deposit in cash in Studio still works: Studio records it as collected, with no Stripe involved. For a connected account (Stripe Connect) pass stripeAccount.

Not built yet: per-business Stripe accounts and the payment page in the hosted booking page and Studio. For now payments is for self-hosted setups.

Rules for AI coding tools #

If you're an AI assistant adding OpenBooking to a project:

This page is generated from docs/RECIPES.md in the open-source repository. To fix something, change it there.