const webPush = require('web-push') //generate and store VAPID keys in .env.local if not already done if (!process.env.NEXT_PUBLIC_WEB_PUSH_PUBLIC_KEY || !process.env.WEB_PUSH_PRIVATE_KEY) { const { publicKey, privateKey } = webPush.generateVAPIDKeys() console.log('VAPID keys generated:') console.log('Public key:', publicKey) console.log('Private key:', privateKey) console.log('Store these keys in your .env.local file:') console.log('NEXT_PUBLIC_WEB_PUSH_PUBLIC_KEY=', publicKey) console.log('WEB_PUSH_PRIVATE_KEY=', privateKey) process.exit(0) } webPush.setVapidDetails( `mailto:${process.env.WEB_PUSH_EMAIL}`, process.env.NEXT_PUBLIC_WEB_PUSH_PUBLIC_KEY, process.env.WEB_PUSH_PRIVATE_KEY ) const Notification = async (req, res) => { if (req.method == 'GET') { res.statusCode = 200 res.setHeader('Allow', 'POST') // send the public key in the response headers //res.setHeader('Content-Type', 'text/plain') res.end(process.env.NEXT_PUBLIC_WEB_PUSH_PUBLIC_KEY) res.end() } // on PUT store the subscription object in the database if (req.method == 'POST') { const { subscription } = req.body await webPush .sendNotification( subscription, JSON.stringify({ title: 'Hello Web Push', message: 'Your web push notification is here!' }) ) .then(response => { res.writeHead(response.statusCode, response.headers).end(response.body) }) .catch(err => { if ('statusCode' in err) { res.writeHead(err.statusCode, err.headers).end(err.body) } else { console.error(err) res.statusCode = 500 res.end() } }) } else { res.statusCode = 405 res.end() } } export default Notification