Get started
Get started

Authentication in the SDK

Authentication in the SDK

The publishable key goes in every client. A session token goes beside it for the Data API, for drafts, and for every write. Your server mints the token with the secret key, and the client keeps it fresh.

Mint on your server

Add one route that calls postSession with your secret key:

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

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

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

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

That is a Next.js route handler. Authentication has the same route for Express and FastAPI.

Keep the token fresh in the browser

Give the client a SessionTokenEngine. It calls your route, and mints again before each token expires:

import { Mountaya, SessionTokenEngine } from "@mountaya/client/browser";

const session = new SessionTokenEngine({
  mint: async () => {
    const response = await fetch("/api/mountaya-session");
    if (!response.ok) {
      throw new Error(`The session endpoint answered ${response.status}.`);
    }
    return response.json();
  },
});
// The engine refreshes while something subscribes to it: hold it for the page's life.
session.subscribe(() => undefined);

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

One client serves the whole page. Each request, and each map tile, carries the current token.

In React

useSessionToken holds the engine for you. Build the client once over its session:

import { type ReactNode, useState } from "react";
import { Mountaya } from "@mountaya/client/browser";
import { MountayaProvider, useSessionToken } from "@mountaya/client-react";

const mintSession = async () => {
  const response = await fetch("/api/mountaya-session");
  if (!response.ok) {
    throw new Error(`The session endpoint answered ${response.status}.`);
  }
  return response.json();
};

export const Session = ({ children }: { children: ReactNode }) => {
  const { session } = useSessionToken({ mint: mintSession });
  const [mountaya] = useState(
    () =>
      new Mountaya({
        credential: { publishableKey: "pk_your_publishable_key", sessionToken: session },
      }),
  );

  return <MountayaProvider client={mountaya}>{children}</MountayaProvider>;
};

Mount it inside your QueryClientProvider. Pass enabled: false while nobody is signed in.

Act as a member

A token minted without user_id reads only what your organization publishes, and writes nothing. To read drafts and write, mint the token for the member your own sign-in vouches for:

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

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

export async function mintFor(userId: string) {
  const { data } = await server.admin.sessions.postSession({
    body: { publishable_key: process.env.MOUNTAYA_PUBLISHABLE_KEY ?? "", user_id: userId },
  });
  return data;
}

Read userId from your server's session, never from the request. Every call made with the token acts as that member.

Embedded Studio tokens

The Embedded Studio takes only tokens minted for it. Add surface: "studio-embedded" to the mint:

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

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

export async function mintStudioToken(userId: string) {
  const { data } = await server.admin.sessions.postSession({
    body: {
      publishable_key: process.env.MOUNTAYA_PUBLISHABLE_KEY ?? "",
      surface: "studio-embedded",
      user_id: userId,
    },
  });
  return data;
}

The studio quickstart wires it end to end.

Keep the secret key out of the browser

In every bundle that reaches a browser, import the client from @mountaya/client/browser. It has no secret-key credential, so passing one is a type error.

Next steps

Last updated