# Embedded pages

Source: https://snizu.dev/docs/apps/embedded-pages

## Install it [#install-it]

```sh title="Terminal"
npm i @snizu/app-bridge
```

The admin opens your manifest's `admin_url` in a frame under Apps, and adds three launch parameters to its address: `store_id`, `host` (the admin's origin, the only one your page should talk to) and `locale`. Connect once when the page loads:

```ts title="admin.ts"
import { createAppBridge } from "@snizu/app-bridge";

const bridge = createAppBridge();

const { storeId, locale, direction, theme } = await bridge.context;
document.documentElement.lang = locale;
document.documentElement.dir = direction;

// A token for your backend, before every request. Cached until shortly before it expires.
const response = await fetch("/api/orders", {
  headers: { authorization: `Bearer ${await bridge.getSessionToken()}` },
});

bridge.toast("Saved");
bridge.toast("Couldn't reach the carrier", { tone: "error" });
bridge.navigate("/orders/ord_01k9c3m7x2v5q8n4t0d6b1w9hz");
```

## createAppBridge(options?) [#createappbridgeoptions]

<Fields>
<Field name="hostOrigin" type="string">
The admin's origin. The `host` launch parameter by default.
</Field>

<Field name="timeoutMs" type="number">
How long to wait for the admin to answer. 10 seconds by default.
</Field>
</Fields>

## The bridge [#the-bridge]

<Fields>
<Field name="context" type="Promise">
Where the app runs: `storeId`, `locale`, `direction` (`ltr` or `rtl`), `theme` (`light` or `dark`) and the protocol's `version`.
</Field>

<Field name="getSessionToken()" type="Promise<string>">
A token for your backend. Call it before every request.
</Field>

<Field name="toast(message, { tone })">
A toast in the admin. `tone` is `info`, the default, or `error`.
</Field>

<Field name="navigate(path)">
Moves the admin to a path inside this store's admin, like `/orders`. Anything else is refused.
</Field>

<Field name="destroy()">
Stops listening to the admin.
</Field>
</Fields>

## Verify the session token [#verify-the-session-token]

Your page runs in a browser, so trust your backend's check of the token, never the page. The token is an HS256 JWT signed with your app's client secret, valid for 60 seconds:

<Fields>
<Field name="typ" type="session">
An admin session token. A checkout block's token never passes as one.
</Field>

<Field name="aud" type="string">
Your app's client ID.
</Field>

<Field name="dest" type="store_…">
The store the page is open in.
</Field>

<Field name="sub" type="string">
The staff member using it.
</Field>

<Field name="iss" type="url">
The store's Admin API address.
</Field>

<Field name="nbf, exp, iat" type="seconds">
When it starts and stops being valid, and when it was made.
</Field>

<Field name="jti" type="string">
Unique to each token, so you can refuse one used twice.
</Field>
</Fields>

```js title="lib/verify.js"
import { createHmac, timingSafeEqual } from "node:crypto";

function same(left, right) {
  const a = Buffer.from(left);
  const b = Buffer.from(right);
  return a.length === b.length && timingSafeEqual(a, b);
}

function verifyToken(token, key, clientId, type, now) {
  const [header, claims, signature] = String(token ?? "").split(".");
  if (!header || !claims || !signature) return null;
  const expected = createHmac("sha256", key).update(`${header}.${claims}`).digest("base64url");
  if (!same(expected, signature)) return null;
  let decoded;
  try {
    decoded = JSON.parse(Buffer.from(claims, "base64url").toString("utf8"));
  } catch {
    return null;
  }
  const inTime = decoded.nbf - 5 <= now && now <= decoded.exp + 5;
  return inTime && decoded.aud === clientId && decoded.typ === type ? decoded : null;
}

export function verifySessionToken(token, secret, clientId, now = Date.now() / 1000) {
  return verifyToken(token, secret, clientId, "session", now);
}
```

It allows five seconds of difference between your clock and ours, either way.

[`snizu app create`](/docs/cli/app/create) writes an app whose `lib/verify.js` does this, with tests, and a `GET /api/me` route that uses it.

## The frame [#the-frame]

The page runs on your own origin, in a sandboxed frame that may run scripts, submit forms, open popups and downloads, show dialogs and write to the clipboard. It can't navigate the admin itself: ask with `navigate`.

The protocol's own pieces, `isAppMessage`, `isHostMessage`, `isAdminPath`, `LAUNCH_PARAMS` and `BRIDGE_VERSION`, are exported too, for testing a page outside the admin.