# Next.js quickstart

> A Next.js App Router website for Northwilds with a page for every trip, live departures and places, and bookings paid through Stripe's Payment Element.

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

In about 20 minutes you build a Next.js website for Northwilds that reads its trips from Travel Orbit. Every trip has its own page with its departures and places left, travellers see the price as they choose, and they book and pay the deposit with Stripe's Payment Element. Payment goes straight to your organisation's own Stripe account.

Every call to Travel Orbit in this guide is made from your Next.js server, so you don't need to add the website to **Allowed websites**. Bookings made from a server are marked as coming from the API rather than from a website.

**Tested with:** Next.js 16.4.5, React 19.3, `@stripe/stripe-js` 10.2.1, Node.js 24, against an organisation in Stripe test mode.

## Before you start

You need:

- **A published, public trip** in Travel Orbit with at least one open departure, and your **booking name** from [Booking settings](https://docs.bifrostorbit.com/travel/everyone/booking-settings/), such as `northwilds`.
- **Stripe connected**, in test mode while you build, so the test card `4242 4242 4242 4242` pays without charging anyone. Without online payment, bookings come back as requests and nothing is charged.
- **Node.js 20 or later.**

You don't need an API key or Stripe keys of your own.

## 1. Create the project

```bash
npx create-next-app@latest northwilds-trips --ts --app --eslint --no-tailwind --no-src-dir --import-alias "@/*" --no-cache-components --yes
cd northwilds-trips
rm app/page.tsx app/page.module.css
npm install @stripe/stripe-js server-only
```

```bash
# .env.local
TRAVEL_API_URL=https://app.bifrostorbit.com/travel/api/public/northwilds
```

## 2. Add the Travel Orbit helper

```ts
// lib/travel.ts
import 'server-only'

const base = process.env.TRAVEL_API_URL!

export interface Departure {
  id: string
  startDate: string
  endDate: string | null
  status: 'open' | 'full' | 'closed'
  seatsLeft: number | null
  priceFrom: number | null
}

export interface Trip {
  id: string
  slug: string
  name: string
  summary: string
  days: number | null
  images: { url: string; alt: string }[]
  seo: { title: string; description: string }
  currency: string
  priceFrom: number | null
  bookingMode: 'instant' | 'request' | 'closed'
  departures: Departure[]
}

export interface TripDetail extends Trip {
  description: string
  packages: { id: string; name: string; price: number }[]
  travellers: { min: number; max: number }
  terms: string
}

export interface Booking {
  reference: string
  status: 'held' | 'confirmed' | 'requested' | 'expired' | 'cancelled'
  total: number
  currency: string
  schedule: { label: string; dueDate: string; amount: number; status: string }[]
}

export class TravelError extends Error {
  constructor(message: string, readonly status: number) {
    super(message)
  }
}

export async function travel<T>(path: string, init: { body?: unknown; revalidate?: number } = {}): Promise<T> {
  const response = await fetch(`${base}${path}`, {
    method: init.body === undefined ? 'GET' : 'POST',
    headers: init.body === undefined ? undefined : { 'Content-Type': 'application/json' },
    body: init.body === undefined ? undefined : JSON.stringify(init.body),
    ...(init.revalidate ? { next: { revalidate: init.revalidate } } : { cache: 'no-store' }),
  })
  const json = await response.json()
  if (!response.ok) throw new TravelError(json.error?.message ?? `Travel Orbit answered ${response.status}`, response.status)
  return json.data as T
}

export const price = (amount: number | null, currency: string) =>
  amount === null ? '' : new Intl.NumberFormat('en-GB', { style: 'currency', currency }).format(amount / 100)

export const date = (value: string) => new Intl.DateTimeFormat('en-GB', { dateStyle: 'long', timeZone: 'UTC' }).format(new Date(value))
```

- **`travel`** calls the booking API, unwraps `data` and turns an `error` into a `TravelError` with the status. Error messages are written to be shown to travellers as they are.
- **Amounts** are whole minor units in the trip's currency: `56000` with `EUR` is €560.00.
- **Dates** such as `startDate` are calendar dates, so `date` formats them in UTC to keep the day the same everywhere.
- **The types** hold only the fields this guide uses. [The booking API](https://docs.bifrostorbit.com/travel/developers/booking-api/) lists them all, including itineraries, guides, extras and other currencies.

## 3. List the trips

```tsx
// app/page.tsx
import Link from 'next/link'

import { price, travel, type Trip } from '@/lib/travel'

export const revalidate = 30

export default async function Trips() {
  const trips = await travel<Trip[]>('/trips', { revalidate: 30 })
  return (
    <main>
      <h1>Trips</h1>
      <ul>
        {trips.map((trip) => (
          <li key={trip.id}>
            <Link href={`/trips/${trip.slug}`}>
              {trip.images[0] ? <img src={`${trip.images[0].url}?w=640&format=webp`} alt={trip.images[0].alt} width={320} /> : null}
              <h2>{trip.name}</h2>
            </Link>
            <p>{trip.summary}</p>
            <p>
              {trip.days ? `${trip.days} days, ` : ''}from {price(trip.priceFrom, trip.currency)}
            </p>
          </li>
        ))}
      </ul>
    </main>
  )
}
```

```tsx
// app/layout.tsx
import type { Metadata } from 'next'
import Link from 'next/link'

import './globals.css'

export const metadata: Metadata = { title: 'Northwilds trips' }

export default function RootLayout({ children }: LayoutProps<'/'>) {
  return (
    <html lang="en">
      <body>
        <header>
          <Link href="/">Northwilds trips</Link>
        </header>
        {children}
      </body>
    </html>
  )
}
```

`?w=640&format=webp` asks Travel Orbit's media library for a smaller WebP copy of the photo.

**Check it:** run `npm run dev` and open `http://localhost:3000`. You see every published, public trip with its photo and lowest price, such as the Archipelago paddle weekend from €560.00.

## 4. Show a trip

```tsx
// app/trips/[slug]/page.tsx
import type { Metadata } from 'next'
import { notFound } from 'next/navigation'

import { date, price, travel, TravelError, type TripDetail } from '@/lib/travel'

import { BookingForm } from './booking-form'

type Props = { params: Promise<{ slug: string }> }

export const revalidate = 30

export function generateStaticParams() {
  return []
}

async function load({ params }: Props) {
  const { slug } = await params
  try {
    return await travel<TripDetail>(`/trips/${encodeURIComponent(slug)}`, { revalidate: 30 })
  } catch (error) {
    if (error instanceof TravelError && error.status === 404) notFound()
    throw error
  }
}

export async function generateMetadata(props: Props): Promise<Metadata> {
  const trip = await load(props)
  return { title: trip.seo.title, description: trip.seo.description }
}

export default async function TripPage(props: Props) {
  const trip = await load(props)
  const open = trip.departures.filter((departure) => departure.status === 'open')
  return (
    <main>
      {trip.images[0] ? <img src={`${trip.images[0].url}?w=1280&format=webp`} alt={trip.images[0].alt} width={640} /> : null}
      <h1>{trip.name}</h1>
      <p>{trip.summary}</p>
      <div dangerouslySetInnerHTML={{ __html: trip.description }} />

      <h2>Departures</h2>
      <ul>
        {trip.departures.map((departure) => (
          <li key={departure.id}>
            {date(departure.startDate)}: {price(departure.priceFrom, trip.currency)},{' '}
            {departure.status === 'open' ? (departure.seatsLeft === null ? 'places available' : `${departure.seatsLeft} places left`) : departure.status}
          </li>
        ))}
      </ul>

      {trip.bookingMode !== 'closed' && open.length ? (
        <BookingForm
          departures={open.map((departure) => ({ id: departure.id, label: date(departure.startDate) }))}
          packageId={trip.packages[0].id}
          min={trip.travellers.min}
          max={Math.min(trip.travellers.max, 24)}
          terms={trip.terms}
        />
      ) : (
        <p>This trip is not open for online booking right now.</p>
      )}
    </main>
  )
}
```

- **A trip's old address** still answers after the address changes. An address that never existed answers `404`.
- **`departures`** leaves out past and cancelled departures. `seatsLeft` is `null` when a departure has no limit.
- **`bookingMode: "closed"`** refuses bookings, so the page shows no form.
- **This guide books the trip's first package.** A trip with several packages, such as a shared or a single room, lists them in `packages`; let travellers choose and send each traveller's `packageId`.

## 5. Price and book

Two server actions call the booking API: one prices the booking, the other makes it.

```ts
// app/trips/actions.ts
'use server'

import { travel, TravelError } from '@/lib/travel'

export interface BookingInput {
  departureId: string
  packageId: string
  travellers: { firstName: string; lastName: string }[]
  email: string
  acceptTerms: boolean
}

export type Quote = { total: number; dueNow: number; currency: string } | { error: string }

export type BookingResult =
  | {
      reference: string
      email: string
      status: string
      payment: { kind: 'payment' | 'setup'; clientSecret: string; publishableKey: string } | null
    }
  | { error: string }

const failed = (error: unknown) => ({ error: error instanceof TravelError ? error.message : 'Something went wrong. Try again.' })

export async function quote(departureId: string, packageId: string, count: number): Promise<Quote> {
  try {
    return await travel<{ total: number; dueNow: number; currency: string }>('/quote', {
      body: { departureId, travellers: Array.from({ length: count }, () => ({ packageId })) },
    })
  } catch (error) {
    return failed(error)
  }
}

export async function book(input: BookingInput): Promise<BookingResult> {
  try {
    const [lead] = input.travellers
    const { booking, payment } = await travel<{ booking: { reference: string; status: string }; payment: Extract<BookingResult, { reference: string }>['payment'] }>('/bookings', {
      body: {
        departureId: input.departureId,
        lead: { firstName: lead.firstName, lastName: lead.lastName, email: input.email },
        travellers: input.travellers.map((traveller) => ({ ...traveller, packageId: input.packageId })),
        acceptTerms: input.acceptTerms,
      },
    })
    return { reference: booking.reference, email: input.email, status: booking.status, payment }
  } catch (error) {
    return failed(error)
  }
}
```

- **`/quote`** saves nothing, so call it as often as the traveller changes their choices. `dueNow` is what is paid at booking, usually the deposit.
- **`/bookings`** holds the places for 15 minutes, unless the organisation changed it, and answers with the booking and, when something is due, the payment for Stripe.
- **Required details:** a trip can ask for more about each traveller, such as a date of birth or a passport number, in `travellerFields`, and its own `questions`. A booking without them answers `422` with a message naming what is missing. See [The booking form](https://docs.bifrostorbit.com/travel/everyone/booking-form/).

The booking form prices the booking, makes it and then shows the Payment Element:

```tsx
// app/trips/[slug]/booking-form.tsx
'use client'

import { loadStripe, type Stripe, type StripeElements } from '@stripe/stripe-js'
import { useEffect, useRef, useState } from 'react'

import { book, quote, type BookingResult, type Quote } from '../actions'

type Props = {
  departures: { id: string; label: string }[]
  packageId: string
  min: number
  max: number
  terms: string
}

const confirmation = (reference: string, email: string) => `/bookings/${reference}?email=${encodeURIComponent(email)}`

const money = (amount: number, currency: string) => new Intl.NumberFormat('en-GB', { style: 'currency', currency }).format(amount / 100)

export function BookingForm({ departures, packageId, min, max, terms }: Props) {
  const [departureId, setDepartureId] = useState(departures[0]?.id ?? '')
  const [count, setCount] = useState(Math.max(min, 1))
  const [price, setPrice] = useState<Quote | null>(null)
  const [result, setResult] = useState<BookingResult | null>(null)
  const [email, setEmail] = useState('')
  const [message, setMessage] = useState('')
  const stripe = useRef<{ stripe: Stripe; elements: StripeElements } | null>(null)
  const mount = useRef<HTMLDivElement>(null)

  useEffect(() => {
    let live = true
    quote(departureId, packageId, count).then((answer) => live && setPrice(answer))
    return () => {
      live = false
    }
  }, [departureId, packageId, count])

  useEffect(() => {
    if (!result || 'error' in result) return
    if (!result.payment) {
      window.location.assign(confirmation(result.reference, result.email))
      return
    }
    const { clientSecret, publishableKey } = result.payment
    let live = true
    loadStripe(publishableKey).then((loaded) => {
      if (!live || !loaded || !mount.current) return
      const elements = loaded.elements({ clientSecret })
      elements.create('payment').mount(mount.current)
      stripe.current = { stripe: loaded, elements }
    })
    return () => {
      live = false
    }
  }, [result])

  async function submit(form: FormData) {
    const travellers = Array.from({ length: count }, (_, index) => ({
      firstName: String(form.get(`firstName${index}`)),
      lastName: String(form.get(`lastName${index}`)),
    }))
    setResult(await book({ departureId, packageId, travellers, email, acceptTerms: form.get('terms') === 'on' }))
  }

  async function pay() {
    if (!stripe.current || !result || 'error' in result || !result.payment) return
    const options = { elements: stripe.current.elements, confirmParams: { return_url: new URL(confirmation(result.reference, result.email), window.location.origin).toString() } }
    const { error } = result.payment.kind === 'setup' ? await stripe.current.stripe.confirmSetup(options) : await stripe.current.stripe.confirmPayment(options)
    if (error) setMessage(error.message ?? 'The payment did not go through.')
  }

  if (result && !('error' in result) && result.payment) {
    return (
      <section>
        <h2>Pay for booking {result.reference}</h2>
        <div ref={mount} />
        <button type="button" onClick={pay}>
          Pay now
        </button>
        {message ? <p role="alert">{message}</p> : null}
      </section>
    )
  }

  return (
    <form action={submit}>
      <h2>Book this trip</h2>
      <label>
        Departure
        <select value={departureId} onChange={(event) => setDepartureId(event.target.value)}>
          {departures.map((departure) => (
            <option key={departure.id} value={departure.id}>
              {departure.label}
            </option>
          ))}
        </select>
      </label>
      <label>
        Travellers
        <input type="number" min={min} max={max} value={count} onChange={(event) => setCount(Number(event.target.value))} />
      </label>
      {Array.from({ length: count }, (_, index) => (
        <fieldset key={index}>
          <legend>Traveller {index + 1}</legend>
          <input name={`firstName${index}`} placeholder="First name" required />
          <input name={`lastName${index}`} placeholder="Last name" required />
        </fieldset>
      ))}
      <input type="email" placeholder="Email" value={email} onChange={(event) => setEmail(event.target.value)} required />
      <label>
        <input type="checkbox" name="terms" required /> I accept the booking terms
      </label>
      <details>
        <summary>Booking terms</summary>
        <p>{terms}</p>
      </details>
      {price ? 'error' in price ? <p role="alert">{price.error}</p> : <p>Total {money(price.total, price.currency)}, {money(price.dueNow, price.currency)} to pay now</p> : null}
      {result && 'error' in result ? <p role="alert">{result.error}</p> : null}
      <button type="submit">Book</button>
    </form>
  )
}
```

- **`kind: "payment"`** takes what is due now with `confirmPayment`. **`kind: "setup"`** means nothing is due today, so `confirmSetup` saves the card for the later payments.
- **`payment: null`** means the booking is a request: the trip takes requests, or online payment is off. The traveller goes straight to the confirmation page.
- **A failed payment** shows Stripe's reason. The traveller tries again with the same booking; don't make a second one.

**Check it:** open a trip, set two travellers and watch the total change, such as "Total €1,120.00, €224.00 to pay now". Fill in the names and an email, accept the terms and select **Book**. Choose **Card**, enter `4242 4242 4242 4242`, any future expiry date and any CVC, and select **Pay now**.

## 6. Confirm the booking

```tsx
// app/bookings/[reference]/page.tsx
import { notFound } from 'next/navigation'

import { date, price, travel, TravelError, type Booking } from '@/lib/travel'

type Props = { params: Promise<{ reference: string }>; searchParams: Promise<{ email?: string }> }

export const dynamic = 'force-dynamic'

const HEADING: Record<Booking['status'], string> = {
  confirmed: 'Your trip is booked',
  held: 'We are confirming your payment',
  requested: 'Thank you for your request',
  expired: 'This booking has expired',
  cancelled: 'This booking is cancelled',
}

export default async function BookingPage({ params, searchParams }: Props) {
  const { reference } = await params
  const { email = '' } = await searchParams
  const { booking } = await travel<{ booking: Booking }>(`/bookings/${encodeURIComponent(reference)}/check`, { body: { email } }).catch((error) => {
    if (error instanceof TravelError && error.status === 404) notFound()
    throw error
  })
  return (
    <main>
      <h1>{HEADING[booking.status]}</h1>
      <p>Booking {booking.reference}</p>
      <p>Total {price(booking.total, booking.currency)}</p>
      <ul>
        {booking.schedule.map((payment) => (
          <li key={payment.label}>
            {payment.label}: {price(payment.amount, booking.currency)}, due {date(payment.dueDate)} ({payment.status})
          </li>
        ))}
      </ul>
    </main>
  )
}
```

- **`/bookings/{reference}/check`** needs the lead traveller's email in the body. Any other email answers `404`.
- **A booking still `held`** makes Travel Orbit ask Stripe first, so a payment that went through is confirmed straight away.

**Check it:** after paying, you land on `/bookings/NO-64Y4SQ?email=…` with "Your trip is booked", the deposit marked as paid and the balance with its due date. The booking is in **Bookings** in Travel Orbit.

## Next steps

- [The booking API](https://docs.bifrostorbit.com/travel/developers/booking-api/): packages, extras, discount codes, currencies, languages and the traveller account.
- [The booking form](https://docs.bifrostorbit.com/travel/everyone/booking-form/): the questions and traveller details a trip can ask for.
- [Events](https://docs.bifrostorbit.com/travel/developers/webhooks-and-events/): hear about new bookings in your own systems.
- [Troubleshooting](https://docs.bifrostorbit.com/travel/developers/troubleshooting/): what each error means.
