Files
kycnotme/web/src/lib/webPush.ts

60 lines
1.4 KiB
TypeScript
Raw Normal View History

2025-06-02 03:53:03 +00:00
/* eslint-disable import/no-named-as-default-member */
import webpush, { WebPushError } from 'web-push'
2025-06-04 16:41:32 +00:00
import { getServerEnvVariable } from './serverEnvVariables'
const VAPID_PUBLIC_KEY = getServerEnvVariable('VAPID_PUBLIC_KEY')
const VAPID_PRIVATE_KEY = getServerEnvVariable('VAPID_PRIVATE_KEY')
const VAPID_SUBJECT = getServerEnvVariable('VAPID_SUBJECT')
2025-06-02 03:53:03 +00:00
// Configure VAPID keys
webpush.setVapidDetails(VAPID_SUBJECT, VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY)
export { webpush }
2025-06-04 16:41:32 +00:00
export type NotificationData = {
title: string
body?: string
icon?: string
badge?: string
url?: string
}
2025-06-02 03:53:03 +00:00
export async function sendPushNotification(
subscription: {
endpoint: string
keys: {
p256dh: string
auth: string
}
},
2025-06-04 16:41:32 +00:00
data: NotificationData
2025-06-02 03:53:03 +00:00
) {
try {
const result = await webpush.sendNotification(
subscription,
JSON.stringify({
title: data.title,
options: {
body: data.body,
icon: data.icon ?? '/favicon.svg',
badge: data.badge ?? '/favicon.svg',
data: {
url: data.url,
},
},
}),
{
TTL: 24 * 60 * 60, // 24 hours
}
)
return { success: true, result } as const
} catch (error) {
console.error('Error sending push notification:', error)
return {
success: false,
error: error instanceof WebPushError ? error : undefined,
} as const
}
}