Get started
Get started

Next.js quickstart

Next.js quickstart

An itinerary page on the App Router: a Server Component reads the itinerary, and a Client Component draws it on a map.

1

Create the app
npx create-next-app@latest my-map --yes
cd my-map
npm install @mountaya/client @mountaya/client-react @mountaya/elements @mountaya/elements-react @tanstack/react-query maplibre-gl@6.16.0

2

Set your keys

Create both keys under Organization → API keys in the Mountaya app. The publishable key needs the publishing and tiles scopes.

.env.local
MOUNTAYA_PUBLISHABLE_KEY=pk_your_publishable_key
MOUNTAYA_SECRET_KEY=sk_your_secret_key

3

Add the providers
app/providers.tsx
"use client";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { type ReactNode, useState } from "react";
import { Mountaya } from "@mountaya/client/browser";
import { MountayaProvider } from "@mountaya/client-react";

export function Providers({
  children,
  publishableKey,
}: {
  children: ReactNode;
  publishableKey: string;
}) {
  const [queryClient] = useState(() => new QueryClient());
  const [mountaya] = useState(() => new Mountaya({ credential: { publishableKey } }));

  return (
    <QueryClientProvider client={queryClient}>
      <MountayaProvider client={mountaya}>{children}</MountayaProvider>
    </QueryClientProvider>
  );
}

Mount them in the root layout, with the stylesheet:

app/layout.tsx
import "@mountaya/elements-react/styles.css";
import type { ReactNode } from "react";
import { Providers } from "./providers";

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body style={{ margin: 0 }}>
        <Providers publishableKey={process.env.MOUNTAYA_PUBLISHABLE_KEY ?? ""}>
          {children}
        </Providers>
      </body>
    </html>
  );
}

4

Read the itinerary on the server

Import from @mountaya/client-react/query: it is the entry a Server Component can call.

app/itineraries/[itineraryId]/layout.tsx
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";

export default async function ItineraryLayout({
  children,
  params,
}: {
  children: ReactNode;
  params: Promise<{ itineraryId: string }>;
}) {
  const { itineraryId } = await params;
  // One query client per request, so no visitor sees another's reads.
  const queryClient = new QueryClient();
  // The browser's credential, so the page finds this read in its cache.
  const mountaya = new Mountaya({
    credential: { publishableKey: process.env.MOUNTAYA_PUBLISHABLE_KEY ?? "" },
  });

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

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

5

Draw the map in the browser
app/itineraries/[itineraryId]/page.tsx
"use client";

import { use, useEffect } from "react";
import { useItinerary, useMountaya } from "@mountaya/client-react";
import { MapControls, MapView, useMountayaMap } from "@mountaya/elements-react";

// Draws the itinerary on the map it sits in, and frames it.
function DrawnItinerary({ itineraryId }: { itineraryId: string }) {
  const map = useMountayaMap();

  useEffect(() => {
    if (map === null) return;
    const drawing = new AbortController();
    map.setItinerary(itineraryId, { fit: true, signal: drawing.signal }).catch((error: unknown) => {
      if (!drawing.signal.aborted) console.error(error);
    });
    return () => drawing.abort();
  }, [itineraryId, map]);

  return null;
}

export default function ItineraryPage({ params }: { params: Promise<{ itineraryId: string }> }) {
  const { itineraryId } = use(params);
  const mountaya = useMountaya();
  // Already in the cache: the server read it.
  const { data: itinerary } = useItinerary(itineraryId);

  return (
    <main style={{ display: "grid", gridTemplateRows: "auto 1fr", height: "100dvh" }}>
      <h1>{itinerary?.name ?? "Loading…"}</h1>
      <MapView client={mountaya}>
        <MapControls compass layers zoom />
        <DrawnItinerary itineraryId={itineraryId} />
      </MapView>
    </main>
  );
}

6

Run it
npm run dev

Open /itineraries/ followed by the id of one of your published itineraries. The name arrives in the server's HTML, and the map draws in the browser.

Add a session token

A publishable key reads only published content. For drafts and the Data API, add a route that mints a session token with your secret key:

app/api/mountaya-session/route.ts
import { Mountaya } from "@mountaya/client";

// A new token on every call: never cache this route.
export const dynamic = "force-dynamic";

const mountaya = new Mountaya({
  credential: { secretKey: process.env.MOUNTAYA_SECRET_KEY ?? "" },
});

export async function GET(): Promise<Response> {
  const { data } = await mountaya.admin.sessions.postSession({
    body: { publishable_key: process.env.MOUNTAYA_PUBLISHABLE_KEY ?? "" },
  });

  // { token, expires_at, user_id }: what useSessionToken reads.
  return Response.json(data, { headers: { "Cache-Control": "no-store" } });
}

Then build the browser client over useSessionToken, as authentication in the SDK shows. The complete app is the examples/next-app directory of the SDK repository.

Next steps

Last updated