Basker Docs

Build a site with Next.js

Render a Basker site with the Next.js App Router, route, routes, and the FrontStage client

This guide builds a Next.js App Router site that renders every public URL of a Basker site. One optional catch-all route resolves each path with route, and generateStaticParams pre-renders the paths from routes. The examples use Next.js 15 and https://www.example.org/graphql.

Create the project

npx create-next-app@latest basker-site --typescript --app
cd basker-site

Add the FrontStage client. It is not on npm yet. Build it in a checkout of the Basker repository, then install it from its folder:

pnpm --filter @baskerhq/frontstage-client build
npm install /path/to/basker/packages/frontstage-client

To work without the client, send GET requests with fetch. See Send your first query.

Add the endpoint of your site to .env.local:

BASKER_GRAPHQL_URL=https://www.example.org/graphql

Create the client

Pass next.revalidate so that Next.js caches each response for 60 seconds, the same as the browser lifetime that the API sets.

lib/basker.ts
import { createFrontstageClient } from "@baskerhq/frontstage-client";

export const basker = createFrontstageClient({
  endpoint: process.env.BASKER_GRAPHQL_URL!,
  fetch: (input, init) => fetch(input, { ...init, next: { revalidate: 60 } }),
});

export const ROUTE_QUERY = `query Route($path: String!) {
  route(path: $path) {
    __typename
    ... on RouteRedirect { to status }
    ... on RouteNotFound { page { title } }
    ... on RouteMatch {
      node {
        __typename
        title
        path
        seo { title description noIndex image { url(transform: { width: 1200, format: jpeg }) } }
        alternates { locale path }
        ... on Page { description }
        ... on Event {
          description
          startDate
          venue { title path }
          instances(limit: 20) { docs { id startDate path } }
        }
      }
    }
  }
}`;

export type RouteNode = {
  __typename: string;
  title: string;
  path: string;
  description?: string | null;
  startDate?: string | null;
  venue?: { title: string; path: string } | null;
  instances?: { docs: Array<{ id: string; startDate: string; path: string }> };
  seo: { title: string | null; description: string | null; noIndex: boolean; image: { url: string } | null };
  alternates: Array<{ locale: string; path: string }>;
};

export type RouteData = {
  route: {
    __typename: "RouteMatch" | "RouteRedirect" | "RouteNotFound";
    to?: string;
    status?: number;
    node?: RouteNode;
  };
};

Resolve the path

The site languages decide how to read the path. splitLocalePath returns the language of a prefixed path such as /es/visit.

lib/resolve.ts
import { splitLocalePath } from "@baskerhq/frontstage-client";
import { cache } from "react";

import type { RouteData } from "./basker";

import { basker, ROUTE_QUERY } from "./basker";

type SiteData = { site: { defaultLocale: string; locales: Array<{ code: string }> } };

export const getSite = cache(() =>
  basker.query<SiteData>(`{ site { defaultLocale locales { code } } }`),
);

export const resolvePath = cache(async (segments: string[] = []) => {
  const { site } = await getSite();
  const path = `/${segments.join("/")}`;
  const { locale } = splitLocalePath(path, site.locales.map(l => l.code), site.defaultLocale);
  const { route } = await basker.query<RouteData>(ROUTE_QUERY, { path }, { locale });
  return { locale, route };
});

Add the catch-all page

app/[[...path]]/page.tsx
import type { Metadata } from "next";

import { notFound, permanentRedirect, redirect } from "next/navigation";

import { basker } from "@/lib/basker";
import { getSite, resolvePath } from "@/lib/resolve";

type Props = { params: Promise<{ path?: string[] }> };

export async function generateStaticParams() {
  const { site } = await getSite();
  const params: Array<{ path: string[] }> = [];
  for (const { code } of site.locales) {
    for (let page = 1; ; page += 1) {
      const { routes } = await basker.query<{ routes: { hasNextPage: boolean; docs: Array<{ path: string }> } }>(
        `query Routes($page: Int) { routes(page: $page, limit: 500) { hasNextPage docs { path } } }`,
        { page },
        { locale: code },
      );
      for (const { path } of routes.docs) {
        params.push({ path: path.split("/").filter(Boolean) });
      }
      if (!routes.hasNextPage) {
        break;
      }
    }
  }
  return params;
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { route } = await resolvePath((await params).path);
  const node = route.node;
  if (!node) {
    return {};
  }
  return {
    title: node.seo.title ?? node.title,
    description: node.seo.description ?? undefined,
    robots: node.seo.noIndex ? { index: false } : undefined,
    openGraph: node.seo.image ? { images: [node.seo.image.url] } : undefined,
    alternates: {
      languages: Object.fromEntries(node.alternates.map(a => [a.locale, a.path])),
    },
  };
}

export default async function Page({ params }: Props) {
  const { locale, route } = await resolvePath((await params).path);

  if (route.__typename === "RouteRedirect" && route.to) {
    if (route.status === 301) {
      permanentRedirect(route.to);
    }
    redirect(route.to);
  }
  if (route.__typename === "RouteNotFound" || !route.node) {
    notFound();
  }

  const node = route.node;
  return (
    <main lang={locale}>
      <h1>{node.title}</h1>
      {node.startDate && <p>{new Date(node.startDate).toLocaleString(locale)}</p>}
      {node.venue && <a href={node.venue.path}>{node.venue.title}</a>}
      {node.description && <p>{node.description}</p>}
      {node.instances && (
        <ul>
          {node.instances.docs.map(instance => (
            <li key={instance.id}>
              <a href={instance.path}>{new Date(instance.startDate).toLocaleString(locale)}</a>
            </li>
          ))}
        </ul>
      )}
    </main>
  );
}

Add the 404 page

app/not-found.tsx
import { basker } from "@/lib/basker";

export default async function NotFound() {
  const { page } = await basker.query<{ page: { title: string } | null }>(`{ page(slug: "404") { title } }`);
  return <h1>{page?.title ?? "Page not found"}</h1>;
}

Render booking status in the browser

Booking status changes fast. Load it in a client component so the page itself can stay cached for longer:

app/components/availability.tsx
"use client";

import { createFrontstageClient } from "@baskerhq/frontstage-client";
import { useEffect, useState } from "react";

const basker = createFrontstageClient({ endpoint: "https://www.example.org/graphql" });

type Instance = { id: string; ticketing: { status: string | null; label: string | null; bookingUrl: string | null } | null };

export function Availability({ eventId }: { eventId: string }) {
  const [instances, setInstances] = useState<Instance[]>([]);
  useEffect(() => {
    basker
      .query<{ eventInstances: { docs: Instance[] } }>(
        `query Availability($eventId: ID!) { eventInstances(eventId: $eventId) { docs { id ticketing { status label bookingUrl } } } }`,
        { eventId },
      )
      .then(data => setInstances(data.eventInstances.docs));
  }, [eventId]);
  return <ul>{instances.map(i => <li key={i.id}>{i.ticketing?.label} {i.ticketing?.status}</li>)}</ul>;
}

See Events, calendars, and ticketing.

On this page