Booking SDK: a typed TypeScript SDK for custom booking flows

Stanislav TyshchenkoEngineering11 min readUpdated
Booking SDK — a typed TypeScript SDK for custom booking flows

Adding booking to an app looks like a weekend project until you start. Real-time availability across staff and locations, cart state that survives a page refresh, a payment flow that fails gracefully, booking statuses that move through their lifecycle — every piece is more nested and more stateful than it looks from the outside.

A booking SDK is what turns that from raw HTTP plumbing into typed method calls. This is a look at what a booking SDK does, when it's worth using over the raw API, and how the Opencals storefront SDK is structured — with code you can actually run.

Why a booking flow earns an SDK

Plenty of APIs don't need an SDK. A booking API does, and the reason is the shape of the data. A single booking flow touches:

Availability

Nested slots computed across staff, hours, duration, capacity

Cart state

Line items, quantities, selected times — held across steps

Payment intents

Stripe client secrets, confirmation, idempotency

Booking status

Pending (held, awaiting payment or approval), scheduled, completed, canceled

Wire that up with hand-rolled fetch calls and you're maintaining a private, untyped copy of the API's mental model — one that silently drifts every time the backend adds a field. A typed SDK gives you autocomplete for every request, compile-time errors when a shape changes, and schemas for validating responses at the boundary. In a domain this nested, that's the difference between a booking flow you trust and one you babysit.

Use a booking SDK when the flow is stateful and the types are nested — availability, carts, and payments. Reach for the raw REST API for one-off scripts, server-to-server jobs, or non-JavaScript stacks.

Install and set up

The Opencals storefront SDK is a TypeScript package:

bash
npm install @opencals/storefront-sdk

Initialize it once with your store API key. Keys are scoped to a single store. For server code use a private storefront key: it starts with spk_ and comes from the dashboard under Users → your user → API Keys. Keep it server-side, and forward each visitor's IP with the buyerIp option so rate limits count per visitor, not per server.

ts
// lib/opencals.ts — import it from server code import { setupOpencals } from "@opencals/storefront-sdk"; import { nextBuyerIp } from "@opencals/storefront-sdk/next"; // Next.js; elsewhere pass your own function setupOpencals({ apiKey: process.env.OPENCALS_API_KEY, // spk_... buyerIp: nextBuyerIp, throwOnError: true, // failed calls throw OpencalsApiError instead of returning { error } });

