push-notifications
Push notifications for web and mobile. Firebase Cloud Messaging (FCM), Apple Push Notification Service (APNs), Web Push API, Expo Notifications, and notification service architecture. USE WHEN: user mentions "push notification", "FCM", "Firebase messaging", "APNs", "web push", "service worker notification", "Expo notifications" DO NOT USE FOR: email notifications - use `email-sending`; in-app real-time updates - use `socket-io` or `sse`
What this skill does
# Push Notifications
## Firebase Cloud Messaging (FCM) — Server
```typescript
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 (Service Worker)
```typescript
// 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' },
});
```
### Service Worker (sw.js)
```javascript
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));
});
```
### Server (web-push library)
```typescript
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 Notifications (React Native)
```typescript
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);
});
```
## Notification Service Pattern
```typescript
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);
}
}
}
}
```
## Anti-Patterns
| Anti-Pattern | Fix |
|--------------|-----|
| Sending pushes synchronously | Use background job queue |
| No token cleanup | Remove invalid/expired device tokens |
| Missing notification permission UX | Ask contextually with explanation |
| No notification grouping | Group by type to avoid notification spam |
| Silent failures on send | Log failures, retry transient errors |
## Production Checklist
- [ ] VAPID keys generated for web push
- [ ] FCM service account configured
- [ ] Device token storage and cleanup
- [ ] Background job queue for batch sends
- [ ] Notification preferences per user
- [ ] Rate limiting to prevent spam
- [ ] Analytics: delivery rate, open rate
Related in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.