Course contentsShow
← Web Development
Lesson 2347 of 2,98242. Progressive Web AppsFree lesson

Push Subscription Creation

Creating a push subscription with service worker registration.pushManager.subscribe().

Push Subscription Creation

You'll learn how to create a push subscription object that enables your PWA to receive push messages from a server.

What is Push Subscription Creation?

Once the user grants notification permission, your next step is creating a push subscription. This subscription is a unique endpoint that your server will use to send push notifications specifically to this user's device and browser. Think of it like getting a unique mailing address assigned just for this user's browser—your server needs this address to deliver messages.

Using pushManager.subscribe()

The service worker's registration.pushManager.subscribe() method creates the subscription. You must provide a VAPID public key (a security token that proves your server is authorized to send pushes):

// In your main app (not the service worker file)
navigator.serviceWorker.ready.then(registration => {
  const vapidPublicKey = 'YOUR_PUBLIC_KEY_HERE';
  
  // Convert base64 string to Uint8Array
  const convertedKey = urlBase64ToUint8Array(vapidPublicKey);
  
  return registration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: convertedKey
  });
}).then(subscription => {
  console.log('Push subscription created:', subscription);
  // Send subscription to your server
});

function urlBase64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
  const rawData = window.atob(base64);
  return Uint8Array.from([...rawData].map(char => char.charCodeAt(0)));
}

The userVisibleOnly: true option ensures every push message shows a notification (required by most browsers). The subscription object contains the endpoint and encryption keys your server needs.

Key Takeaway: Creating a push subscription with registration.pushManager.subscribe() generates a unique endpoint and encryption keys that you must send to your server for delivering push notifications.