# Next.js quickstart

> A Next.js website that shows a location's services from the server, cached for a minute, and lets customers pick a free time and book an appointment in the browser with the Booking SDK.

Source: https://docs.bifrostorbit.com/booking/developers/quickstart-nextjs/

In about 15 minutes you build a Next.js booking page for Northwilds Oslo. The server renders the location and its services, so search engines see them, and refreshes them at most once a minute. Free times, holding and booking run in the visitor's browser, so every visitor has their own rate limits and the server never books for anyone.

**Tested with:** Next.js 16.4 (App Router), React 19.3, TypeScript 5, `@bifrost-orbit-booking/sdk` 0.1.0, Node.js 24, against a local Booking Orbit.

> **Note:** The SDK is not on npm yet. Until it is, step 2 fails; the code shows the calls to make with the [public booking API](https://docs.bifrostorbit.com/booking/developers/public-api/).

## Before you start

You need:

- **A Booking Orbit location** with at least one service and someone who takes it, such as `northwilds-oslo`. Its short name is the last part of its booking page address.
- **Your website allowed:** under the location's **Settings › Your website**, add `http://localhost:3000` to **Other websites** while you build, and your real website's address before you go live. See [Allowed websites](https://docs.bifrostorbit.com/booking/developers/allowed-websites/).
- **Node.js 20.9 or later.**

## 1. Create the project

```bash
npx create-next-app@latest northwilds-booking --ts --app --eslint --no-tailwind --no-src-dir --import-alias "@/*" --use-npm --yes
cd northwilds-booking
rm app/page.module.css
```

## 2. Install the SDK

```bash
npm install @bifrost-orbit-booking/sdk
```

## 3. Add the settings

```bash
# .env.local
NEXT_PUBLIC_BOOKING_URL=https://app.bifrostorbit.com/booking
NEXT_PUBLIC_BOOKING_LOCATION=northwilds-oslo
```

Neither is a secret: the booking API needs no key. The `NEXT_PUBLIC_` prefix lets the browser read them too.

## 4. Create the clients

```ts
// lib/booking.ts
import { createBookingClient } from "@bifrost-orbit-booking/sdk";

const settings = {
  baseUrl: process.env.NEXT_PUBLIC_BOOKING_URL!,
  location: process.env.NEXT_PUBLIC_BOOKING_LOCATION!,
  locale: "en",
};

export const serverBooking = createBookingClient({
  ...settings,
  fetch: (input, init) => fetch(input, { ...init, next: { revalidate: 60 } }),
});

export const browserBooking = createBookingClient(settings);
```

- **`serverBooking`** reads on the server. Its `fetch` asks Next.js to keep each answer for 60 seconds, the same time Booking Orbit allows, so a busy page doesn't use up the server's rate limit.
- **`browserBooking`** runs in the visitor's browser, for free times, holds and bookings. Free times change every minute, so they are never cached on the server.

## 5. Show the services

Replace `app/page.tsx`:

```tsx
// app/page.tsx
import { serverBooking } from "@/lib/booking";
import { BookingFlow } from "./booking-flow";

export default async function Home() {
  const [location, services] = await Promise.all([serverBooking.location(), serverBooking.services()]);

  return (
    <main>
      <h1>Book at {location.name}</h1>
      <p>{location.description}</p>
      <BookingFlow services={services} />
    </main>
  );
}
```

## 6. Book in the browser

```tsx
// app/booking-flow.tsx
"use client";

import { useState, type FormEvent } from "react";
import { BookingError, isTimeTaken, type BookingAppointment, type BookingHold, type BookingService, type BookingSlots } from "@bifrost-orbit-booking/sdk";

import { browserBooking as booking } from "@/lib/booking";

const timeOf = (iso: string, timeZone: string) => new Intl.DateTimeFormat("en-GB", { timeZone, hour: "2-digit", minute: "2-digit" }).format(new Date(iso));
const dateOf = (iso: string, timeZone: string) => new Intl.DateTimeFormat("en-GB", { timeZone, weekday: "long", day: "numeric", month: "long" }).format(new Date(iso));
const dayOf = (date: string) => dateOf(`${date}T12:00:00Z`, "UTC");

export function BookingFlow({ services }: { services: BookingService[] }) {
  const [service, setService] = useState<BookingService | null>(null);
  const [slots, setSlots] = useState<BookingSlots | null>(null);
  const [hold, setHold] = useState<BookingHold | null>(null);
  const [startsAt, setStartsAt] = useState<string | null>(null);
  const [booked, setBooked] = useState<BookingAppointment | null>(null);
  const [error, setError] = useState<string | null>(null);
  const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;

  async function choose(next: BookingService) {
    setService(next);
    setSlots(null);
    setSlots(await booking.slots({ service: next.id, timeZone, days: 7 }));
  }

  async function pick(time: string) {
    setError(null);
    try {
      setHold(await booking.hold({ service: service!.id, startsAt: time }));
      setStartsAt(time);
    } catch (failure) {
      setError((failure as Error).message);
      if (isTimeTaken(failure)) await choose(service!);
    }
  }

  async function book(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    try {
      const { appointment } = await booking.book({
        service: service!.id,
        startsAt: startsAt!,
        holdToken: hold!.token,
        name: String(form.get("name")),
        email: String(form.get("email")),
        timeZone,
      });
      setBooked(appointment);
    } catch (failure) {
      setError(failure instanceof BookingError ? failure.message : "Something went wrong. Try again.");
      if (isTimeTaken(failure)) {
        setHold(null);
        await choose(service!);
      }
    }
  }

  if (booked) {
    return (
      <section>
        <h2>{"You're booked"}</h2>
        <p>{booked.service.name} with {booked.staff ?? "our team"}, {dateOf(booked.startsAt, timeZone)} at {timeOf(booked.startsAt, timeZone)}.</p>
        <p>Your reference is {booked.reference}. {"We've"} sent the details to {booked.attendee?.email}.</p>
        <p><a href={booked.manageUrl}>Change or cancel</a></p>
      </section>
    );
  }

  return (
    <>
      {error && <p role="alert">{error}</p>}

      <ul>
        {services.map((entry) => (
          <li key={entry.id}>
            <button type="button" onClick={() => void choose(entry)} aria-pressed={service?.id === entry.id}>
              {entry.name}, {entry.durationMinutes} minutes
            </button>
          </li>
        ))}
      </ul>

      {slots && !hold && (
        <section>
          <h2>Pick a time</h2>
          {slots.days.filter((day) => day.slots.length > 0).map((day) => (
            <div key={day.date}>
              <h3>{dayOf(day.date)}</h3>
              {day.slots.map((slot) => (
                <button key={slot.startsAt} type="button" onClick={() => void pick(slot.startsAt)}>
                  {timeOf(slot.startsAt, timeZone)}
                </button>
              ))}
            </div>
          ))}
          {slots.days.every((day) => day.slots.length === 0) && <p>No free times this week{slots.next ? `. The next is ${dateOf(slots.next.startsAt, timeZone)}.` : "."}</p>}
        </section>
      )}

      {hold && startsAt && (
        <form onSubmit={(event) => void book(event)}>
          <h2>{service!.name} at {timeOf(startsAt, timeZone)}</h2>
          <p>{"We're holding this time for you for 10 minutes."}</p>
          <label>Name <input name="name" required autoComplete="name" /></label>
          <label>Email <input name="email" type="email" required autoComplete="email" /></label>
          <button type="submit">Book</button>
        </form>
      )}
    </>
  );
}
```

What happens:

1. The server passes the services to the booking flow.
2. `slots()` asks for seven days of free times in the visitor's time zone. `dayOf` labels each day, which is already grouped in that time zone.
3. `hold()` keeps the chosen time for 10 minutes while the visitor types. If someone else took it a moment ago, the free times load again.
4. `book()` books with the hold's token. Booking Orbit emails the confirmation and the reminders, and `manageUrl` is the visitor's page to change or cancel.

## 7. Run it

```bash
npm run dev
```

Open `http://localhost:3000`, choose a service, pick a time and book. The booking appears under **Calendar** in Booking Orbit. Cancel it with the **Change or cancel** link when you're done.

`npm run build` renders the page ahead of time and refreshes it in the background every minute.

## Make it yours

- **One page per service:** add `app/[service]/page.tsx`, read it with `serverBooking.service(params.service)`, and start the flow with that service. `serverBooking.services()` gives the short names for `generateStaticParams`.
- **Ask what the location asks:** `location()` says whether a phone number and notes are `required`, `optional` or `hidden`. `service(id)` returns the form's questions; send the answers as `answers`, keyed by question id. See Booking in the [public booking API](https://docs.bifrostorbit.com/booking/developers/public-api/).
- **Paid services:** The SDK doesn't take payments. For a service paid online when it's booked, `hold()` and `book()` throw `BookingPaymentRequiredError`. Check with `isPaymentRequired(error)` and send the customer to `error.bookingUrl`, the booking page with the time already chosen, or open the [widget](https://docs.bifrostorbit.com/booking/developers/embed-the-widget/).
- **Paused locations:** Reading still works when a location is paused. Catch `BookingPausedError` from `hold()` and `book()` and say that online booking is unavailable for now.
