notifications-push
Web Push notifications with VAPID — subscribe devices, send targeted pushes, notification preferences, and in-app notification center. Use this skill when the user says "add push notifications", "setup notifications", "add web push", "notification bell", or "push notifications".
What this skill does
# Push Notifications Web Push API notifications with VAPID authentication. Includes device subscription management, targeted push delivery, per-user notification preferences, an in-app notification center with bell icon, and a service worker for background push handling. ## Prerequisites - Next.js app with `src/` directory and App Router - `auth` skill installed (`withAuth` available at `@/lib/auth-guard`) - `db` skill installed (Drizzle ORM + Postgres) - `add-pwa` skill installed (service worker registration support) - shadcn/ui initialized ## Installation ```bash bun add web-push bun add -D @types/web-push ``` ## Environment Variables Add to `.env.local`: ```env # Web Push (VAPID) NEXT_PUBLIC_VAPID_PUBLIC_KEY=your-vapid-public-key VAPID_PRIVATE_KEY=your-vapid-private-key VAPID_SUBJECT=mailto:[email protected] ``` ### Generate VAPID Keys ```bash bunx web-push generate-vapid-keys ``` Copy the output into your `.env.local` file. ### Update `src/env.ts` Add to the `server` object: ```typescript server: { // ... existing variables VAPID_PRIVATE_KEY: z.string().min(1), VAPID_SUBJECT: z.string().startsWith("mailto:"), }, ``` Add to the `client` object: ```typescript client: { // ... existing variables NEXT_PUBLIC_VAPID_PUBLIC_KEY: z.string().min(1), }, ``` Add to the `runtimeEnv` object: ```typescript runtimeEnv: { // ... existing variables VAPID_PRIVATE_KEY: process.env.VAPID_PRIVATE_KEY, VAPID_SUBJECT: process.env.VAPID_SUBJECT, NEXT_PUBLIC_VAPID_PUBLIC_KEY: process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY, }, ``` ## What Gets Created ``` src/ ├── lib/ │ ├── notifications/ │ │ ├── push.ts # Server: initWebPush, sendPushNotification, sendBulkNotifications │ │ ├── types.ts # PushSubscription, NotificationPayload, NotificationPreference │ │ └── use-push.ts # Client hook: requestPermission, subscribe, unsubscribe │ └── db/ │ └── schema/ │ └── push-subscriptions.ts # push_subscriptions, notification_preferences, notifications tables ├── components/ │ └── notifications/ │ ├── notification-bell.tsx # Bell icon with unread count badge │ ├── notification-center.tsx # Dropdown notification list │ └── permission-prompt.tsx # One-time permission request dialog ├── app/ │ └── api/ │ └── notifications/ │ ├── subscribe/ │ │ └── route.ts # POST register push subscription │ ├── preferences/ │ │ └── route.ts # GET/PUT notification preferences │ └── route.ts # GET list, PATCH mark as read └── public/ └── sw-push.js # Service worker for push events ``` ## Database After applying this skill, push the schema: ```bash bunx drizzle-kit push ``` ## Setup Steps ### Step 1: Create `src/lib/notifications/types.ts` ```typescript export type PushSubscriptionData = { endpoint: string; keys: { p256dh: string; auth: string; }; }; export type NotificationPayload = { title: string; body: string; icon?: string; url?: string; actions?: Array<{ action: string; title: string; }>; }; export type NotificationPreference = { roomInvites: boolean; mentions: boolean; callAlerts: boolean; meetingSummaries: boolean; }; export type NotificationRecord = { id: string; userId: string; title: string; body: string; url: string | null; read: boolean; createdAt: string; }; ``` ### Step 2: Create `src/lib/notifications/push.ts` ```typescript import webPush from "web-push"; import { db } from "@/lib/db"; import { pushSubscriptions, notifications } from "@/lib/db/schema/push-subscriptions"; import { eq } from "drizzle-orm"; import type { NotificationPayload } from "./types"; let initialized = false; export function initWebPush() { if (initialized) return; const publicKey = process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY; const privateKey = process.env.VAPID_PRIVATE_KEY; const subject = process.env.VAPID_SUBJECT; if (!publicKey || !privateKey || !subject) { throw new Error( "VAPID keys not configured. Set NEXT_PUBLIC_VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY, and VAPID_SUBJECT." ); } webPush.setVapidDetails(subject, publicKey, privateKey); initialized = true; } /** * Send a push notification to a specific user. * Sends to all subscribed devices for that user. * Also stores the notification in the database for the in-app notification center. */ export async function sendPushNotification( userId: string, payload: NotificationPayload ): Promise<{ sent: number; failed: number }> { initWebPush(); // Store in-app notification await db.insert(notifications).values({ userId, title: payload.title, body: payload.body, url: payload.url ?? null, }); // Get all subscriptions for this user const subscriptions = await db .select() .from(pushSubscriptions) .where(eq(pushSubscriptions.userId, userId)); let sent = 0; let failed = 0; const pushPayload = JSON.stringify({ title: payload.title, body: payload.body, icon: payload.icon ?? "/icon-192x192.png", url: payload.url ?? "/", actions: payload.actions ?? [], }); for (const sub of subscriptions) { try { await webPush.sendNotification( { endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth, }, }, pushPayload ); sent++; } catch (error) { failed++; // Remove expired/invalid subscriptions (410 Gone) if ( error instanceof webPush.WebPushError && error.statusCode === 410 ) { await db .delete(pushSubscriptions) .where(eq(pushSubscriptions.id, sub.id)); } } } return { sent, failed }; } /** * Send a push notification to multiple users. */ export async function sendBulkNotifications( userIds: string[], payload: NotificationPayload ): Promise<{ totalSent: number; totalFailed: number }> { let totalSent = 0; let totalFailed = 0; const results = await Promise.allSettled( userIds.map((userId) => sendPushNotification(userId, payload)) ); for (const result of results) { if (result.status === "fulfilled") { totalSent += result.value.sent; totalFailed += result.value.failed; } else { totalFailed++; } } return { totalSent, totalFailed }; } ``` ### Step 3: Create `src/lib/notifications/use-push.ts` ```tsx "use client"; import { useState, useEffect, useCallback } from "react"; function urlBase64ToUint8Array(base64String: string): Uint8Array<ArrayBuffer> { const padding = "=".repeat((4 - (base64String.length % 4)) % 4); const base64 = (base64String + padding) .replace(/-/g, "+") .replace(/_/g, "/"); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; } type UsePushReturn = { isSupported: boolean; isSubscribed: boolean; isLoading: boolean; permission: NotificationPermission | "unsupported"; requestPermission: () => Promise<NotificationPermission>; subscribe: () => Promise<void>; unsubscribe: () => Promise<void>; }; export function usePush(): UsePushReturn { const [isSupported, setIsSupported] = useState(false); const [isSubscribed, setIsSubscribed] = useState(false); const [isLoading, setIsLoading] = useState(true); const [permission, setPermission] = useState<NotificationPermission | "unsupported">("unsupported"); // Check support and current subscription status useEffect(() => { const checkSupport = async () => { const supported = typeof window !== "undefined" && "serviceWorker" in navigator &&
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.