Get started
Fetch data

Server rendering

Server rendering

Read on the server, render in the browser. A Server Component prefetches through @mountaya/client-react/query, and the hooks in the browser find the result in the cache.

Prefetch in a Server Component

import { dehydrate, HydrationBoundary, QueryClient } from "@tanstack/react-query";
import type { ReactNode } from "react";
import { Mountaya } from "@mountaya/client";
import { itineraryQueryOptions } from "@mountaya/client-react/query";

interface ItineraryRouteProps {
  readonly children: ReactNode;
  readonly itineraryId: string;
  readonly publishableKey: string;
}

export const ItineraryRoute = async ({
  children,
  itineraryId,
  publishableKey,
}: ItineraryRouteProps) => {
  // One query client per request, so nothing one visitor read is served to another.
  const queryClient = new QueryClient();
  // The browser's credential: the cache key includes it.
  const mountaya = new Mountaya({ credential: { publishableKey } });

  await queryClient.prefetchQuery(itineraryQueryOptions(mountaya, itineraryId));

  return <HydrationBoundary state={dehydrate(queryClient)}>{children}</HydrationBoundary>;
};

A Client Component under it calls useItinerary(itineraryId) and renders with no request of its own. The Next.js quickstart puts the pieces in place.

Use the same credential on both sides

The prefetch is found only when the server's client holds the browser's credential: the same publishable key, and a session on both sides or on neither. Otherwise the browser reads again.

A page that reads published content works with the key alone on both sides. A page whose browser client holds a session token reads under that session, so prefetch there buys nothing.

What runs where

PackageIn a Server ComponentIn a Client Component
@mountaya/clientCall itCall it, from /browser
@mountaya/client-react/queryCall itCall it
@mountaya/client-reactImport nothing to callHooks and provider
@mountaya/elements-reactImport nothing to callThe map and elements
@mountaya/studio-reactImport nothing to callThe studio

Every chunk of @mountaya/client-react and @mountaya/elements-react is marked "use client", so importing them from a server file needs no wrapper. Their hooks and maps still run in the browser.

Next steps

Last updated