# Build a route planner

> Canonical URL: https://docs.mountaya.com/en/sdks/typescript/tutorials/route-planner/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Click the map to add waypoints, route them with the Data API, and draw the route with its elevation profile.

A planner where a hiker clicks the map to add waypoints. Each click routes the trail with the Data API, draws it, and updates the elevation profile below.

![A route drawn on the map above its elevation profile](https://docs.mountaya.com/examples/tutorial-route-planner.webp)

You need:

- a publishable key with the `data` and `tiles` scopes, and your secret key, from **Organization → API keys** in the [Mountaya app](https://app.mountaya.com/api-keys);
- a Vite and React app. To start one:

```bash
npx create-vite@latest route-planner --template react-ts && cd route-planner && \
  npm install @mountaya/client @mountaya/client-react @mountaya/elements \
  @mountaya/elements-react @tanstack/react-query maplibre-gl@6.18.0
```

The Data API is self-serve. The base map comes with the Tile API, which needs an agreement.

**1. Mint a session token**

Every Data API request carries a session token. Your server mints it with the secret key and hands it to the page.

**cURL**

```bash
export MOUNTAYA_DATA_TOKEN=$(curl -s -X POST https://api.mountaya.com/v1/sessions \
  -H "X-API-Key: $MOUNTAYA_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"publishable_key\": \"$MOUNTAYA_PUBLISHABLE_KEY\"}" | jq -r .data.token)
```

**TypeScript**

```typescript
import { Mountaya } from "@mountaya/client";
import { MountayaAdmin } from "@mountaya/client/admin";

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

// Answer your page's GET /api/mountaya-session with this session.
const { data: session } = await new MountayaAdmin(server).sessions.postSession({
  body: { publishable_key: publishableKey },
});

console.log(session.token, session.expires_at);
```

**Python**

```python
import os

import requests

# Answer your page's GET /api/mountaya-session with this session.
session = requests.post(
    "https://api.mountaya.com/v1/sessions",
    headers={"X-API-Key": os.environ["MOUNTAYA_SECRET_KEY"]},
    json={"publishable_key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"]},
    timeout=10,
).json()["data"]

print(session["expires_at"])
```

**Response**

```json
{
  "data": {
    "expires_at": "2026-11-09T13:37:04.051423Z",
    "token": "sess_your_session_token",
    "user_id": null
  }
}
```

Serve the session from a route such as `/api/mountaya-session`. [Authentication](https://docs.mountaya.com/en/authentication.md) has route handlers for Next.js, Express and FastAPI.

The next step reads the token as `MOUNTAYA_DATA_TOKEN`. It lasts five minutes, so mint another before it expires.

- Mint only on a server: the secret key never reaches a browser. The page receives `{ token, expires_at, user_id }` and sends `X-API-Key` (publishable) and `X-Session-Token` with each Data API request; the SDK does this from the client's `credential`.
- A token minted without `user_id` acts as nobody: the Data API answers routing and places, which need no member.
- The token lasts five minutes. `useSessionToken` (`@mountaya/client-react`) calls the route again before it expires; never cache the route's answer.
- The `data` scope works once the organization holds the Data API product (a card on file, or an agreement); before that, a request under it answers `402`.

**2. Route between two points**

`directions` takes the activity and the waypoints, as `[longitude, latitude]`, and answers the route with its figures.

**cURL**

```bash
curl -s https://data.mountaya.com/graphql \
  -H "X-API-Key: $MOUNTAYA_PUBLISHABLE_KEY" \
  -H "X-Session-Token: $MOUNTAYA_DATA_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "query Directions($input: DirectionsInput!) { directions(input: $input) { routes { distance duration summary elevation { ascent descent } } } }",
    "variables": {
      "input": {
        "activity": "HIKING_AND_TRAIL",
        "waypoints": [[6.8712, 45.9231], [6.9271, 45.9822]]
      }
    }
  }'
```

**TypeScript**

```typescript
import { Mountaya } from "@mountaya/client";

const mountaya = new Mountaya({
  credential: {
    publishableKey: process.env.MOUNTAYA_PUBLISHABLE_KEY ?? "",
    sessionToken: process.env.MOUNTAYA_DATA_TOKEN ?? "",
  },
});

const { routes } = await mountaya.data.directions(
  {
    activity: "HIKING_AND_TRAIL",
    waypoints: [
      [6.8712, 45.9231],
      [6.9271, 45.9822],
    ],
  },
  {
    select: {
      routes: { distance: true, duration: true, summary: true, elevation: { ascent: true, descent: true } },
    },
  },
);

console.log(routes[0]?.summary);
```

**Python**

```python
query = """
query Directions($input: DirectionsInput!) {
  directions(input: $input) {
    routes { distance duration summary elevation { ascent descent } }
  }
}
"""

result = requests.post(
    "https://data.mountaya.com/graphql",
    headers={
        "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
        "X-Session-Token": session["token"],
    },
    json={
        "query": query,
        "variables": {
            "input": {
                "activity": "HIKING_AND_TRAIL",
                "waypoints": [[6.8712, 45.9231], [6.9271, 45.9822]],
            }
        },
    },
    timeout=30,
).json()

if "errors" in result:
    raise RuntimeError(result["errors"])
print(result["data"]["directions"]["routes"][0]["summary"])
```

**Response**

```json
{
  "data": {
    "directions": {
      "routes": [
        {
          "distance": 9005.14542243658,
          "duration": 9631.009017156648,
          "summary": "9.0 km, ~2h40m, +277m / -56m elevation, 67% path, 12% track, 8% road.",
          "elevation": {
            "ascent": 275.21426732008536,
            "descent": 53.70828803578206
          }
        }
      ]
    }
  }
}
```

Distances are in meters, durations in seconds and climbs in meters. The page asks for the same route, plus its `geometry`: a line of `[longitude, latitude, elevation]` positions.

- `POST https://data.mountaya.com/graphql`, queries only. Enum values are SCREAMING_SNAKE_CASE (`HIKING_AND_TRAIL`). A failed query still answers `200 OK` with an `errors` array: check it on every response.
- `directions` takes 2 to 45 waypoints, and the straight line through them may be at most 100 km; either limit is `VALIDATION_FAILED` at `["input", "waypoints"]`. A planner should stop adding points at 45.
- `routes[].geometry` is a GeoJSON `LineString` of `[longitude, latitude, elevation]`. `routes[].elevation` carries `ascent`, `descent`, and `altitude` and `gradient` (each `min` and `max`). `summary` is a human sentence in the request's language.
- `speed` (km/h on level ground) only rescales `duration`; omit it for the activity's default.
- The TypeScript client's `select` sends only the fields asked for; without it, the full selection, geometry and analysis included, is sent.

**3. Build the planner**

Replace the `src/main.tsx` Vite wrote with this file.

The page builds one client over the session route, so tokens renew while the map stays mounted. Each click pins a waypoint. `addDirections` routes the waypoints through the same client and draws the result, and the profile draws its line.

**src/main.tsx**

```tsx
/// <reference types="vite/client" />
import { Mountaya } from "@mountaya/client/browser";
import { useSessionToken } from "@mountaya/client-react";
import type { MountayaMap } from "@mountaya/elements";
import { MapControls, MapView, MountayaElementsProvider } from "@mountaya/elements-react";
import { ItineraryProfile } from "@mountaya/elements-react/elements";
import "@mountaya/elements-react/styles.css";
import { StrictMode, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";

// Your server route from step 1.
const mint = async () => {
  const response = await fetch("/api/mountaya-session");
  if (!response.ok) throw new Error(`The session route answered ${response.status}.`);
  return response.json();
};

type Route = Awaited<ReturnType<MountayaMap["addDirections"]>>["result"]["routes"][number];

const RoutePlanner = () => {
  const { session } = useSessionToken({ mint });
  const [client] = useState(
    () =>
      new Mountaya({
        credential: {
          publishableKey: import.meta.env.VITE_MOUNTAYA_PUBLISHABLE_KEY,
          sessionToken: session,
        },
      }),
  );
  const [map, setMap] = useState<MountayaMap | null>(null);
  const [waypoints, setWaypoints] = useState<[number, number][]>([]);
  const [route, setRoute] = useState<Route | null>(null);

  // Each click on the map adds a waypoint, up to the 45 one route takes.
  useEffect(() => {
    if (map === null) return;
    return map.on("click", ({ lngLat }) =>
      setWaypoints((current) => (current.length < 45 ? [...current, lngLat] : current)),
    );
  }, [map]);

  // Pin the waypoints, then route them and draw the route.
  useEffect(() => {
    if (map === null) return;
    map.clearMarkers();
    waypoints.forEach((lngLat, index) => {
      map.addMarker({ id: `waypoint-${index}`, label: `Waypoint ${index + 1}`, lngLat });
    });
    map.clearDirections();
    if (waypoints.length < 2) {
      setRoute(null);
      return;
    }
    map
      .addDirections({ activity: "HIKING_AND_TRAIL", waypoints })
      .then(({ result }) => setRoute(result.routes[0] ?? null))
      .catch((error: unknown) => {
        // Clearing the directions cancels a route still in flight.
        if (!(error instanceof Error && error.name === "AbortError")) console.error(error);
      });
  }, [map, waypoints]);

  return (
    <MountayaElementsProvider client={client} map={map}>
      <div style={{ height: 480 }}>
        <MapView center={[6.8712, 45.9231]} client={client} onReady={setMap} terrain="topo" zoom={12}>
          <MapControls preferences={false} />
        </MapView>
      </div>
      <p>
        {route === null ? "Click the map to add waypoints." : route.summary}{" "}
        <button onClick={() => setWaypoints([])} type="button">
          Clear
        </button>
      </p>
      {route?.geometry ? (
        <ItineraryProfile
          axis
          segments={[{ geojson: route.geometry, id: "route", name: "Your route" }]}
          stats={["distance", "ascent", "descent"]}
          tooltip
        />
      ) : null}
    </MountayaElementsProvider>
  );
};

const root = document.getElementById("root");
if (root === null) throw new Error("index.html has no #root element.");

createRoot(root).render(
  <StrictMode>
    <RoutePlanner />
  </StrictMode>,
);
```

- Build the client once, over `session`: requests made before the first token wait for it, and a renewed token reaches the next request with nothing rebuilt. A client rebuilt per token would rebuild the map.
- `map.on(event, handler)` returns its own unsubscribe, which the effect returns. The `click` payload is `{ lngLat: [longitude, latitude], point }`; `featureclick` fires only on Mountaya's own features.
- `map.addDirections(input, options?)` runs `client.data.directions(input)` through the map's client, draws the routes at the itinerary-line rank, and resolves `{ id, result }`. It draws the full selection. `map.clearDirections()` removes every drawn route and cancels one in flight, which then rejects with an `AbortError`. `editDirections(id, patch)` re-runs one route with a changed input; `fit: true` in the options frames it.
- `map.addMarker({ id, lngLat, label, glyph, color, onClick })` replaces a marker under the same id; `clearMarkers()` removes them all.
- `ItineraryProfile` takes `segments` instead of `itineraryId` for a line you hold: each segment's `geojson` (a `LineString` with elevations) makes up the curve, in order. Elevation comes from the route's third coordinate.
- The map and the profile share the provider's map, so hovering the curve places a marker on the route.

**4. Run it**

In development, Vite's dev server can answer `/api/mountaya-session` in place of your backend. This `vite.config.ts` does, with the secret key from its environment. Drop its `resolve.conditions`, which point the SDK's own example at the SDK's source.

**From examples/elements-react-map/vite.config.ts**

```typescript
import react from "@vitejs/plugin-react";
import { defaultClientConditions, defineConfig, loadEnv, type Plugin } from "vite";

/**
 * Answers the page's `/api/mountaya-session` from the dev server, standing in for your backend.
 *
 * Minting a session token takes the secret key, and a secret key never reaches a browser: the
 * page asks a server for a token, and that server holds the key. While `vite` serves this
 * application, the dev server is that server. It reads the secret key from its own environment,
 * and Vite hands a page only the variables whose name starts with `VITE_`, so the secret key is
 * in no bundle.
 *
 * The answer is the session `POST /v1/sessions` returns, taken out of the `data` it arrives in:
 * `{ token, expires_at, user_id }`, which is what `useSessionToken`'s `mint` resolves with. The
 * session script the embed wizard copies under `require_session_token` reads this shape and the
 * API's own `{ data: { token, expires_at } }` alike, so the same endpoint answers a hosted embed's
 * page too. A built application has no dev server: its own backend serves the same address.
 *
 * The token is minted without `user_id`, so it reads what the key alone does: the published
 * itinerary, and no private or unpublished one. It still matters, since an organization that requires a
 * session token is answered nothing without one. To read a member's drafts, a backend adds
 * `user_id`, the member it signed in, read from its own session and never from the request.
 *
 * @param env The dev server's environment, as `loadEnv` reads it.
 */
const sessionEndpoint = (env: Record<string, string>): Plugin => ({
  configureServer(server) {
    server.middlewares.use("/api/mountaya-session", (_request, response) => {
      const answer = (status: number, body: unknown): void => {
        response.statusCode = status;
        response.setHeader("Content-Type", "application/json");
        response.end(JSON.stringify(body));
      };

      const publishableKey = env.VITE_MOUNTAYA_PUBLISHABLE_KEY;
      const secretKey = env.MOUNTAYA_SECRET_KEY;
      if (publishableKey === undefined || secretKey === undefined) {
        answer(500, {
          error: "Set VITE_MOUNTAYA_PUBLISHABLE_KEY (pk_…) and MOUNTAYA_SECRET_KEY (sk_…).",
        });

        return;
      }

      // Imported at the first mint and not at the top of this file, so `vite build` loads no
      // client into the process that only bundles. Minting is the admin unit's.
      Promise.all([import("@mountaya/client"), import("@mountaya/client/admin")])
        .then(([{ Mountaya }, { MountayaAdmin }]) =>
          new MountayaAdmin(new Mountaya({ credential: { secretKey } })).sessions.postSession({
            body: { publishable_key: publishableKey },
          }),
        )
        .then(({ data: session }) => answer(200, session))
        .catch((error: unknown) => answer(502, { error: String(error) }));
    });
  },
  name: "mountaya-session",
});

/**
 * The example builds against the packages' SOURCE, not their `dist`.
 *
 * `@mountaya/source` is the condition every package in this family publishes its own TypeScript
 * under, and naming it here is what makes this example a gate: a change to `MapView` or to the
 * client's credential is compiled by the next build of this application, with no build of the
 * packages in between. An application pointed at `dist` goes on succeeding against whatever was
 * built last.
 *
 * It is the one thing in this file a consumer does not copy. Their bundler resolves the published
 * `dist` under the default conditions, which is what `scripts/packaging.test.mjs` holds every
 * package to.
 */
export default defineConfig(({ mode }) => ({
  // Every variable, the unprefixed ones included: the endpoint above runs in the dev server
  // and reads the secret key there.
  plugins: [react(), sessionEndpoint(loadEnv(mode, ".", ""))],
  resolve: {
    // Vite replaces its default conditions with a list a config names, so they follow the
    // condition: without them a dependency loses `module`, `browser` and `development|production`.
    conditions: ["@mountaya/source", ...defaultClientConditions],
  },
}));
```

Start it with your keys, then click two points along a valley. The trail appears, with its distance, its climb and its profile.

**Terminal**

```text
VITE_MOUNTAYA_PUBLISHABLE_KEY=pk_your_publishable_key MOUNTAYA_SECRET_KEY=sk_your_secret_key npm run dev
```

- The `vite.config.ts` plugin answers `GET /api/mountaya-session` with the session `POST /v1/sessions` returns (`{ token, expires_at, user_id }`), which is what `useSessionToken`'s `mint` resolves with. Vite hands a page only `VITE_` variables, so the secret key stays in the dev server. A built app has no dev server: serve the same route from your backend ([Authentication](https://docs.mountaya.com/en/authentication.md) has handlers for Next.js, Express and FastAPI).

## Next steps

- [Routing](https://docs.mountaya.com/en/apis/data/routing.md): Loops, isochrones and travel-time matrices.
- [Elevation profile](https://docs.mountaya.com/en/sdks/typescript/elevation-profile.md): Axes, sections and a synced map.
