Cursorcursorintermediate
Add Web Push Notifications to Next.js (Cursor Prompt)
Cursor prompt to add web push notifications with service worker, subscription management, and VAPID keys.
What you'll get
Web push notification system with service worker, subscription management, and VAPID-based delivery.
The Prompt
Add web push notifications to this Next.js app. FILES TO CREATE: - public/sw.js — Service worker for push notification handling - src/lib/push.ts — Push subscription management utilities - src/app/api/push/subscribe/route.ts — Save push subscriptions - src/app/api/push/send/route.ts — Send push notifications - src/components/PushNotificationButton.tsx — Opt-in button component IMPLEMENTATION: 1. Generate VAPID keys using web-push library (run once: npx web-push generate-vapid-keys). 2. Create a service worker (public/sw.js) that listens for 'push' events and displays notifications with title, body, icon, badge, and click action (opens a URL). 3. In push.ts, create functions: registerServiceWorker(), subscribeToPush() (requests permission, creates subscription, sends to server), and unsubscribeFromPush(). 4. The subscribe API route saves the PushSubscription object to a Supabase "push_subscriptions" table linked to the user. 5. The send API route accepts userId and notification payload, retrieves their subscription, and sends via web-push library. 6. PushNotificationButton shows a bell icon that toggles subscription state. Handle permission states: default (show opt-in), granted (show active), denied (show explanation). 7. Handle subscription expiry and re-subscription gracefully. DATABASE: - "push_subscriptions" table: id, user_id, endpoint, p256dh, auth, created_at, updated_at DO NOT: - Use Firebase Cloud Messaging — use the native Web Push API - Auto-request permission on page load (this is anti-pattern and browsers penalize it) - Send push notifications without user consent ENVIRONMENT VARIABLES: - NEXT_PUBLIC_VAPID_PUBLIC_KEY - VAPID_PRIVATE_KEY - VAPID_SUBJECT (mailto: email)
Replace these variables
| Variable | Replace with |
|---|---|
| [NOTIFICATION_TYPES] | Types of notifications to send (e.g., new message, order update) |
Tips for best results
Never request push permission on page load — wait for a user action like clicking a 'Get Notifications' button.
Store VAPID keys as environment variables — regenerating them invalidates all existing subscriptions.
Follow-up prompts
Add notification scheduling
Add the ability to schedule push notifications for a future time using a cron job or Supabase pg_cron.