2

After followed the tutorial from Google about Push Notification, I added Push Notification capacity to my Gatsby + Netlify powered PWA website.

it works, but with a bug.

Step 1 From the client side, it subscribes to get service worker registration.

swRegistration.pushManager.subscribe({
  userVisibleOnly: true
})
.then(subscription => {
  console.log('User is subscribed:', subscription);
  isSubscribed = true;
})
.catch(err => {
  if (Notification.permission === 'denied') {
    console.warn('Permission for notifications was denied');
  } else {
    console.error('Failed to subscribe the user: ', err);
  }
});

Step 2 then from the server side(Netlify Lambda function), we need to paste in the registration object which is printed out from client side from this line of code

.then(subscription => { console.log('User is subscribed:', subscription); isSubscribed = true; })

in order to make it work(server side/lambda function):

const webPush = require('web-push');

const pushSubscription = YOUR_SUBSCRIPTION_OBJECT;

// TODO 4.3a - include VAPID keys

const payload = 'Here is a payload!';

const options = {
  TTL: 60,

  // TODO 4.3b - add VAPID details
  vapidDetails: {
    subject: "mailto:my@gmail.com",
    publicKey: vapidPublicKey,
    privateKey: vapidPrivateKey,
  },
};

webPush.sendNotification(
  pushSubscription,
  payload,
  options
);

Now, you probably has already noticed the issue.

When developing locally, I can launch my Gatsby PWA website by

gatsby build && gatsby serve

then it prints out the registration object from the Gatsby PWA client side. I can then paste it(the registration object) into the Netlify lambda function, then launch my Netlify Lambda function by

netlify dev

But when deploying the Garsby + Netlify PWA website, the lambda function is deployed together with the PWA, then how can I make sure the lambda function uses the registration received from the client side which only happens when a user hits the website after deployment?

Franva
  • 6,565
  • 23
  • 79
  • 144

0 Answers0