Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

プッシュ通知

最終更新 Markdown で表示Agent セットアップ

エージェントからブラウザへプッシュ通知を送れます。タブを閉じていても届きます。エージェントの永続状態(プッシュサブスクリプションの保存)、スケジュール(時刻指定の配信)、Web Push API を組み合わせると、完全にオフラインのユーザーにも届けられます。

仕組み

ブラウザ                              エージェント(Durable Object)
───────                              ──────────────────────
1. サービスワーカーを登録
2. プッシュを購読(VAPID キー)
3. サブスクリプションをエージェントへ送信 ──────► this.state に保存
4. リマインダーを作成 ─────────────────► this.schedule(delay, "sendReminder", payload)

   ... ユーザーがタブを閉じる ...

5.                                    アラーム発火 → sendReminder()
                                      web-push が暗号化ペイロードを送信

6. サービスワーカーがプッシュを受信 ◄─────────────┘
7. showNotification()

エージェントはプッシュサブスクリプションを状態に永続保存し、this.schedule() で適切な時刻に通知を発火します。アラームが発火すると、エージェントは web-push ライブラリでプッシュサービスエンドポイントを呼び出します。ブラウザのサービスワーカーが push イベントを受け取り、ネイティブ通知を表示します。

前提条件

VAPID キーを生成する

Web Push には VAPID(Voluntary Application Server Identification)のキーペアが必要です。次で生成します。

npx web-push generate-vapid-keys

ローカル開発では .env ファイルにキーを保存します。

VAPID_PUBLIC_KEY=BGxK...
VAPID_PRIVATE_KEY=abc1...
VAPID_SUBJECT=mailto:you@example.com

本番では wrangler secret put を使います。

wrangler secret put VAPID_PUBLIC_KEY
wrangler secret put VAPID_PRIVATE_KEY
wrangler secret put VAPID_SUBJECT

エージェントを作成する

エージェントの役割は 3 つです。プッシュサブスクリプションの保存、リマインダーのスケジュール、アラーム発火時の通知送信です。

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 コールバックは 3 つを処理します。web-push ライブラリによるプッシュ通知の配信、無効になったサブスクリプションの削除(プッシュサービスはサブスクリプションが無効だと 404 または 410 を返します)、接続中のクライアントへのブロードキャスト(UI をリアルタイム更新します)。

サービスワーカーを設定する

サービスワーカーはブラウザ上で動き、タブが開いていなくても push イベントを受け取ります。ドメインのルートから配信されるよう、このファイルを public/sw.js に置きます。

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 イベントハンドラーは JSON ペイロードを解析し、ネイティブ通知を表示します。notificationclick ハンドラーは、ユーザーが通知をタップしたときに既存タブへフォーカスするか、新しいタブを開きます。

クライアントを構築する

クライアントでは次を行います。サービスワーカーの登録、通知許可のリクエスト、VAPID 公開鍵でのプッシュ購読、サブスクリプションのエージェントへの送信です。

サービスワーカーを登録する

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");
}, []);

プッシュを購読する

エージェントから VAPID 公開鍵を取得し、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,
		},
	]);
}

リマインダーを作成する

サブスクリプションを保存したあと、リマインダー作成は RPC 呼び出し 1 回です。スケジュールと配信はエージェントが担当します。

await agent.call("createReminder", ["Check the oven", 300]);
await agent.call("createReminder", ["Check the oven", 300]);

エージェントは 300 秒(5 分)後にアラームをスケジュールします。発火するとプッシュ通知が届きます。数分前にタブを閉じていても届きます。

設定

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",
	},
}

web-push ライブラリには nodejs_compat 互換性フラグが必要です。

依存関係

npm install agents web-push

本番運用の注意点

サブスクリプションの期限切れ

プッシュサブスクリプションは期限切れになる、またはユーザーが取り消すことがあります。プッシュサービスから 404 と 410 が返ったら、上記の sendReminder 例のように、無効なサブスクリプションを状態から必ず削除します。

ユーザー単位と共有エージェント

ほとんどのアプリでは、ユーザーごとに 1 つのエージェントを使います(ユーザー ID をエージェント名にします)。サブスクリプションとリマインダーがユーザーごとに分離されます。ブロードキャスト型の通知(多数のユーザーへ同じメッセージ)では、共有エージェントに全サブスクリプションを保存できます。ただしリストが大きくなると状態サイズに注意してください。

プッシュと WebSocket ブロードキャストの併用

接続中のクライアントには this.broadcast() を使います(即時で、プッシュサービスを経由しません)。オフラインのクライアントには Web Push を使います。上記の sendReminder 例は両方を行います。接続中のクライアントはリアルタイムの WebSocket メッセージを受け取り、オフラインのクライアントはプッシュ通知を受け取ります。

複数デバイス

1 人のユーザーが複数のブラウザやデバイスから購読することがあります。エージェントは各サブスクリプションを個別に保存し、sendReminder はすべてを走査します。各デバイスが独自のプッシュ通知を受け取ります。

失敗時の再試行

プッシュサービスが 5xx エラー(一時的な失敗)を返した場合、短い遅延で this.schedule() を使って再試行できます。

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,
		});
	}
}

次のステップ

役に立ちましたか?