Place search
SearchControl searches places, huts and itineraries as a reader types, then moves the map onto the result. It calls the Data API, so the client carries a session token your server mints.
src/SearchMap.tsx
/// <reference types="vite/client" />
import { Mountaya } from "@mountaya/client/browser";
import { useSessionToken } from "@mountaya/client-react";
import { MapControls, MapView, SearchControl } from "@mountaya/elements-react";
import "@mountaya/elements-react/styles.css";
import { useState } from "react";
// Your server route that mints a session token with the secret key.
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();
};
export const SearchMap = () => {
const { session } = useSessionToken({ mint });
const [client] = useState(
() =>
new Mountaya({
credential: {
publishableKey: import.meta.env.VITE_MOUNTAYA_PUBLISHABLE_KEY,
sessionToken: session,
},
}),
);
return (
<div style={{ height: 420 }}>
<MapView center={[6.8712, 45.9231]} client={client} terrain="topo" zoom={12}>
<MapControls position="top-left" zoom>
<SearchControl />
</MapControls>
</MapView>
</div>
);
};useSessionToken comes from @mountaya/client-react, installed with its peer @tanstack/react-query. It renews the token before it expires.
In development, Vite's dev server can answer /api/mountaya-session with your secret key, as this vite.config.ts does. Drop its resolve.conditions, which serve the SDK's own example.
From examples/elements-react-map/vite.config.ts
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 mint names no user, so the token 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.
import("@mountaya/client")
.then(({ Mountaya }) =>
new Mountaya({ credential: { secretKey } }).admin.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],
},
}));