← Vytvářejte agenty na Cloudflare / agents / communication-channels / webhooks
Push notifikace
Odesílejte push oznámení prohlížeče z vašeho agenta, i když uživatel zavřel kartu. Kombinací trvalého stavu agenta (pro ukládání odběrů push oznámení), plánování (pro časované doručení) a Web Push API ↗, můžete oslovit uživatele, kteří jsou zcela offline.
Jak to funguje
Browser Agent (Durable Object)
─────── ──────────────────────
1. Register service worker
2. Subscribe to push (VAPID key)
3. Send subscription to agent ──────► Store in this.state
4. Create reminder ─────────────────► this.schedule(delay, "sendReminder", payload)
... user closes tab ...
5. Alarm fires → sendReminder()
web-push sends encrypted payload
│
6. Service worker receives push ◄─────────────┘
7. showNotification()Agent trvale ukládá push odběry ve svém stavu a používá this.schedule() ke spouštění oznámení ve správný čas. Jakmile se alarm spustí, agent zavolá koncový bod push služby pomocí web-push ↗ knihovnu. Service worker prohlížeče přijme událost push a zobrazí nativní oznámení.
Předpoklady
Vygenerujte klíče VAPID
Web Push vyžaduje pár klíčů VAPID (Voluntary Application Server Identification). Vygenerujte jej:
npx web-push generate-vapid-keysUložte klíče do .env soubor pro lokální vývoj:
VAPID_PUBLIC_KEY=BGxK...
VAPID_PRIVATE_KEY=abc1...
VAPID_SUBJECT=mailto:[email protected]V produkci použijte wrangler secret put:
wrangler secret put VAPID_PUBLIC_KEY
wrangler secret put VAPID_PRIVATE_KEY
wrangler secret put VAPID_SUBJECTVytvořte agenta
Agent má tři úkoly: ukládat push odběry, plánovat připomenutí a odesílat oznámení při spuštění alarmů.
import { Agent, callable, routeAgentRequest } from "agents";
import webpush from "web-push";
export class ReminderAgent extends Agent {
initialState = {
subscriptions: [],
reminders: [],
};
@callable()
getVapidPublicKey() {
return this.env.VAPID_PUBLIC_KEY;
}
@callable()
async subscribe(subscription) {
const exists = this.state.subscriptions.some(
(s) => s.endpoint === subscription.endpoint,
);
if (!exists) {
this.setState({
...this.state,
subscriptions: [...this.state.subscriptions, subscription],
});
}
return { ok: true };
}
@callable()
async unsubscribe(endpoint) {
this.setState({
...this.state,
subscriptions: this.state.subscriptions.filter(
(s) => s.endpoint !== endpoint,
),
});
return { ok: true };
}
@callable()
async createReminder(message, delaySeconds) {
const id = crypto.randomUUID();
const scheduledAt = Date.now() + delaySeconds * 1000;
const reminder = { id, message, scheduledAt, sent: false };
this.setState({
...this.state,
reminders: [...this.state.reminders, reminder],
});
await this.schedule(delaySeconds, "sendReminder", { id, message });
return reminder;
}
async sendReminder(payload) {
webpush.setVapidDetails(
this.env.VAPID_SUBJECT,
this.env.VAPID_PUBLIC_KEY,
this.env.VAPID_PRIVATE_KEY,
);
const deadEndpoints = [];
await Promise.all(
this.state.subscriptions.map(async (sub) => {
try {
await webpush.sendNotification(
sub,
JSON.stringify({
title: "Reminder",
body: payload.message,
tag: `reminder-${payload.id}`,
}),
);
} catch (err) {
const statusCode =
err instanceof webpush.WebPushError ? err.statusCode : 0;
if (statusCode === 404 || statusCode === 410) {
deadEndpoints.push(sub.endpoint);
}
}
}),
);
if (deadEndpoints.length > 0) {
this.setState({
...this.state,
subscriptions: this.state.subscriptions.filter(
(s) => !deadEndpoints.includes(s.endpoint),
),
});
}
this.setState({
...this.state,
reminders: this.state.reminders.map((r) =>
r.id === payload.id ? { ...r, sent: true } : r,
),
});
this.broadcast(
JSON.stringify({
type: "reminder_sent",
id: payload.id,
timestamp: Date.now(),
}),
);
}
}
export default {
async fetch(request, env) {
return (
(await routeAgentRequest(request, env)) ??
new Response("Not found", { status: 404 })
);
},
};import { Agent, callable, routeAgentRequest } from "agents";
import webpush from "web-push";
type Subscription = {
endpoint: string;
expirationTime: number | null;
keys: {
p256dh: string;
auth: string;
};
};
type Reminder = {
id: string;
message: string;
scheduledAt: number;
sent: boolean;
};
type ReminderAgentState = {
subscriptions: Subscription[];
reminders: Reminder[];
};
export class ReminderAgent extends Agent<Env, ReminderAgentState> {
initialState: ReminderAgentState = {
subscriptions: [],
reminders: [],
};
@callable()
getVapidPublicKey(): string {
return this.env.VAPID_PUBLIC_KEY;
}
@callable()
async subscribe(subscription: Subscription): Promise<{ ok: boolean }> {
const exists = this.state.subscriptions.some(
(s) => s.endpoint === subscription.endpoint,
);
if (!exists) {
this.setState({
...this.state,
subscriptions: [...this.state.subscriptions, subscription],
});
}
return { ok: true };
}
@callable()
async unsubscribe(endpoint: string): Promise<{ ok: boolean }> {
this.setState({
...this.state,
subscriptions: this.state.subscriptions.filter(
(s) => s.endpoint !== endpoint,
),
});
return { ok: true };
}
@callable()
async createReminder(
message: string,
delaySeconds: number,
): Promise<Reminder> {
const id = crypto.randomUUID();
const scheduledAt = Date.now() + delaySeconds * 1000;
const reminder: Reminder = { id, message, scheduledAt, sent: false };
this.setState({
...this.state,
reminders: [...this.state.reminders, reminder],
});
await this.schedule(delaySeconds, "sendReminder", { id, message });
return reminder;
}
async sendReminder(payload: { id: string; message: string }) {
webpush.setVapidDetails(
this.env.VAPID_SUBJECT,
this.env.VAPID_PUBLIC_KEY,
this.env.VAPID_PRIVATE_KEY,
);
const deadEndpoints: string[] = [];
await Promise.all(
this.state.subscriptions.map(async (sub) => {
try {
await webpush.sendNotification(
sub,
JSON.stringify({
title: "Reminder",
body: payload.message,
tag: `reminder-${payload.id}`,
}),
);
} catch (err: unknown) {
const statusCode =
err instanceof webpush.WebPushError ? err.statusCode : 0;
if (statusCode === 404 || statusCode === 410) {
deadEndpoints.push(sub.endpoint);
}
}
}),
);
if (deadEndpoints.length > 0) {
this.setState({
...this.state,
subscriptions: this.state.subscriptions.filter(
(s) => !deadEndpoints.includes(s.endpoint),
),
});
}
this.setState({
...this.state,
reminders: this.state.reminders.map((r) =>
r.id === payload.id ? { ...r, sent: true } : r,
),
});
this.broadcast(
JSON.stringify({
type: "reminder_sent",
id: payload.id,
timestamp: Date.now(),
}),
);
}
}
export default {
async fetch(request: Request, env: Env) {
return (
(await routeAgentRequest(request, env)) ??
new Response("Not found", { status: 404 })
);
},
} satisfies ExportedHandler<Env>; sendReminder callback řeší tři věci: doručení push notifikace přes web-push knihovnu, odstraňuje mrtvé odběry (push služba u neplatného odběru vrací 404 nebo 410) a rozesílá zprávu všem připojeným klientům, aby se rozhraní aktualizovalo v reálném čase.
Nastavte service worker
Service worker běží v prohlížeči a přijímá push události i tehdy, když nejsou otevřené žádné karty. Tento soubor umístěte na public/sw.js aby se obsluhoval z kořene vaší domény:
self.addEventListener("push", (event) => {
if (!event.data) return;
const data = event.data.json();
event.waitUntil(
self.registration.showNotification(data.title || "Notification", {
body: data.body || "",
icon: data.icon || "/favicon.ico",
tag: data.tag,
data: data.data,
}),
);
});
self.addEventListener("notificationclick", (event) => {
event.notification.close();
event.waitUntil(
self.clients.matchAll({ type: "window" }).then((windowClients) => {
for (const client of windowClients) {
if (
client.url.includes(self.location.origin) &&
"focus" in client
) {
return client.focus();
}
}
return self.clients.openWindow("/");
}),
);
}); push event handler zpracuje payload JSON a zobrazí nativní oznámení. notificationclick handler po klepnutí uživatele na oznámení zaměří existující kartu nebo otevře novou.
Sestavte klienta
Klient musí: zaregistrovat service worker, požádat o oprávnění k zobrazování oznámení, přihlásit se k odběru push zpráv pomocí veřejného klíče VAPID a odeslat odběr agentovi.
Zaregistrujte service worker
useEffect(() => {
if (!("serviceWorker" in navigator) || !("PushManager" in window)) {
return;
}
navigator.serviceWorker.register("/sw.js");
}, []);useEffect(() => {
if (!("serviceWorker" in navigator) || !("PushManager" in window)) {
return;
}
navigator.serviceWorker.register("/sw.js");
}, []);Přihlášení k odběru push
Načtěte veřejný klíč VAPID z agenta a poté se přihlaste k odběru přes Push API:
function base64urlToUint8Array(base64url) {
const padded = base64url + "=".repeat((4 - (base64url.length % 4)) % 4);
const binary = atob(padded.replace(/-/g, "+").replace(/_/g, "/"));
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes;
}
async function subscribeToPush(agent) {
const permission = await Notification.requestPermission();
if (permission !== "granted") return;
const vapidPublicKey = await agent.call("getVapidPublicKey");
const reg = await navigator.serviceWorker.ready;
const subscription = await reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: base64urlToUint8Array(vapidPublicKey).buffer,
});
const subJson = subscription.toJSON();
await agent.call("subscribe", [
{
endpoint: subJson.endpoint,
expirationTime: subJson.expirationTime ?? null,
keys: subJson.keys,
},
]);
}function base64urlToUint8Array(base64url: string): Uint8Array {
const padded = base64url + "=".repeat((4 - (base64url.length % 4)) % 4);
const binary = atob(padded.replace(/-/g, "+").replace(/_/g, "/"));
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes;
}
async function subscribeToPush(
agent: ReturnType<typeof useAgent>,
) {
const permission = await Notification.requestPermission();
if (permission !== "granted") return;
const vapidPublicKey = await agent.call("getVapidPublicKey");
const reg = await navigator.serviceWorker.ready;
const subscription = await reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: base64urlToUint8Array(vapidPublicKey).buffer,
});
const subJson = subscription.toJSON();
await agent.call("subscribe", [
{
endpoint: subJson.endpoint,
expirationTime: subJson.expirationTime ?? null,
keys: subJson.keys,
},
]);
}Vytvářejte připomínky
Jakmile je odběr uložen, vytvoření připomínky je jediné volání RPC. O plánování a doručení se stará agent:
await agent.call("createReminder", ["Check the oven", 300]);await agent.call("createReminder", ["Check the oven", 300]);Agent naplánuje alarm na 300 sekund (5 minut). Když se spustí, push oznámení dorazí, i když uživatel zavřel kartu před několika minutami.
Konfigurace
wrangler.jsonc
{
"name": "push-notifications",
"compatibility_date": "2026-01-28",
"compatibility_flags": ["nodejs_compat"],
"main": "src/server.ts",
"durable_objects": {
"bindings": [
{ "name": "ReminderAgent", "class_name": "ReminderAgent" },
],
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["ReminderAgent"] }],
"assets": {
"not_found_handling": "single-page-application",
},
} nodejs_compat je vyžadován příznak kompatibility pro web-push knihovna.
Závislosti
npm install agents web-pushÚvahy o produkčním nasazení
Vypršení odběru
Push odběry mohou vypršet nebo je může uživatel zrušit. Odpovědi 404 a 410 od push služby vždy ošetřete odebráním neplatného odběru ze stavu, jak je znázorněno v sendReminder příklad výše.
Agenti pro jednotlivé uživatele oproti sdíleným agentům
Pro většinu aplikací použijte jednoho agenta na uživatele (jako název agenta použijte ID uživatele). Tím se oddělí odběry a připomenutí jednotlivých uživatelů. Pro hromadná oznámení (stejná zpráva pro mnoho uživatelů) může všechny odběry ukládat sdílený agent, je ale třeba počítat s velikostí stavu, jak seznam odběrů roste.
Kombinace push notifikací s vysíláním přes WebSocket
Použijte this.broadcast() pro aktuálně připojené klienty (okamžitě, bez zpáteční cesty přes push službu) a Web Push pro klienty offline. sendReminder příklad výše dělá obojí: připojení klienti dostanou zprávu WebSocket v reálném čase a odpojení klienti dostanou push notifikaci.
Více zařízení
Jeden uživatel se může přihlásit k odběru z více prohlížečů nebo zařízení. Agent ukládá každý odběr zvlášť a sendReminder projde všechny z nich. Každé zařízení dostane vlastní push notifikaci.
Opakování při selhání
Pokud push služba vrátí chybu 5xx (dočasné selhání), můžete pokus zopakovat pomocí this.schedule() s krátkým zpožděním:
try {
await webpush.sendNotification(sub, payload);
} catch (err) {
const statusCode = err instanceof webpush.WebPushError ? err.statusCode : 0;
if (statusCode >= 500) {
await this.schedule(60, "retrySendNotification", {
endpoint: sub.endpoint,
payload,
});
}
}try {
await webpush.sendNotification(sub, payload);
} catch (err: unknown) {
const statusCode =
err instanceof webpush.WebPushError ? err.statusCode : 0;
if (statusCode >= 500) {
await this.schedule(60, "retrySendNotification", {
endpoint: sub.endpoint,
payload,
});
}
}