That's the whole setup. setupOpencals configures one shared client, so the service classes below don't take a client argument: every call takes a single options object with path, query, body and headers as needed. The base URL (https://api.opencals.com) is the default, and every route is typed. The full endpoint reference is at api.opencals.com/docs/storefront if you want to see the raw HTTP underneath.

The five things every booking flow does

Almost every custom booking flow is the same five steps. Here's each one through the SDK (version 0.3.20, checked November 2026; the examples assume throwOnError: true).

1. Load the service catalog

Your services page is populated from the product catalog. It rarely changes, so cache it.

ts
import { ProductService } from "@opencals/storefront-sdk"; const { data: page } = await ProductService.list({ query: { status: ["active"], take: 50 }, }); const services = page.data; // each service is typed: title, price, duration (seconds), variants, staff and locations

2. Fetch real-time availability

This is the endpoint that earns the platform. You ask for a service on a date, optionally narrowed to a staff member and a location; you get back the slots that are bookable right now — after existing bookings, working hours, buffers, and capacity are all accounted for.

ts
import { ProductService } from "@opencals/storefront-sdk"; const { data: slots } = await ProductService.getCurrentAvailabilities({ path: { productId }, query: { date: "2026-07-20", // one day per call staffMemberId, // optional — omit for "any available" locationId, // optional timezone: "Europe/Warsaw", }, }); // slots: [{ productId, fromDate, fromTime, toDate, toTime, staffMemberIds, attendees, maxAttendees }]

You render slots straight into a calendar. You are not reconstructing availability logic on the client — the hard part stays on the server where it belongs. For "next free slot" buttons there's ProductService.getNearestAvailability.

3. Create a cart and hold the slot

A cart holds the selected slot while the customer finishes checkout. Every cart and checkout call names its cart in the X-Cart-Id header; store the cart ID (an httpOnly cookie works) so the cart survives a page refresh.

ts
import { AppointmentService, CartService } from "@opencals/storefront-sdk"; const { data: cart } = await CartService.createOrGet({ headers: { "X-Cart-Id": savedCartId ?? "" }, }); await AppointmentService.create({ body: { slot: { productId: slot.productId, fromDate: slot.fromDate, fromTime: slot.fromTime, toDate: slot.toDate, toTime: slot.toTime, }, // times are UTC numberOfAttendees: 1, cartId: cart.id, }, });

If two people try to hold the same slot at the same moment, one gets it and the other gets a clear error that the slot is being booked, so show that and let them pick another time.

4. Start checkout, pay, submit

CheckoutService.start attaches the customer and creates the payment. For card payments it returns a Stripe client secret, the publishable key and the connected account ID, so your app never stores a Stripe key. The browser confirms the payment with Stripe.js, then your server submits.

ts
import { CheckoutService } from "@opencals/storefront-sdk"; const cartHeaders = { "X-Cart-Id": cart.id }; const { data: checkout } = await CheckoutService.start({ headers: cartHeaders, body: { provider: "stripe", customer: { kind: "new", email, firstName, lastName }, }, }); // browser: loadStripe(checkout.publishableKey, { stripeAccount: checkout.stripeAccountId }) // → mount a Payment Element with checkout.clientSecret → stripe.confirmPayment(...) const { data: result } = await CheckoutService.submit({ headers: cartHeaders, body: { stripePaymentIntentId: paymentIntent.id }, });

The failure cases are named, so a retry doesn't have to guess. Submitting a card payment that isn't authorised returns 402 PAYMENT_NOT_AUTHORIZED: no order is placed and the cart is untouched, so the customer can try again. A second start or submit while one is still running returns 409 CHECKOUT_IN_PROGRESS, and starting a cart that already became an order returns 409 CART_ALREADY_CHECKED_OUT with that order's ID. Not every booking is confirmed on submit: a pending appointment with pendingReason set is awaiting payment or the store's approval, so label it that way rather than "Confirmed".

5. Customer self-service

Viewing, rescheduling, and cancelling a customer's own bookings uses a second credential: a customer access token from Opencals' customer accounts (AuthService.signIn, or signUp for new customers), sent as a Bearer header. The store key stays on the server while a signed-in customer acts only on their own bookings.

ts
import { AppointmentService, AuthService } from "@opencals/storefront-sdk"; const { data: session } = await AuthService.signIn({ body: { email, password } }); const asCustomer = { Authorization: `Bearer ${session.accessToken}` }; const { data: upcoming } = await AppointmentService.list({ headers: asCustomer, query: { status: ["scheduled", "pending"], orderBy: "from", order: "ASC" }, }); await AppointmentService.reschedule({ headers: asCustomer, path: { appointmentId }, body: { slot: newSlot }, // from getCurrentAvailabilities with excludeAppointmentId }); await AppointmentService.cancel({ headers: asCustomer, path: { appointmentId }, body: { notifyCustomer: true }, });
1

Catalog

ProductService.list() — populate services from page.data. Cache it.

2

Availability

ProductService.getCurrentAvailabilities({ path: { productId }, query: { date } }) — render the calendar from real bookable slots, one day per call.

3

Cart

CartService.createOrGet() with the X-Cart-Id header, then AppointmentService.create() with the slot and cartId to hold it.

4

Checkout

CheckoutService.start() for the Stripe client secret, stripe.confirmPayment() in the browser, then CheckoutService.submit().

5

Self-service

AuthService.signIn() for a customer token, then AppointmentService.list(), reschedule() and cancel() with it.

Type safety and runtime validation

Static types catch shape mismatches at compile time. But data crossing a network boundary can still surprise you at runtime, so the SDK also exports a Zod schema for every response type. Run the ones you care about with safeParse at the boundary, and a malformed or unexpected payload fails loudly at the edge instead of leaking an undefined three components deep into your UI.

ts
import { zProductListResponse } from "@opencals/storefront-sdk"; const parsed = zProductListResponse.safeParse(raw); if (!parsed.success) console.error(parsed.error);

It also includes the small formatting helpers you'd otherwise rewrite on every project:

ts
import { formatPrice, formatDuration } from "@opencals/storefront-sdk"; formatPrice(45, "USD"); // "$45.00" formatPrice(0, "USD"); // "Free" formatDuration(5400); // "1 hour 30 minutes"

Durations come back in seconds and prices as plain amounts in the store's currency (45 is $45.00, not cents), which is what the helpers expect. Check the output in your own locale before you ship; formatPrice takes a locale as its third argument.

Using it with Next.js and React

The SDK is framework-agnostic; it runs wherever JavaScript runs. The only real rule is credential placement.

Keep the store API key on the server — route handlers, server actions, or server components. Fetch there, then pass typed data (or a customer token) down to the client. Never ship the private spk_ key to the browser. The Next.js booking tutorial walks through the whole flow this way, from services to checkout.

ts
// app/api/availability/route.ts (Next.js route handler) import "@/lib/opencals"; // the setupOpencals module from above import { ProductService } from "@opencals/storefront-sdk"; export async function GET(req: Request) { const { searchParams } = new URL(req.url); const { data: slots } = await ProductService.getCurrentAvailabilities({ path: { productId: searchParams.get("productId")! }, query: { date: searchParams.get("date")!, // YYYY-MM-DD staffMemberId: searchParams.get("staffMemberId") ?? undefined, }, }); return Response.json(slots); }

The client calls your route, not Opencals directly. That's the whole headless booking pattern: your frontend, your framework, your domain — the booking engine and payments handled underneath.

SDK or raw REST — which to reach for

Both are supported; they're not competitors.

Pros

  • SDK: typed methods, autocomplete, and compile-time safety across the whole flow
  • SDK: Zod runtime validation and money/duration helpers included
  • SDK: less boilerplate for the stateful cart-and-checkout sequence

Cons

  • Raw REST: better for non-JavaScript stacks (Python, Go, PHP) — no SDK to depend on
  • Raw REST: leaner for server-to-server jobs or one-off scripts
  • Raw REST: nothing to update when you just need a single endpoint

If you're building a production booking experience in TypeScript, the SDK is the shorter path. If you're integrating from another language or writing a quick automation, the REST API is right there with the same guarantees.

Note

The SDK and the website templates are open source and free; the Opencals platform underneath is a managed cloud service. You get open, inspectable client code running against an API you don't have to operate.

Where to go from here

FAQ

Frequently Asked Questions

Get started

Ready to transform your service business?

Join 150+ businesses already using Opencals. Start on a free development store with every feature unlocked, and only pay once you go live.

No credit card required
Setup in 10 minutes
Cancel anytime