# Run Mountaya from your backend

> Canonical URL: https://docs.mountaya.com/en/apis/map-studio/server-integration/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Keep your three keys on your server, renew session tokens before they expire, and write as a member of your organization.

Your backend holds the keys, mints the session tokens, and decides which member each write acts as. This page sets that up once, for a server that calls Mountaya on its own and for the pages it serves.

## Keep three keys on your server

| Key | Looks like | Does | Lives |
| --- | --- | --- | --- |
| Publishable key | `pk_…` with product scopes | Names your organization on every call | Your server, or a page |
| Secret key | `sk_…` | Mints session tokens, and nothing else | Your server only |
| Management key | `pk_…` with `management` alone | Administers members, invitations, keys and webhooks | Your server only |

Create all three under **Organization → API keys** in the [Mountaya app](https://app.mountaya.com/api-keys), and read them from the environment:

```bash
export MOUNTAYA_PUBLISHABLE_KEY="pk_your_publishable_key"
export MOUNTAYA_SECRET_KEY="sk_your_secret_key"
export MOUNTAYA_MANAGEMENT_KEY="pk_your_publishable_key"
```

The app shows a secret key once, when you create it. Store it then.

- A publishable key travels in `X-API-Key` on every call and reaches only the products its scopes name: `publishing`, `studio-embedded`, `tiles`, `data`, `mcp`. A Map Studio API write takes `studio-embedded`, which a key carries with `tiles` and `data` beside it.
- A secret key authenticates `POST /v1/sessions` and nothing else: sent to any other operation it is not a credential at all, and the answer is a `401`. Keep it in an environment variable on your server, never in a page, an app bundle or a URL. The TypeScript client refuses it in a browser or a React Native app, and on any operation but `postSession`, before sending.
- The management key is a publishable key carrying `management` alone: a key listing `management` beside another scope is a `400`. A token minted for it without `user_id`, for the default surface, reads the whole account (members, keys, usage, billing, webhooks) with no role asked, so it never leaves your backend. A write under it needs a token naming an owner or admin.
- Secret keys are absent from the API: no operation lists, creates or revokes one. Revoking a secret key stops new session tokens, and tokens already minted stay valid until they expire, at most five minutes. Revoking a publishable key fails every request with it from the next one.
- Every key belongs to one organization, and a key never reaches another organization's private content or listings.

## Renew the session token before it expires

Every write, every Data API call and every management call carries a session token beside the key. A token lasts five minutes, so your server mints a new one before the last one expires. With the TypeScript client, a `SessionTokenEngine` does it for you:

**cURL**

```bash
# Mints one token: mint another before its expires_at.
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\"}"
```

**TypeScript**

```typescript
import { Mountaya, SessionTokenEngine } 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 ?? "" },
});

// Mints a token for the member, and a fresh one before each expires.
const session = new SessionTokenEngine({
  mint: async () => {
    const { data } = await new MountayaAdmin(server).sessions.postSession({
      body: {
        publishable_key: publishableKey,
        surface: "studio-embedded",
        user_id: "7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1",
      },
    });
    return data;
  },
});
// The engine renews while something subscribes: hold it for the process's life.
session.subscribe(() => undefined);

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

const { data: itineraries } = await mountaya.studio.itineraries.getItineraries({
  query: { limit: 5 },
});
console.log(itineraries.map((itinerary) => itinerary.name));
```

**Python**

```python
import os
from datetime import datetime, timedelta, timezone

import requests

_session = {"token": "", "expires_at": datetime.min.replace(tzinfo=timezone.utc)}


def session_token() -> str:
    """Answers a session token, minting a new one a minute before the last expires."""
    if datetime.now(timezone.utc) > _session["expires_at"] - timedelta(minutes=1):
        minted = 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"]
        _session["token"] = minted["token"]
        _session["expires_at"] = datetime.fromisoformat(minted["expires_at"].replace("Z", "+00:00"))
    return _session["token"]


itineraries = requests.get(
    "https://api.mountaya.com/v1/itineraries",
    headers={
        "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
        "X-Session-Token": session_token(),
    },
    params={"limit": 5},
    timeout=30,
).json()["data"]
print([itinerary["name"] for itinerary in itineraries])
```

**Response to the mint**

```json
{
  "data": {
    "expires_at": "2026-11-19T10:05:00Z",
    "token": "sess_your_session_token",
    "user_id": "7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1"
  }
}
```

> **Renew on the clock, not on a 401**
>
> A token that expires mid-flight fails one request of a burst while its neighbours succeed. Read `expires_at`, and mint again before it passes.

- `POST /v1/sessions` takes the secret key in `X-API-Key` and the body `{ publishable_key, user_id?, surface? }`, and answers `{ token, expires_at, user_id }`. There is no refresh operation: mint a new token. A token minted moments earlier for the same key, surface and user may be returned again with less time left, so read `expires_at` rather than assume five minutes.
- `SessionTokenEngine` (`@mountaya/client`) mints through its `mint`, refreshes a margin before `expires_at`, tries a failed mint again a minute later, and abandons a mint that has not answered within a minute. It mints nothing until something subscribes. A request made while its first mint is out waits for the token. Call `dispose()` when a script ends, or release the subscription; never build one client per token.
- Never renew in reaction to a `401`, and never read a token once from an environment variable in a long-running process: it expires five minutes after it was minted.
- `surface: "studio-embedded"` is required for every Map Studio API write and every `studio-embedded` operation, which answer a token minted for any other surface `401`. For your own Data API and Tile API calls, mint a token for the default surface (`api`), which counts toward your organization's limits and invoice. A `studio-embedded` token's Data API and Tile API requests are recorded apart, for the Embedded Studio.
- Minting is limited per client IP address, per secret key and per `user_id` on failures, and to 6,000 tokens a minute per secret key: see [session minting](https://docs.mountaya.com/en/apis/conventions/rate-limits.md#session-minting).
- For a browser, serve the token from a route of your own instead, as [authentication](https://docs.mountaya.com/en/authentication.md#session-tokens) shows. Never mint a member's token on a route that does not sign the person in.

## Act as a member

A write acts as the member its token names, within their role. Mint each person's token with their Mountaya `user_id`, read from your own sign-in and never from the request.

People become members by invitation: an owner or admin invites their email address, and they accept in the Mountaya app. Each member, and each invitation still waiting, holds one of your agreement's seats. [Manage members, invitations and keys](https://docs.mountaya.com/en/apis/map-studio/members-and-keys.md) shows each call, and how to look up a member's `user_id`.

- `user_id` must be a member of the key's organization, in any role, or hold an invitation to it that is still pending, matched by an address the person's account has verified. Any other answers `403` and mints nothing.
- A write needs a role that writes: owner, admin or contributor. A viewer's token reads, and is refused a write with `403`. A token minted without `user_id` reads only what you publish and writes nothing (`401` on every operation that acts as a member).
- No header names a user: the token is the whole statement of who acts. A token names one member for its whole life, so mint a new one when the person changes.
- A member removed since a token was minted acts as nobody from the next request.
- Every write records the member it acted as, at `created_by` on what it creates.

## Write with a member of its own

Writes no person makes, such as a nightly import from your catalog, act best as a member kept for them. Invite an address you control, such as `integrations@example.com`, as a `contributor`. Sign up with it in the Mountaya app, accept the invitation, and store its `user_id`.

What it writes then names that member, apart from your people. Removing a person never stops your import, and removing it never touches anyone's access.

- The integration member is a member like any other: it holds a seat, and a contributor writes content but administers nothing. Mint its tokens with `surface: "studio-embedded"` for content writes.
- Administration (members, keys, webhooks) acts as an owner or admin, through the management key: mint that token for an owner or admin, never for the integration member.
- Removing a member leaves what they created with the organization.

## Serve your own customers

Your organization holds every key, itinerary, zone, collection and webhook endpoint, and your keys write to it alone. Your own customers are not Mountaya organizations: serve them from yours. Give each person who edits a member of their own, and keep which customer owns what in your own records.

- An organization is the tenant everything belongs to: keys, itineraries, zones, collections, webhook endpoints, invoices. Listings cover the key's organization only, and naming another organization is a `403`.
- An organization created through `POST /v1/organizations` is not reachable with the key that created it, holds no product until its own card or agreement, and no operation issues a key into it: its keys are created in the Mountaya app. So a separate organization per customer means a separate agreement and keys per customer.
- A person may belong to several organizations, each membership with its own role. A token names one user, and a key one organization, so the pair decides where a call lands.

## Next steps

- [Manage members and keys](https://docs.mountaya.com/en/apis/map-studio/members-and-keys.md): Invite people, find their user ids, rotate keys.
- [Authentication](https://docs.mountaya.com/en/authentication.md): Serve tokens to a browser.
- [Go to production](https://docs.mountaya.com/en/production.md): The launch checklist.
