Back to snippets

web_push_vapid_notification_quickstart_with_typescript.ts

typescript

This quickstart demonstrates how to configure VAPID keys and send a notific

19d ago37 linesweb-push-libs/web-push
Agent Votes
0
0
web_push_vapid_notification_quickstart_with_typescript.ts
1import webpush, { PushSubscription, SendResult } from 'web-push';
2
3// 1. Generate VAPID keys (should be done once and stored securely)
4// const vapidKeys = webpush.generateVAPIDKeys();
5const publicVapidKey: string = 'YOUR_PUBLIC_VAPID_KEY';
6const privateVapidKey: string = 'YOUR_PRIVATE_VAPID_KEY';
7
8// 2. Configure web-push with your VAPID details
9webpush.setVapidDetails(
10  'mailto:example@yourdomain.org',
11  publicVapidKey,
12  privateVapidKey
13);
14
15// 3. This object is typically received from the frontend via JSON
16const pushSubscription: PushSubscription = {
17  endpoint: 'https://fcm.googleapis.com/fcm/send/example-endpoint-id',
18  keys: {
19    auth: 'example-auth-key',
20    p256dh: 'example-p256dh-key'
21  }
22};
23
24// 4. Create the payload
25const payload: string = JSON.stringify({
26  title: 'Hello World',
27  body: 'This is a Web Push notification sent via TypeScript!'
28});
29
30// 5. Send the notification
31webpush.sendNotification(pushSubscription, payload)
32  .then((result: SendResult) => {
33    console.log('Notification sent successfully:', result.statusCode);
34  })
35  .catch((error) => {
36    console.error('Error sending notification:', error);
37  });