# Build a race course page

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

Publish a course with its aid stations, services and cut-offs through the Map Studio API, then show it with a map, a profile and a filterable table.

A course page runners can read at a glance: the route on a map, its elevation profile, and a table of aid stations with their services and cut-off times.

![A course on a map above its table of aid stations](https://docs.mountaya.com/examples/tutorial-race-course.webp)

You set the course up with the Map Studio API, then draw it with the TypeScript SDK. You need:

- a publishable key with the `studio-embedded`, `publishing` and `tiles` scopes, and your secret key;
- the id of a member of your organization, who the writes act as;
- for the page, a Vite and React app. To start one:

```bash
npx create-vite@latest course-page --template react-ts && cd course-page && \
  npm install @mountaya/client @mountaya/elements @mountaya/elements-react maplibre-gl@6.18.0
```

Map Studio and the Tile API come with an agreement.

**1. Mint a session token for a member**

Writes act as one of your members, so your server mints a session token that names them.

**cURL**

```bash
export MOUNTAYA_MEMBER_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\", \"user_id\": \"7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1\", \"surface\": \"studio-embedded\"}" \
  | 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 ?? "" },
});
const { data: session } = await new MountayaAdmin(server).sessions.postSession({
  body: {
    publishable_key: publishableKey,
    surface: "studio-embedded",
    user_id: "7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1",
  },
});

const mountaya = new Mountaya({ credential: { publishableKey, sessionToken: session.token } });
```

**Python**

```python
import os
import uuid

import requests

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"],
        "user_id": "7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1",
        "surface": "studio-embedded",
    },
    timeout=10,
).json()["data"]
```

**Response**

```json
{
  "data": {
    "expires_at": "2026-11-09T13:28:33.925081Z",
    "token": "sess_your_session_token",
    "user_id": "7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1"
  }
}
```

- Mint on your server only: the secret key never reaches a browser. `user_id` must name a member of the key's organization with a write role; `surface: "studio-embedded"` is the surface the Map Studio API's writes take.
- The token lasts five minutes (`expires_at`). Mint a fresh one before `expires_at` passes, never in reaction to a `401`; a `401` on a write usually means it passed.
- Every write below takes an `Idempotency-Key` header. The TypeScript client sends one by itself and reuses it on retries; send your own with cURL and Python.

**2. Create the course**

Import the route and its aid stations in one call. Already have your course in Mountaya? Skip this step and use its id.

**cURL**

```bash
ACTIVITY_ID=$(curl -s https://api.mountaya.com/v1/activities \
  -H "X-API-Key: $MOUNTAYA_PUBLISHABLE_KEY" \
  | jq -r '.data[].children[] | select(.slug == "running") | .id')

COURSE=$(curl -s -X POST https://api.mountaya.com/v1/itineraries/import \
  -H "X-API-Key: $MOUNTAYA_PUBLISHABLE_KEY" \
  -H "X-Session-Token: $MOUNTAYA_MEMBER_TOKEN" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d @- <<JSON
{
  "name": "Docs Vallée Trail",
  "activity_id": "$ACTIVITY_ID",
  "is_private": false,
  "segments": [{
    "name": "Les Houches to Argentière",
    "mode": "directions",
    "geojson": {"type": "MultiPoint", "coordinates": [[6.7991, 45.8915], [6.8712, 45.9231], [6.9271, 45.9822]]}
  }],
  "waypoints": [
    {"mode": "poi", "name": "Chamonix", "icon": "droplet", "geojson": {"type": "Point", "coordinates": [6.8712, 45.9231]}},
    {"mode": "poi", "name": "Argentière", "icon": "flag", "geojson": {"type": "Point", "coordinates": [6.9271, 45.9822]}}
  ]
}
JSON
)

ITINERARY_ID=$(echo "$COURSE" | jq -r .data.id)
echo "$COURSE" | jq '.data | {id, name, distance, ascent, waypoints: [.waypoints[] | {id, name}]}'
```

**TypeScript**

```typescript
const { data: activities } = await mountaya.studio.activities.getActivities();
const running = activities
  .flatMap((category) => category.children)
  .find((activity) => activity.slug === "running");

const { data: course } = await mountaya.studio.itineraries.postItineraryImport({
  body: {
    name: "Docs Vallée Trail",
    activity_id: running?.id ?? "",
    is_private: false,
    segments: [
      {
        name: "Les Houches to Argentière",
        mode: "directions",
        geojson: {
          type: "MultiPoint",
          coordinates: [
            [6.7991, 45.8915],
            [6.8712, 45.9231],
            [6.9271, 45.9822],
          ],
        },
      },
    ],
    waypoints: [
      {
        mode: "poi",
        name: "Chamonix",
        icon: "droplet",
        geojson: { type: "Point", coordinates: [6.8712, 45.9231] },
      },
      {
        mode: "poi",
        name: "Argentière",
        icon: "flag",
        geojson: { type: "Point", coordinates: [6.9271, 45.9822] },
      },
    ],
  },
});

const itineraryId = course.id;
console.log(course.name, course.distance, course.waypoints.map((waypoint) => waypoint.name));
```

**Python**

```python
activities = requests.get(
    "https://api.mountaya.com/v1/activities",
    headers={"X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"]},
    timeout=10,
).json()["data"]
running_id = next(
    activity["id"]
    for category in activities
    for activity in category["children"]
    if activity["slug"] == "running"
)

course = requests.post(
    "https://api.mountaya.com/v1/itineraries/import",
    headers={
        "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
        "X-Session-Token": session["token"],
        "Idempotency-Key": str(uuid.uuid4()),
    },
    json={
        "name": "Docs Vallée Trail",
        "activity_id": running_id,
        "is_private": False,
        "segments": [
            {
                "name": "Les Houches to Argentière",
                "mode": "directions",
                "geojson": {
                    "type": "MultiPoint",
                    "coordinates": [[6.7991, 45.8915], [6.8712, 45.9231], [6.9271, 45.9822]],
                },
            }
        ],
        "waypoints": [
            {"mode": "poi", "name": "Chamonix", "icon": "droplet",
             "geojson": {"type": "Point", "coordinates": [6.8712, 45.9231]}},
            {"mode": "poi", "name": "Argentière", "icon": "flag",
             "geojson": {"type": "Point", "coordinates": [6.9271, 45.9822]}},
        ],
    },
    timeout=60,
).json()["data"]

itinerary_id = course["id"]
print(course["name"], course["distance"], [waypoint["name"] for waypoint in course["waypoints"]])
```

**Response (abridged)**

```json
{
  "id": "aa75b75f-db36-4554-a13a-15e33b19aa9e",
  "name": "Docs Vallée Trail",
  "distance": 17060.58,
  "ascent": 360,
  "waypoints": [
    {
      "id": "a142860b-7c91-4c27-9389-c12aa0cfec2e",
      "name": "Chamonix"
    },
    {
      "id": "bc1f1b0b-0196-4a13-9109-a22c082a3519",
      "name": "Argentière"
    }
  ]
}
```

The route is routed through the three points you sent, so `distance` and `ascent` are the real trail figures.

- `POST /v1/itineraries/import` creates the itinerary, its segments and its waypoints together or not at all, and answers `201 Created` with the whole draft. It needs Map Studio, the `studio-embedded` scope and a member's session token with a write role.
- `name` is 2 to 30 characters and unique in the organization (`409` on a duplicate). `activity_id` is required: read it from `GET /v1/activities` by slug.
- A `directions` segment takes a `MultiPoint` of 2 to 45 points, routed for the activity; a `linestring` segment takes a `LineString` drawn as given.
- A waypoint with `mode: "poi"` needs a `name` and an `icon` (`droplet`, `flag`, `hut`, `medical-cross`, …; `flag-start` and `flag-end` are refused). Import takes no services or timing: set them with a waypoint `PATCH`, as in the next step.
- To import a GPX file instead, preview it first: [Import a GPX catalog](https://docs.mountaya.com/en/apis/map-studio/gpx-import.md).

**3. Add services and a cut-off**

Give the Chamonix aid station its services and the time runners must leave it by.

**cURL**

```bash
WAYPOINT_ID=$(echo "$COURSE" | jq -r '.data.waypoints[] | select(.name == "Chamonix") | .id')

curl -s -X PATCH "https://api.mountaya.com/v1/itineraries/$ITINERARY_ID/waypoints/$WAYPOINT_ID" \
  -H "X-API-Key: $MOUNTAYA_PUBLISHABLE_KEY" \
  -H "X-Session-Token: $MOUNTAYA_MEMBER_TOKEN" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{"amenities": ["water", "food", "first-aid"], "timing": {"cutoff_at": "2026-08-29T09:30:00Z", "stop_duration": 300}}' \
  | jq '.data.waypoints[] | select(.name == "Chamonix") | {name, amenities, timing}'
```

**TypeScript**

```typescript
const { data: draft } = await mountaya.studio.itineraries.getItinerary({
  itinerary_id: itineraryId,
});
const chamonix = draft.waypoints.find((waypoint) => waypoint.name === "Chamonix");
if (chamonix === undefined) {
  throw new Error("The course has no Chamonix aid station.");
}

const { data: updated } = await mountaya.studio.itineraries.patchItineraryWaypoint({
  itinerary_id: itineraryId,
  waypoint_id: chamonix.id,
  body: {
    amenities: ["water", "food", "first-aid"],
    timing: { cutoff_at: new Date("2026-08-29T09:30:00Z"), stop_duration: 300 },
  },
});

console.log(updated.waypoints.find((waypoint) => waypoint.id === chamonix.id)?.timing);
```

**Python**

```python
chamonix = next(waypoint for waypoint in course["waypoints"] if waypoint["name"] == "Chamonix")

updated = requests.patch(
    f"https://api.mountaya.com/v1/itineraries/{itinerary_id}/waypoints/{chamonix['id']}",
    headers={
        "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
        "X-Session-Token": session["token"],
        "Idempotency-Key": str(uuid.uuid4()),
    },
    json={
        "amenities": ["water", "food", "first-aid"],
        "timing": {"cutoff_at": "2026-08-29T09:30:00Z", "stop_duration": 300},
    },
    timeout=30,
).json()["data"]

print(next(waypoint for waypoint in updated["waypoints"] if waypoint["id"] == chamonix["id"])["timing"])
```

**Response (abridged)**

```json
{
  "name": "Chamonix",
  "amenities": [
    "water",
    "food",
    "first-aid"
  ],
  "timing": {
    "cutoff_at": "2026-08-29T09:30:00Z",
    "stop_duration": 300
  }
}
```

`cutoff_at` is an absolute instant, so the page decides which time zone to print it in.

- `PATCH /v1/itineraries/{itinerary_id}/waypoints/{waypoint_id}` answers `200` with the whole itinerary. Each member you send replaces the stored one wholesale; a member you omit is kept; `null` clears it.
- `amenities` is a list of unique values from a fixed vocabulary: `water`, `drinks`, `food`, `hot-meal`, `snacks`, `medical`, `first-aid`, `toilets`, `showers`, `drop-bag`, `luggage-storage`, `assistance`, `rest-area`, `accommodation`, `shelter`, `camping`, `picnic`, `shop`, `parking`, `shuttle`, `public-transport`, `cable-car`, `power-charging`, `wifi`, `mobile-signal`, `waste`, `pet-friendly`, `wheelchair-access`, `viewpoint`, `timing-checkpoint`.
- `timing.cutoff_at` is an RFC 3339 instant (the TypeScript client takes a `Date`); `timing.stop_duration` is seconds, at most 2,592,000. An object whose members are all null clears the timing.
- Send `If-Match` with the itinerary's `etag` to refuse the write when someone else changed the course since you read it (`412`).

**4. Publish the course**

Runners read the published version, so publish once the course is ready.

**cURL**

```bash
curl -s -X POST "https://api.mountaya.com/v1/itineraries/$ITINERARY_ID/publication" \
  -H "X-API-Key: $MOUNTAYA_PUBLISHABLE_KEY" \
  -H "X-Session-Token: $MOUNTAYA_MEMBER_TOKEN" \
  -H "Idempotency-Key: $(uuidgen)" \
  | jq '.data | {id, name, published_at, has_unpublished_changes}'
```

**TypeScript**

```typescript
const { data: published } = await mountaya.studio.itineraries.postItineraryPublication({
  itinerary_id: itineraryId,
});

console.log(published.id, published.published_at);
```

**Python**

```python
published = requests.post(
    f"https://api.mountaya.com/v1/itineraries/{itinerary_id}/publication",
    headers={
        "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
        "X-Session-Token": session["token"],
        "Idempotency-Key": str(uuid.uuid4()),
    },
    timeout=30,
).json()["data"]

print(published["id"], published["published_at"])
```

**Response (abridged)**

```json
{
  "id": "aa75b75f-db36-4554-a13a-15e33b19aa9e",
  "name": "Docs Vallée Trail",
  "published_at": "2026-11-09T13:26:19.12665Z",
  "has_unpublished_changes": false
}
```

- `POST /v1/itineraries/{itinerary_id}/publication` copies the draft into the published snapshot that a publishable key alone reads, and answers the itinerary with `published_at` set. Publish again after each change; until then, `has_unpublished_changes` is `true` and runners see the previous version.
- The published snapshot's segment ids differ from the draft's and change at every publish.
- `DELETE /v1/itineraries/{itinerary_id}/publication` takes the course down; a key alone then reads `404`.

**5. Build the page**

The page needs only the publishable key and the course id. The map, the profile and the table share one provider, so hovering one moves the others.

**src/main.tsx**

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

const client = new Mountaya({
  credential: { publishableKey: import.meta.env.VITE_MOUNTAYA_PUBLISHABLE_KEY },
});

// The course you published.
const COURSE_ID = import.meta.env.VITE_MOUNTAYA_COURSE_ID;

// Cut-offs in the race's own time zone, whatever the runner's.
const cutoffTime = new Intl.DateTimeFormat("en-GB", {
  hour: "2-digit",
  minute: "2-digit",
  timeZone: "Europe/Paris",
  weekday: "short",
});
const formatCutoffAt = (instant: Date) => cutoffTime.format(instant);

const CoursePage = () => {
  const [map, setMap] = useState<MountayaMap | null>(null);
  const [filter, setFilter] = useState<readonly string[]>([]);

  return (
    <MountayaElementsProvider client={client} map={map}>
      <div style={{ height: 420 }}>
        <MapView
          client={client}
          onReady={(ready) => {
            setMap(ready);
            void ready.setItinerary(COURSE_ID, { fit: true });
          }}
          terrain="topo"
        >
          <MapControls preferences={false} />
        </MapView>
      </div>
      <ItineraryProfile
        axis
        formatCutoffAt={formatCutoffAt}
        itineraryId={COURSE_ID}
        sections
        surface="published"
        tooltip
      />
      <ItineraryWaypointTable
        columns={["waypoint", "distance", "elevation", "amenities", "cutoff"]}
        filter={filter}
        formatCutoffAt={formatCutoffAt}
        itineraryId={COURSE_ID}
        onFilterChange={setFilter}
        surface="published"
      />
    </MountayaElementsProvider>
  );
};

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

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

It replaces the `src/main.tsx` Vite wrote. Start it with your key and the course id:

**Terminal**

```text
VITE_MOUNTAYA_PUBLISHABLE_KEY=pk_your_publishable_key VITE_MOUNTAYA_COURSE_ID=0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21 npm run dev
```

Pick a service above the table to keep only the aid stations that offer it.

- The page reads the published snapshot with the publishable key alone (`publishing` for the itinerary, `tiles` for the map); it holds no secret and no session token. `surface="published"` makes the profile and the table read the snapshot even under a member's token.
- One `MountayaElementsProvider` holding the map links the three: hovering the profile places a marker on the map, and the table and the map emphasise the same place.
- `formatCutoffAt` receives the instant as a `Date`; give it the race's `timeZone`, or each runner reads cut-offs in their own zone. Without it, cut-offs read as elapsed time.
- `filter` holds the selected amenity keys; the table shows the waypoints offering every selected service.
- The same components are documented in the [tables](https://docs.mountaya.com/en/sdks/typescript/tables.md#filter) and [elevation profile](https://docs.mountaya.com/en/sdks/typescript/elevation-profile.md) guides.

## Next steps

- [Tables](https://docs.mountaya.com/en/sdks/typescript/tables.md): Columns, units and row hooks.
- [Publishing](https://docs.mountaya.com/en/apis/map-studio/publishing.md): Drafts, snapshots and taking a course down.
