Build a booking page
Use this guide to give principals a page that books time slots. To place and commit holds from your server alone, use Book time slots instead. The page shows a court’s hours, places a hold on one through your server, shows how long the hold has left, and extends or releases it. It renders only plain elements, so it fits any design.
The page uses the hold workflow from @agentpost-tools/resourceshark-sdk/workflows, or useHoldWorkflow from @agentpost-tools/resourceshark-react. Your server uses createHoldEndpoint from @agentpost-tools/resourceshark-sdk/server. The example’s server uses Hono on Node; any server framework works the same way.
Listing slots and writing holds take your secret key, which never goes to a browser, so the page sends every request to your server. Your server also holds every business rule: which hours a principal may read, how long a hold lasts, who owns a hold, and each source key.
Before you start
- A
devsecret key,key, for a project that adopted ResourceShark, from Create a project and issue a key.
This page's code continues the script of the pages above: run its blocks after theirs, in the same file. To run them as a script of their own, first copy each helper from the page that defines it, and set each other value, such as a key or an ID, to one you already have.
1. Create the court
On your server, create a client with createClient({ token: key }) as resourceshark. Create a client lists the client’s options. Create a court that takes one booking per hour, in hourly buckets on UTC. With no schedule, every hour is open at the court’s capacity. Keep court.id for the next steps.
// The club's court: one booking per hour, in hourly buckets on UTC. These
// are the club's choices; ResourceShark keeps whatever the app sends.
const { resource: court } = await resourceshark.resources.create({
key: 'court-1',
name: 'Court 1',
unit: { code: 'court', singular: 'court', plural: 'courts', precision: 0 },
settings: {
time: 'buckets',
bucket: { size: 'step', stepMinutes: 60, timeZone: 'UTC' },
identity: 'count',
supplyExpiry: 'none',
},
scope: { places: false, holders: false },
tracking: 'none',
shortage: 'deny',
capacity: 1,
});
2. Add your server’s hold endpoint
Serve the endpoint at /api/booking on the same origin as your page. Pass your secret key, key, as secretKey from your server’s environment, and court.id as courtId. Replace userOf with a read of your own session.
// The app's server: the court booking page's hold endpoint, in Hono. The
// page lists the court's hours and places, extends, and releases its hold
// here; this server calls ResourceShark with the project's secret key,
// which never reaches the page.
//
// `createHoldEndpoint` keeps users apart and passes refusals on. Every
// business choice is this file's own: which court and hours a user may
// read, how long a hold lasts, who owns a hold, and each `sourceKey`.
// ResourceShark and the SDK hold none of them.
import {
createHoldEndpoint,
HoldRefusal,
} from '@agentpost-tools/resourceshark-sdk/server';
import { Hono } from 'hono';
/** What the page asks for: the hour it wants, and its own checkout ID. */
export interface BookingRequest {
/** The hour's start, as a slot gives it, such as `2026-11-23T15:00:00.000Z`. */
start: string;
/** The page makes one for each hold it asks for, and sends it again on a retry. */
checkoutId: string;
}
export interface BookingServerOptions {
/** The project's secret key, `sk_test_…` or `sk_live_…`. Keep it on the server. */
secretKey: string;
/** ResourceShark's API root. Defaults to Agentpost's hosted API. */
baseUrl?: string;
/** The court pages may book. */
courtId: string;
/** Who is signed in, from your app's own session, or null for no one. */
userOf(request: Request): string | null | Promise<string | null>;
/** For tests: this server's clock, in ms since the epoch. */
now?: () => number;
}
const MINUTE = 60_000;
const HOUR = 60 * MINUTE;
// The club's rules, set here on your server.
// A user may book an hour that starts within the next 7 days.
const BOOKING_WINDOW = 7 * 24 * HOUR;
// A new hold keeps the hour for 5 minutes.
const FIRST_HOLD = '5m';
// Each extension keeps it for 10 minutes from then...
const EXTENSION = '10m';
const EXTENSION_MS = 10 * MINUTE;
// ...up to 30 minutes after the hold was placed.
const LONGEST_HOLD_MS = 30 * MINUTE;
export function createBookingServer(options: BookingServerOptions) {
const now = options.now ?? Date.now;
const { courtId } = options;
const holds = createHoldEndpoint<string, BookingRequest>({
secretKey: options.secretKey,
baseUrl: options.baseUrl,
// The app's choice: each caller's attempt keys are kept apart by caller ID.
callerKey: (user) => user,
// The app's choice: a principal reads this one court, and only the hours
// from the current one to the end of the booking window.
slots(query) {
if (query.resourceId !== courtId)
throw new HoldRefusal('not_found', 'no such court', 404);
const from = Date.parse(query.from ?? '');
const to = Date.parse(query.to ?? '');
if (!Number.isFinite(from) || !Number.isFinite(to))
throw new HoldRefusal('invalid_request', 'from and to are times');
const at = now();
const first = Math.max(from, Math.floor(at / HOUR) * HOUR);
const last = Math.min(to, at + BOOKING_WINDOW);
if (first >= last)
throw new HoldRefusal(
'outside_booking_window',
'choose hours within the next 7 days',
422,
);
return {
resourceId: courtId,
from: new Date(first).toISOString(),
to: new Date(last).toISOString(),
};
},
// The app's choices: an hour that starts on the hour within the booking
// window, held for 5 minutes, for the signed-in user, under a
// `sourceKey` made from the user and the page's checkout.
place(input, user) {
const start = Date.parse(input?.start ?? '');
if (!Number.isFinite(start) || start % HOUR !== 0)
throw new HoldRefusal('invalid_request', 'start is a whole hour');
if (start <= now() || start + HOUR > now() + BOOKING_WINDOW)
throw new HoldRefusal(
'outside_booking_window',
'choose an hour within the next 7 days',
422,
);
if (!/^[\w-]{1,64}$/.test(input.checkoutId ?? ''))
throw new HoldRefusal(
'invalid_request',
'checkoutId is 1 to 64 letters, digits, - or _',
);
return {
lines: [
{
resourceId: courtId,
quantity: 1,
span: {
start: new Date(start).toISOString(),
end: new Date(start + HOUR).toISOString(),
},
},
],
ttl: FIRST_HOLD,
holderRef: `user:${user}`,
sourceKey: `${checkoutPrefix(user)}${input.checkoutId}`,
};
},
// The app's choice: a hold belongs to the user whose checkout placed
// it. The `sourceKey` says whose that was, even once the hold has ended.
owns: (hold, user) => hold.sourceKey.startsWith(checkoutPrefix(user)),
// The app's choice: 10 more minutes from now, until the hold would run
// past 30 minutes from when it was placed.
extend(hold) {
if (
'createdAt' in hold &&
now() + EXTENSION_MS > Date.parse(hold.createdAt) + LONGEST_HOLD_MS
)
throw new HoldRefusal(
'hold_too_long',
'a hold lasts at most 30 minutes from when it was placed',
409,
);
return { ttl: EXTENSION };
},
// No `commit`: this page never books the hour itself. The booking is
// made by whatever takes the payment, on the server, with `commitHold`.
});
const app = new Hono();
// Only the app's own pages, for a signed-in user, may use the endpoint.
app.all('/api/booking/*', async (c) => {
if (!fromThisSite(c.req.raw))
return c.json(
refusal('forbidden', 'change_the_request', 'cross-site request'),
403,
);
const user = await options.userOf(c.req.raw);
if (!user)
return c.json(
refusal('unauthorized', 'change_the_request', 'sign in'),
401,
);
return holds.handle(c.req.raw, user);
});
// The endpoint answers every refusal itself. It throws only when
// ResourceShark can't be reached or refuses the secret key.
app.onError((error, c) => {
console.error(error);
return c.json(
refusal('internal_error', 'retry_later', 'something went wrong'),
500,
);
});
return app;
}
/** The start of every `sourceKey` this caller's checkouts make. */
function checkoutPrefix(user: string) {
return `court-checkout:${encodeURIComponent(user)}:`;
}
/** The standard error body, as the page's `endpointTransport` reads it. */
function refusal(code: string, errorClass: string, message: string) {
return { error: { code, class: errorClass, message } };
}
/**
* Whether a request came from this app's own pages. A browser says where a
* request came from in `Sec-Fetch-Site`, and an older one in `Origin`. A
* request with neither isn't from a browser, so it carries no visitor's
* cookie to misuse.
*/
function fromThisSite(request: Request) {
const site = request.headers.get('Sec-Fetch-Site');
if (site) return site === 'same-origin';
const origin = request.headers.get('Origin');
return !origin || origin === new URL(request.url).origin;
}
- Each hook is one of your rules.
slotsdecides which court and hours a principal may read.placeturns the page’s request into the hold, with itsttl, its line, and itssourceKey.extendsets each extension’sttl. AHoldRefusalthrown in a hook reaches the page as the error body, with your code. ownskeeps principals apart. The endpoint asks it before every extend and release. A hold the principal doesn’t own answers 404, the same as a hold that doesn’t exist, and nothing changes.callerKeykeeps each principal’s retries apart. The endpoint hashes it with the page’s attempt key to make theIdempotency-Keyit sends, so two principals never share a saved answer.- Commit on your server. Commit the hold where you take the payment, with
commitHold. Without acommithook, a commit from the page answers 404. - Wire format lists the routes the endpoint answers and the refusal details that reach the page.
3. Build the page
Pass endpointTransport the path you served the endpoint at. Pass the court’s ID to the page.
// The court booking page in React. It lists the court's next 12 hours,
// holds one through the app's server (./server.ts), counts the hold down,
// and extends or releases it. `useHoldWorkflow` keeps the requests, the
// countdown, and the refusals; this file draws them with plain elements.
import { useEffect, useState } from 'react';
import { useHoldWorkflow } from '@agentpost-tools/resourceshark-react';
import type { Slot } from '@agentpost-tools/resourceshark-sdk';
import {
endpointTransport,
type WorkflowError,
} from '@agentpost-tools/resourceshark-sdk/workflows';
import type { BookingRequest } from './server.ts';
export interface BookingPageProps {
/** The court to book: the one the app's server lets pages read. */
courtId: string;
/** For tests: how the page calls its own server. */
fetch?: typeof fetch;
}
const HOUR = 60 * 60_000;
export function BookingPage({ courtId, fetch }: BookingPageProps) {
const [transport] = useState(() =>
endpointTransport<BookingRequest>({ url: '/api/booking', fetch }),
);
const booking = useHoldWorkflow(transport);
// The page shows the hours from the next one on; the server decides which a user may read.
const [hours] = useState(() => {
const from = Math.ceil(Date.now() / HOUR) * HOUR;
return {
resourceId: courtId,
from: new Date(from).toISOString(),
to: new Date(from + 12 * HOUR).toISOString(),
};
});
// One checkout for each hold the page asks for, so a retry sends the same.
const [checkoutId, setCheckoutId] = useState(() => crypto.randomUUID());
const writing =
booking.pendingAction !== null && booking.pendingAction !== 'slots';
const ranOut = booking.step === 'held' && booking.secondsLeft === 0;
const held = booking.step === 'held' && !ranOut ? booking.hold : null;
// Read the hours on load, and again once a hold runs out and frees its hour.
const { listSlots } = booking;
useEffect(() => {
void listSlots(hours);
}, [listSlots, hours, ranOut]);
const slots =
booking.slots.find((read) => read.query.resourceId === courtId)?.slots ??
[];
async function hold(slot: Slot) {
const outcome = await booking.place({ start: slot.start, checkoutId });
if (outcome.status !== 'failed' || outcome.error.code !== 'network_error')
setCheckoutId(crypto.randomUUID());
void listSlots(hours);
}
async function release() {
await booking.release();
void listSlots(hours);
}
const heldStart = held?.lines[0]?.span?.start;
const heldSlot = slots.find((slot) => slot.start === heldStart);
const notice = ranOut
? 'Your hold ran out. Choose an hour again.'
: booking.step === 'released'
? 'Hold released.'
: null;
const problem = booking.error ? words(booking.error) : null;
return (
<section>
{held ? (
<div data-hold data-hold-id={held.id} data-expires-at={held.expiresAt}>
<p>
Court held for {heldSlot ? when(heldSlot) : heldStart}.{' '}
<span data-countdown>{clock(booking.secondsLeft)} left</span>
</p>
<button
type="button"
data-extend
disabled={writing}
onClick={() => void booking.extend()}
>
Extend hold
</button>{' '}
<button
type="button"
data-release
disabled={writing}
onClick={() => void release()}
>
Release
</button>
</div>
) : null}
{notice ? <p role="status">{notice}</p> : null}
{problem ? <p role="alert">{problem}</p> : null}
<ul>
{slots.map((slot) => (
<li key={slot.start} data-slot data-start={slot.start}>
<button
type="button"
disabled={slot.available < 1 || writing || held !== null}
onClick={() => void hold(slot)}
>
{when(slot)}: {slot.available > 0 ? 'free' : 'taken'}
</button>
</li>
))}
</ul>
</section>
);
}
/** A slot's local date and time, with its time zone. */
function when(slot: Slot) {
return `${slot.local.date} ${slot.local.time} ${slot.timeZone}`;
}
/** Seconds as `m:ss`. */
function clock(seconds: number | null) {
const s = seconds ?? 0;
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
}
/** The words on screen for a refusal, chosen by its code. */
function words(error: WorkflowError) {
switch (error.code) {
case 'insufficient_supply':
return 'Someone else just took that hour. Choose another.';
case 'outside_booking_window':
return 'Choose an hour within the next 7 days.';
case 'hold_too_long':
return 'This hold can’t be extended any further.';
case 'hold_expired':
case 'hold_resolved':
return 'That hold has ended. Choose an hour again.';
case 'network_error':
return 'Can’t reach the server. Try again.';
default:
return 'Something went wrong. Try again.';
}
}
// The court booking page in plain TypeScript, with no UI framework: the
// same page as ./booking.tsx, on `createHoldWorkflow`. It follows the
// workflow's state with `subscribe` and draws it again, with plain
// elements, each time it changes.
import type { Slot } from '@agentpost-tools/resourceshark-sdk';
import {
createHoldWorkflow,
endpointTransport,
type HoldWorkflowState,
type WorkflowError,
} from '@agentpost-tools/resourceshark-sdk/workflows';
import type { BookingRequest } from './server.ts';
export interface BookingOptions {
/** The court to book: the one the app's server lets pages read. */
courtId: string;
/** For tests: how the page calls its own server. */
fetch?: typeof fetch;
}
const HOUR = 60 * 60_000;
export function mountBooking(
host: HTMLElement,
{ courtId, fetch }: BookingOptions,
) {
const booking = createHoldWorkflow(
endpointTransport<BookingRequest>({ url: '/api/booking', fetch }),
);
// The page shows the hours from the next one on; the server decides which a user may read.
const from = Math.ceil(Date.now() / HOUR) * HOUR;
const hours = {
resourceId: courtId,
from: new Date(from).toISOString(),
to: new Date(from + 12 * HOUR).toISOString(),
};
// One checkout for each hold the page asks for, so a retry sends the same.
let checkoutId = crypto.randomUUID();
async function hold(slot: Slot) {
const outcome = await booking.place({ start: slot.start, checkoutId });
if (outcome.status !== 'failed' || outcome.error.code !== 'network_error')
checkoutId = crypto.randomUUID();
void booking.listSlots(hours);
}
async function release() {
await booking.release();
void booking.listSlots(hours);
}
function render(state: HoldWorkflowState) {
const writing =
state.pendingAction !== null && state.pendingAction !== 'slots';
const ranOut = state.step === 'held' && state.secondsLeft === 0;
const held = state.step === 'held' && !ranOut ? state.hold : null;
const slots =
state.slots.find((read) => read.query.resourceId === courtId)?.slots ??
[];
const parts: Node[] = [];
if (held) {
const heldStart = held.lines[0]?.span?.start;
const heldSlot = slots.find((slot) => slot.start === heldStart);
parts.push(
el(
'div',
{
'data-hold': true,
'data-hold-id': held.id,
'data-expires-at': held.expiresAt,
},
el(
'p',
{},
`Court held for ${heldSlot ? when(heldSlot) : heldStart}. `,
el(
'span',
{ 'data-countdown': true },
`${clock(state.secondsLeft)} left`,
),
),
button('Extend hold', writing, () => void booking.extend(), {
'data-extend': true,
}),
' ',
button('Release', writing, () => void release(), {
'data-release': true,
}),
),
);
}
const notice = ranOut
? 'Your hold ran out. Choose an hour again.'
: state.step === 'released'
? 'Hold released.'
: null;
if (notice) parts.push(el('p', { role: 'status' }, notice));
if (state.error) parts.push(el('p', { role: 'alert' }, words(state.error)));
parts.push(
el(
'ul',
{},
...slots.map((slot) =>
el(
'li',
{ 'data-slot': true, 'data-start': slot.start },
button(
`${when(slot)}: ${slot.available > 0 ? 'free' : 'taken'}`,
slot.available < 1 || writing || held !== null,
() => void hold(slot),
),
),
),
),
);
host.replaceChildren(el('section', {}, ...parts));
}
// Draw each change, and read the hours again once a hold runs out and frees its hour.
let ranOutBefore = false;
const unsubscribe = booking.subscribe(() => {
const state = booking.getSnapshot();
const ranOut = state.step === 'held' && state.secondsLeft === 0;
if (ranOut && !ranOutBefore) void booking.listSlots(hours);
ranOutBefore = ranOut;
render(state);
});
render(booking.getSnapshot());
void booking.listSlots(hours);
return {
workflow: booking,
/** Stops the countdown and empties the host. */
unmount() {
unsubscribe();
booking.dispose();
host.replaceChildren();
},
};
}
/** An element with its attributes and children. `true` sets an attribute with no value; `false` leaves it off. */
function el(
tag: string,
attributes: Record<string, string | boolean>,
...children: (Node | string)[]
) {
const node = document.createElement(tag);
for (const [name, value] of Object.entries(attributes))
if (value !== false) node.setAttribute(name, value === true ? '' : value);
node.append(...children);
return node;
}
function button(
label: string,
disabled: boolean,
onClick: () => void,
attributes: Record<string, string | boolean> = {},
) {
const node = el('button', { type: 'button', disabled, ...attributes }, label);
node.addEventListener('click', onClick);
return node;
}
/** A slot's local date and time, with its time zone. */
function when(slot: Slot) {
return `${slot.local.date} ${slot.local.time} ${slot.timeZone}`;
}
/** Seconds as `m:ss`. */
function clock(seconds: number | null) {
const s = seconds ?? 0;
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
}
/** The words on screen for a refusal, chosen by its code. */
function words(error: WorkflowError) {
switch (error.code) {
case 'insufficient_supply':
return 'Someone else just took that hour. Choose another.';
case 'outside_booking_window':
return 'Choose an hour within the next 7 days.';
case 'hold_too_long':
return 'This hold can’t be extended any further.';
case 'hold_expired':
case 'hold_resolved':
return 'That hold has ended. Choose an hour again.';
case 'network_error':
return 'Can’t reach the server. Try again.';
default:
return 'Something went wrong. Try again.';
}
}
- The page asks for a hold with its own shape.
BookingRequestis the hour and a checkout ID. Your server’splacehook turns it into the hold, so your server sets thettland thesourceKey. - Make a new checkout ID after each answered request. After a
network_error, the page keeps the same ID and the workflow reuses its attempt key, so a hold that already landed isn’t placed twice. - The countdown uses the clock of your app’s server.
secondsLeftcounts whole seconds using the offset from successful answers’serverNow, and ticks only while something is subscribed. It’s advisory: the hold ends when ResourceShark says. State and countdown says howsecondsLeftrounds and when it stops. - Choose the words on screen by
error.code.insufficient_supplymeans another principal holds or booked the hour. Your own codes, such ashold_too_long, arrive the same way.
Check it worked
Open the page as a signed-in principal, hold the first free hour, then check:
- Reading the hold with
keyshowsstatus: 'open', that principal’sholderRef, the hour’s span, and anexpiresAt5 minutes aftercreatedAt. - The countdown shows
4:59 leftor close to it and goes down each second. - After Extend hold, the hold’s
expiresAtis later, and the countdown shows close to10:00 left. - After loading the slots, another principal’s page shows the hour as
taken, and theirPOST /api/booking/holds/{id}/releasefor your hold answers 404. - After Release, the hold’s
statusisreleasedand the hour shows asfreeagain.
The example app’s tests assert the first and the fourth:
// The hold is the principal's, on the hour they chose, for the 5 minutes the server gives.
const placed = await holdOf(resourceshark, holdId);
assert.equal(placed.status, 'open');
assert.equal(placed.holderRef, 'user:ana');
assert.equal(placed.lines[0].span?.start, start);
assert.equal(
(Date.parse(placed.expiresAt) - Date.parse(placed.createdAt)) / 60_000,
5,
);
// Another principal's release answers as if there were no such hold.
const byBen = await post(pageFetch(app, 'ben'), `/holds/${holdId}/release`);
assert.equal(byBen.status, 404);
// A page on another site can't release it either, with the principal signed in.
const forged = await pageFetch(app, 'ana')(
`/api/booking/holds/${holdId}/release`,
{
method: 'POST',
headers: {
'idempotency-key': crypto.randomUUID(),
'sec-fetch-site': 'cross-site',
origin: 'https://evil.test',
},
},
);
assert.equal(forged.status, 403);
assert.equal((await holdOf(resourceshark, holdId)).status, 'open');
To set how long holds last and how far ahead principals can book, read Limit hold length and booking window.