push-notifications について
プッシュ通知実装のための開発者向けリファレンススキルです。FCM、Web Push、Expo Notifications のサーバー・クライアント側のコードと運用上の注意点を扱います。
主な機能
- 01FCM のサーバー送信
- 02Web Push の購読と Service Worker
- 03Expo Notifications のトークン取得
- 04マルチプラットフォーム通知サービスのパターン
- 05送信信頼性のチェックリスト
活用シーン
- 01FCM デバイスへの通知送信
- 02Web アプリへのブラウザープッシュ追加
- 03React Native での通知許可要求
- 04トークン整理とバックグラウンド送信の計画
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ claude-dev-suite/ claude-dev-suite --skill push-notificationsインストール後、Claude Code で/push-notificationsを入力して読み込まれたか確認します。
詳細
プッシュ通知
Firebase Cloud Messaging (FCM) — サーバー
import admin from 'firebase-admin';
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
// Send to single device
await admin.messaging().send({
token: deviceToken,
notification: { title: 'New Order', body: 'Order #1234 confirmed' },
data: { orderId: '1234', type: 'order_confirmed' },
android: { priority: 'high' },
apns: { payload: { aps: { sound: 'default', badge: 1 } } },
});
// Send to topic
await admin.messaging().send({
topic: 'promotions',
notification: { title: 'Flash Sale', body: '50% off today!' },
});
Web Push(サービスワーカー)
// Register service worker and subscribe
const registration = await navigator.serviceWorker.register('/sw.js');
const subscription = await registration.pushManager.subscribe({
userVisibleNotification: true,
applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY),
});
// Send subscription to server
await fetch('/api/push/subscribe', {
method: 'POST',
body: JSON.stringify(subscription),
headers: { 'Content-Type': 'application/json' },
});
サービスワーカー(sw.js)
self.addEventListener('push', (event) => {
const data = event.data.json();
event.waitUntil(
self.registration.showNotification(data.title, {
body: data.body,
icon: '/icon-192.png',
badge: '/badge-72.png',
data: { url: data.url },
})
);
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
event.waitUntil(clients.openWindow(event.notification.data.url));
});
サーバー(web-push library)
import webpush from 'web-push';
webpush.setVapidDetails('mailto:[email protected]', VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY);
await webpush.sendNotification(subscription, JSON.stringify({
title: 'New Message',
body: 'You have a new message from John',
url: '/messages/123',
}));
Expo 通知(React Native)
import * as Notifications from 'expo-notifications';
// Request permission
const { status } = await Notifications.requestPermissionsAsync();
if (status !== 'granted') return;
// Get push token
const token = (await Notifications.getExpoPushTokenAsync()).data;
// Send token to your server
// Handle received notification
Notifications.addNotificationReceivedListener((notification) => {
console.log(notification.request.content);
});
// Handle notification tap
Notifications.addNotificationResponseReceivedListener((response) => {
const data = response.notification.request.content.data;
navigateTo(data.screen);
});
通知サービスのパターン
class NotificationService {
async send(userId: string, notification: NotificationPayload) {
const devices = await this.deviceRepo.findByUser(userId);
const results = await Promise.allSettled(
devices.map((device) => {
switch (device.platform) {
case 'web': return this.sendWebPush(device, notification);
case 'ios':
case 'android': return this.sendFCM(device, notification);
}
})
);
// Remove invalid tokens
for (const [i, result] of results.entries()) {
if (result.status === 'rejected' && isInvalidToken(result.reason)) {
await this.deviceRepo.remove(devices[i].id);
}
}
}
}
アンチパターン
| アンチパターン | 修正方法 |
|---|---|
| プッシュ通知を同期的に送信する | バックグラウンドジョブキューを使用する |
| トークンをクリーンアップしない | 無効または期限切れのデバイストークンを削除する |
| 通知許可を求める際の UX が不十分 | 説明を添えて、適切なタイミングで許可を求める |
| 通知をグループ化しない | 通知の乱発を防ぐため、種類ごとにグループ化する |
| 送信時の失敗を通知しない | 失敗をログに記録し、一時的なエラーは再試行する |
本番環境向けチェックリスト
- Web Push 用の VAPID キーを生成済み
- FCM サービスアカウントを設定済み
- デバイストークンの保存とクリーンアップを実装済み
- 一括送信用のバックグラウンドジョブキューを用意済み
- ユーザーごとの通知設定を用意済み
- スパムを防ぐためのレート制限を設定済み
- 分析機能:配信率、開封率
コメント
Markdown 対応