# Build your own app

The app is your web page: in the Packlets look, with packlets.js, sign-in by session token and notifications under the bell.

An app is a web page you build yourself. Packlets shows it as a tile in the **Apps** tab and opens it below the app's header, as wide as the screen. You have the full freedom of HTML, and with `packlets.css` your page still looks like Packlets.

## Channel or app

| | [Channel](https://packlets.app/en/docs/senden.md) | App |
|---|---|---|
| How it works | Your tool sends messages, Packlets lists them one below the other. | The whole app is your web page. |
| You need | just HTTP calls | a server that serves the page over `https://` |
| Good for | Alerts: a server goes down, a deploy fails, an order comes in | Working with lists and data: approving invoices, viewing orders, answering tickets |
| Look | always like Packlets | like Packlets with `packlets.css`, otherwise free |
| Interaction arrives as | [webhook event](https://packlets.app/en/docs/ereignisse.md) | a normal request from your page to your server |

Start with a channel if your tool mainly needs to report things. Buttons, toggles, charts and tables work there too, as [elements in messages](https://packlets.app/en/docs/nachrichten-elemente.md). An app is worth it when you want to check or work through something again and again.

Ideas for what an app can be:

- **Approve invoices:** Every open invoice as a card. Swipe right to approve, left to reject.
- **Servers and deploys:** Status of your services, latest deploys, buttons for restart and rollback.
- **Approvals:** Look at pull requests or expenses and approve them with a tap.
- **Support inbox:** Read new requests and reply briefly.
- **Orders:** Today's orders from your small shop, open and shipped.

If you know Shopify: It's the same principle as embedded Shopify apps with App Bridge and session tokens.

**You need:** a server with an `https` address that serves your page.

## 1. Build the page

A normal HTML page. Two files from Packlets turn it into an app: `packlets.css` for the look and `packlets.js` for the connection to the app.

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://packlets.app/embed/packlets.css">
    <script src="https://packlets.app/embed/packlets.js"></script>
  </head>
  <body>
    <main class="packlets">
      <div class="packlets-row packlets-spread">
        <div>
          <p class="packlets-label" id="firma">Invoice</p>
          <p class="packlets-big" id="betrag">–</p>
          <p class="packlets-sub" id="info"></p>
        </div>
        <span class="packlets-chip" id="offen"></span>
      </div>
      <div class="packlets-row">
        <button class="packlets-button is-secondary packlets-grow" onclick="entscheide('ablehnen')">Reject</button>
        <button class="packlets-button packlets-grow" onclick="entscheide('freigeben')">Approve</button>
      </div>
    </main>
    <script>
      let rechnung;
      async function naechste() {
        const res = await packlets.fetch("/api/rechnungen/naechste");
        rechnung = await res.json();
        document.getElementById("firma").textContent = rechnung.firma;
        document.getElementById("betrag").textContent = rechnung.betrag;
        document.getElementById("info").textContent = `Due ${rechnung.faellig} · ${rechnung.nummer}`;
        document.getElementById("offen").textContent = `${rechnung.offen} open`;
      }
      async function entscheide(aktion) {
        const res = await packlets.fetch(`/api/rechnungen/${rechnung.id}/${aktion}`, { method: "POST" });
        if (!res.ok) return packlets.toast("That didn't work");
        packlets.haptic("success");
        naechste();
      }
      naechste();
    </script>
  </body>
</html>
```

The classes like `packlets-row` and `packlets-button` come from `packlets.css`. They are all listed in the [reference](https://packlets.app/en/docs/api-seiten.md#packlets-css).

## 2. Turn the page into an app

In Packlets, tap the plus at the top left of the **Apps** tab, choose **Your own app** and give it a name. Then your tool sends the address of your page once:

```bash
curl -X PUT https://api.packlets.app/v1/ui \
  -H "Authorization: Bearer $PACKLETS_KEY" \
  -H "Content-Type: application/json" \
  -d '{"page": "https://your-server.example/invoices"}'
```

Response: `{"ok": true, "page": "https://your-server.example/invoices"}`. Packlets shows **Connected!**, and the tile appears in the **Apps** tab.

- `https://` only. The body contains only `page`.
- The first time you open it, Packlets shows the address of your page and asks before loading it. If you later switch to a different address (other host or port), Packlets asks again.
- You set a different address with a new `PUT`.
- Once is enough. What the page shows is up to your server from then on.

## 3. Talk to the app: packlets.js

Through the `packlets` object, your page uses what only the app can do:

| Call | What happens |
|---|---|
| `packlets.toast("Saved")` | Short message in the app. |
| `packlets.haptic("success")` | Vibration. |
| `packlets.open("https://…")` | Opens an address in the browser. |
| `await packlets.fetch(url, init)` | Like `fetch()`, but signed in. See the next step. |
| `packlets.ready()` | The page is ready, Packlets hides the placeholder (with `data-ready="manual"`). |
| `packlets.storage.set("city", "Berlin")` | Stores text on the device, separated by account. |

Packlets keeps opened pages in memory. When someone comes back, your page is there instantly without reloading and receives the event `packlets:activated`. The Packlets colors are available as CSS variables (`--packlets-bg`, `--packlets-text`, `--packlets-cta` …).

In a normal browser the app doesn't exist, and the calls fail. So check `packlets.inPacklets` first if your page should also run there:

```html
<script>
  if (!packlets.inPacklets) document.body.textContent = "Open this page in Packlets.";
</script>
```

All calls are listed in the [reference](https://packlets.app/en/docs/api-seiten.md#packlets-js).

## 4. Know who opens the page

Your page is publicly reachable. If it shows private data, your server has to know that the request really comes from your app in Packlets. You don't need your own login for that: Packlets already knows who is signed in and confirms it to your server with a **session token**.

1. Your page calls `packlets.fetch()`. That gets a fresh token from Packlets and sends it to your server as `Authorization: Bearer …`.
2. Your server checks the token. If it's valid, it knows who is opening the page.

The token is a JWT, valid for 60 seconds and signed with a secret that only you and Packlets know: the SHA-256 hash of your key. It is checked on your server:

```python
import hashlib, os
import jwt  # pip install pyjwt

SECRET = hashlib.sha256(os.environ["PACKLETS_KEY"].encode()).hexdigest()
PACKLET_ID = os.environ["PACKLETS_APP_ID"]

def packlets_user(request):
    token = request.headers.get("Authorization", "").removeprefix("Bearer ")
    claims = jwt.decode(token, SECRET, algorithms=["HS256"], audience=PACKLET_ID)
    return {"id": claims["sub"], "email": claims.get("email"), "name": claims.get("name")}
```

```typescript
import { createHash } from "node:crypto";
import { jwtVerify } from "jose"; // npm install jose

const secret = new TextEncoder().encode(createHash("sha256").update(process.env.PACKLETS_KEY ?? "").digest("hex"));

export async function packletsUser(authorization = "") {
  const token = authorization.replace(/^Bearer /, "");
  const { payload } = await jwtVerify(token, secret, { algorithms: ["HS256"], audience: process.env.PACKLETS_APP_ID });
  return { id: payload.sub, email: payload.email as string | undefined, name: payload.name as string | undefined };
}
```

If the check fails, both functions throw an error. Then respond with `401`.

- **`PACKLETS_APP_ID`** is the ID of your packlet. You get it in the page with `(await packlets.info()).packlet_id`, and it appears in every webhook event as `packlet_id`.
- **No cookie, no session.** `packlets.fetch()` gets a fresh token for every request.
- **Without a JWT library**, your server can also [have Packlets check the token](https://packlets.app/en/docs/api-seiten.md#let-packlets-verify-the-token).

> **Careful:** The key belongs on your server, never in the page. Anything in the HTML or JavaScript can be read by anyone.

## 5. iframes and third-party content

Your page itself is not an iframe: Packlets shows it in its own browser inside the app. You should still take care of two things.

**Third-party content in your page.** If you embed an iframe from another address (video, map, widget), it can't use `packlets`. When loading, Packlets gives the page a secret bridge key that only your page sees, and ignores every call without it. What the iframe does otherwise is up to you:

```html
<iframe src="https://www.youtube-nocookie.com/embed/…"
        sandbox="allow-scripts allow-same-origin"
        referrerpolicy="no-referrer"></iframe>
```

- **`sandbox`**: always set it and allow only what the iframe needs. Without `allow-top-navigation` it can't redirect your page, without `allow-popups` it can't open windows.
- **Third-party scripts** (ads, tracking) running directly in your page have all the rights of your page, including `packlets.fetch()`. Only include scripts you trust.
- **User content**: never insert it as HTML (`innerHTML`), only as text (`textContent`).

**Your page in other sites.** Your address is public. Another website could load it in an iframe and trick users into clicking. It won't get a token there, because Packlets doesn't exist there. Still, forbid embedding with a header from your server:

```http
Content-Security-Policy: frame-ancestors 'none'
X-Frame-Options: DENY
```

This doesn't bother Packlets, because the app doesn't embed your page in an iframe.

## 6. Send notifications

Your app can get in touch even when nobody has it open: the invoice app lets you know when new invoices are waiting, the server dashboard when a service goes down. For that, your **server** sends a message, with the same call as a channel: [`POST /v1/push`](https://packlets.app/en/docs/api-push.md) with the app's key.

```bash
curl https://api.packlets.app/v1/push \
  -H "Authorization: Bearer $PACKLETS_KEY" \
  -H "Content-Type: application/json" \
  -d '{"title": "3 new invoices", "text": "**1,284.50** in total, the first is due on Friday."}'
```

```python
import os, requests

def notify(title: str, text: str, url: str | None = None, priority: str = "normal"):
    r = requests.post(
        "https://api.packlets.app/v1/push",
        headers={"Authorization": f"Bearer {os.environ['PACKLETS_KEY']}"},
        json={"title": title, "text": text, "url": url, "priority": priority},
        timeout=10,
    )
    r.raise_for_status()
    return r.json()["message_id"]
```

The response is `{"message_id": "…"}`, like for any message. Then three things happen in Packlets:

1. **Push to your phone.** The push shows the app's name, plus `title` and the start of `text`. Tap it and the app opens. The push also arrives when the app is currently open.
2. **Counter on the tile.** In the **Apps** tab, the tile shows how many notifications are unread. When you open the app, they all count as read.
3. **History under the bell.** At the top right of every app there's a bell. It shows all of the app's notifications, newest on top, ten at a time and more as you scroll. The history is also stored on the phone, so it's there instantly and shows the latest state without a connection. Next to the bell, a button reloads your page.

### What appears under the bell

| Field | Under the bell |
|---|---|
| `title` | Bold as a heading. Without `title`, it says "Notification". |
| `text` | With [formatting](https://packlets.app/en/docs/senden.md#formatting). Long texts are shortened and expand when tapped. |
| `url` | Tapping opens the link. The address is shown below. Ideally point to the matching spot in your page. |
| `priority` | As with channels: sound, silent, or push despite quiet hours. See [Push, sound and quiet hours](https://packlets.app/en/docs/push.md). |
| `image`, `buttons`, `elements` | Accepted but not shown. Leave them out: interaction belongs in your page. |

### Tips

- **Short and concrete.** A notification says *that* something is waiting. The work itself happens in your page.
- **Refresh the page.** If someone enters the app through the push, the page may still have been in memory. Reload your data as soon as the `packlets:activated` event arrives:

```html
<script>
  addEventListener("packlets:activated", () => naechste());
</script>
```

- **Not for every little thing.** The same limits apply as for channels: 60 calls per minute and app. Combine several events into one notification ("3 new invoices").
- **Push, sound and quiet hours** are set by each person in the app's settings. To get there, tap the avatar or name at the top of the app.
- **Without code:** The addresses for [Slack](https://packlets.app/en/docs/slack.md), [Discord](https://packlets.app/en/docs/discord.md) and [ntfy](https://packlets.app/en/docs/ntfy.md) also work with an app's key. That way, for example, alerts from your CI system land under the bell.

## To make it feel like an app

- **White background**, no border of its own and no shadow around it.
- **No header of your own.** Packlets already shows the name and avatar. Put what matters at the top.
- **Tap targets at least 44 pixels** high, text at least 12 pixels.
- **No hover, no pop-ups**, no `alert()`. For messages there's `packlets.toast()`.
- **Links** to your own address stay in the app. Links to other addresses open in the browser.
- **Test** in the browser at phone width, for example 375 pixels in the developer tools.

## Try it out

The two pages above are real apps:

- **Weather** shows how freely you can design. Every new account has it in Packlets under **Apps**.
- **Account** shows the session token: the page gets a fresh token with every request, its server checks it and shows your name. In the browser, the same page only shows a note, because there is no token there.

## Checklist

- Sent the address of the page with `PUT /v1/ui` and `{"page": "https://…"}`.
- Set `<meta name="viewport" content="width=device-width, initial-scale=1">`.
- Included `packlets.css` and `packlets.js`.
- Requests to your server go through `packlets.fetch()`.
- Your server checks signature, expiry and `aud` of the token on every request.
- The key lives only on the server.
- Third-party iframes with `sandbox`, your page served with `frame-ancestors 'none'`.
- Your server sends notifications with `POST /v1/push`, short and with a `url` to the matching spot in your page.

## What's next

- All `packlets.js` calls, the token and `packlets.css`: [reference](https://packlets.app/en/docs/api-seiten.md).
- Field, response and errors of `PUT /v1/ui`: [PUT /v1/ui](https://packlets.app/en/docs/api-ui.md).
- All fields of a notification: [POST /v1/push](https://packlets.app/en/docs/api-push.md).
