SDKs
Web
@sapagan/web adds browser push to a web app.
@sapagan/web gives a web app browser notifications from Sapagan, even with the tab closed. Transactional messages with web_push in channels, and journeys, reach them. Version 0.3.0.
It has two parts:
sapagan-sw.js, the service worker. It shows Sapagan's pushes, reportsdeliveredwhen one arrives andopenedonce when it is clicked.createSapagan(...), the page side. It registers the worker, asks for permission only from a click, and registers the browser as a device with platformwebthroughPOST /v1/batch.
The package has no Firebase code. Web push goes through FCM in your own Firebase project, with the same service account you give Sapagan for apps.
What you need from Firebase#
- In the Firebase console, add a Web app under Project settings, General. Keep its config.
- Under Project settings, Cloud Messaging, "Web Push certificates", generate a key pair and copy the public key. This is the VAPID key.
- Upload the project's service account to the workspace. See FCM and APNs credentials.
Wire it into the page#
1. Serve the worker from your origin. Copy node_modules/@sapagan/web/sw/sapagan-sw.js to public/sapagan-sw.js, so it is served at /sapagan-sw.js. Do not bundle it. A worker controls only pages under its own path, so it must sit at the site root.
If the app already has a service worker, do not register a second one at the same scope. Put these lines at the top of the existing worker and pass its URL as serviceWorkerUrl:
self.SAPAGAN_CONFIG = { key: "<app key>", baseUrl: "<api base>", icon: "/icons/notification-192.png" };
importScripts("/sapagan-sw.js");2. Create one client, in the browser only.
"use client";
import { initializeApp } from "firebase/app";
import { deleteToken, getMessaging, getToken, isSupported } from "firebase/messaging";
import { createSapagan, type SapaganWeb } from "@sapagan/web";
let client: SapaganWeb | null = null;
export async function sapagan(): Promise<SapaganWeb | null> {
if (client) return client;
if (typeof window === "undefined" || !(await isSupported())) return null;
const messaging = getMessaging(initializeApp(JSON.parse(process.env.NEXT_PUBLIC_FIREBASE_CONFIG!)));
client = createSapagan({
key: process.env.NEXT_PUBLIC_SAPAGAN_KEY!, // ktg_app_...
baseUrl: process.env.NEXT_PUBLIC_SAPAGAN_API!,
appId: "my-web-app",
icon: "/icons/notification-192.png",
getToken: (registration) =>
getToken(messaging, { vapidKey: process.env.NEXT_PUBLIC_FIREBASE_VAPID_KEY!, serviceWorkerRegistration: registration }),
deleteToken: () => deleteToken(messaging),
getUserToken: async () => {
const r = await fetch("/api/sapagan-token", { credentials: "same-origin" });
return r.ok ? ((await r.json()) as { token: string }).token : null;
},
});
return client;
}3. On login and on every load after it, identify the user and refresh. This never prompts.
const k = await sapagan();
if (k && user) {
await k.identify(user.id); // the same external id your backend uses
await k.refreshPush(); // re-sends the token if FCM rotated it
}4. Ask for permission only from a click. Create the client before the click. Call enablePush() first thing in the handler, with no other await before it.
async function onEnable() {
const r = await k!.enablePush();
// r.status: "enabled" | "denied" | "dismissed" | "needs_user_action" | "unsupported" | "not_identified" | "error"
}5. On logout, call await (await sapagan())?.clearIdentify(). The browser stops receiving that user's notifications and the Firebase token is deleted.
Identity tokens#
Use an app key. It always needs an identity token, because a page's key is public. getUserToken returns the signed-in person's token from your backend, or null. The SDK keeps it in memory only and sends it as X-Sapagan-User-Token. See Identity tokens for the token and a Node signing example.
If the token is refused twice, enablePush and refreshPush answer { status: "error", code: "identity" } and the next load tries again.
Your page's origin must also be listed. See Web origins.
Permission prompt guidance#
- Never on page load.
enablePush()answersneeds_user_actionwhen it is not called from a click or key press.refreshPush()never asks. - Ask after the person has a reason, for example on the chat screen, with a short explanation.
- A "no" is final. After
denied, only the person can change it in the browser's site settings. Show a short how-to, and stop offering the button. dismissedis notdenied. Offer again later, not on every visit.
iPhone and iPad#
On iOS and iPadOS 16.4 and later, web push works only for a web app added to the Home Screen and opened from there. In a Safari tab, pushSupport() answers ios_home_screen_only: use it to show the Add to Home Screen steps. The app needs a web app manifest with display: "standalone". Images in notifications are not shown on iOS.
Sending#
Send with your server key. When a person has both a phone and a browser, listing push and web_push together reaches both:
curl -X POST "$SAPAGAN_URL/v1/send" \
-H "Authorization: Bearer $SAPAGAN_KEY" -H "Content-Type: application/json" \
-d '{ "to": { "externalId": "user-42" }, "templateId": "<id>", "channels": ["push", "web_push", "email"], "collapseKey": "chat:1042" }'For web, give the template an https link destination on the workspace's link allowlist. An app path such as /chat opens your web app's start page. A browser that is offline gets the message only while it is fresh (the template's ttl_minutes, default 10).
Notes#
- When FCM answers
UNREGISTEREDfor a browser, Sapagan invalidates that device. The browser registers again with its new token on the next load. - Reports carry the delivery id, the event, the time and
platform: "web", never the token or the user. - A transactional
collapseKeybecomes the notification's tag, so a newer chat push replaces the older one.