myHotTake

Tag: Push API

  • How Does the Push API Function in JavaScript?

    If you find this story helpful or entertaining, feel free to give it a like or share it with others who might appreciate it!


    I’m running a little antique shop at the end of a charming village lane. The Push API is like hiring a town crier to stand outside my shop and announce new arrivals to everyone who passes by. It’s an exciting concept because it means potential customers don’t have to constantly pop in to check if anything new has arrived—they’ll hear about it as soon as it happens.

    However, there are some limitations to this setup. First, not everyone in the village might be around to hear the announcements. Some villagers are out in the fields or visiting other towns. Similarly, in the digital world, not all devices support the Push API equally, so some people might miss these notifications.

    Another challenge is that my town crier has a limited range and can’t travel too far. This means that only those nearby will hear the announcements. In the same vein, the Push API is limited by network connectivity and browser support, so it’s not always effective in reaching everyone everywhere.

    Moreover, if my crier goes on and on about every tiny detail, villagers might get annoyed by the constant noise. In the digital realm, users can become overwhelmed by too many notifications, leading them to mute or block them entirely.

    Lastly, there’s a cost to keeping a town crier employed. In tech terms, this translates to the need for maintaining a reliable server and handling the complexities of managing subscriptions and security, which can be resource-intensive.

    In essence, while the Push API offers a convenient way to keep people informed, just like my town crier, it requires careful management to ensure its messages are both heard and appreciated.


    Back in my antique shop, the town crier (Push API) needs instructions on what to announce and when. In JavaScript, this is like setting up the Push API to send notifications to users. Let’s say I want the crier to announce whenever a new shipment arrives. In JavaScript, I would start by registering a service worker, which acts like the crier’s script.

    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('/service-worker.js')
        .then(function(registration) {
          console.log('Service Worker registered with scope:', registration.scope);
        })
        .catch(function(error) {
          console.error('Service Worker registration failed:', error);
        });
    }

    Next, I need to make sure the crier knows whom to notify. In JavaScript, this means subscribing the user to push notifications.

    function subscribeUser() {
      navigator.serviceWorker.ready.then(function(registration) {
        return registration.pushManager.subscribe({
          userVisibleOnly: true,
          applicationServerKey: '<Your Public VAPID Key Here>'
        });
      }).then(function(subscription) {
        console.log('User is subscribed:', subscription);
      }).catch(function(err) {
        console.error('Failed to subscribe the user:', err);
      });
    }

    Once the subscription is set up, I can send notifications whenever there’s news in the shop. For this, I need to send a push message from my server, like sending a letter to the crier with the latest update.

    function sendPushNotification(subscription, payload) {
      fetch('/send-notification', {
        method: 'POST',
        body: JSON.stringify({ subscription, payload }),
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(function(response) {
        if (!response.ok) {
          throw new Error('Failed to send notification');
        }
        return response.json();
      }).then(function(data) {
        console.log('Push notification sent:', data);
      }).catch(function(error) {
        console.error('Error sending push notification:', error);
      });
    }

    Key Takeaways:

    1. Service Worker: Acts as the backbone of the Push API, enabling background scripts for handling push events.
    2. Subscription: Allows users to opt-in for receiving notifications, similar to villagers agreeing to listen to the town crier.
    3. Notification Management: Requires careful handling to ensure messages are relevant and not overwhelming, akin to balancing the volume and frequency of the crier’s announcements.
    4. Resource Considerations: Managing subscriptions and notifications can be resource-intensive and needs careful planning, much like the logistics of running an effective announcement system.
  • How Do Push and Notifications APIs Work in JavaScript?

    Hey there! If you find this story helpful or just downright interesting, feel free to give it a like or share it with someone who might need a splash of creativity in their learning journey.


    So, I’m a competitive swimmer, training rigorously for a big swim meet. In this scenario, the Push API is like my dedicated coach who keeps me updated about upcoming events, changes in practice schedules, or any immediate alerts that might affect my training regimen. My coach doesn’t need me to be around all the time to deliver these updates. Instead, they have a knack for reaching out to me at the right moment, ensuring I’m prepared and informed regardless of where I am.

    Now, think of the Notifications API as the loudspeaker at the swimming pool. When my coach needs to send an urgent message — maybe a sudden change in the race lineup or the need to rush to the pool for a practice session — they use the loudspeaker to announce it to everyone in the vicinity. This way, the message is clear, direct, and impossible to miss, just like how notifications pop up on a device screen.

    In this aquatic world, my coach (Push API) sends me personalized alerts even when I’m not at the pool. Once I arrive, the loudspeaker (Notifications API) ensures that I, plus anyone else in the area, hear the critical announcements. Together, they create a seamless flow of information, keeping me updated and ready for any twist or turn in my swimming journey.

    So, just like my coach and the loudspeaker work in harmony to keep me on my toes, the Push API and Notifications API collaborate to keep web users informed and engaged, even when they’re not actively browsing. If you enjoyed this dive into the tech pool with me, don’t hesitate to share it with your fellow learners!


    In our swimming analogy, my coach (Push API) needs to send me updates even when I’m not at the pool (or when the app is not open). To achieve this, we set up a service worker. Think of it as a lifeguard who’s always at the pool, even when I’m not, ready to relay any messages from my coach.

    Here’s how you might set it up:

    // Registering the service worker
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
        console.log('Service Worker registered with scope:', registration.scope);
    });

    In the sw.js file, the service worker listens for push events:

    // Listening for push events
    self.addEventListener('push', function(event) {
        const data = event.data.json();
        console.log('Push received:', data);
    
        const options = {
            body: data.body,
            icon: 'images/icon.png',
            badge: 'images/badge.png'
        };
    
        event.waitUntil(
            self.registration.showNotification(data.title, options)
        );
    });

    When my coach sends a message, the lifeguard (service worker) catches it and uses the loudspeaker (Notifications API) to make an announcement. This announcement is the notification you see on your device.

    Now, to send a push message, a server-side script might look something like this:

    const webPush = require('web-push');
    
    const pushSubscription = {
        endpoint: 'https://fcm.googleapis.com/fcm/send/example',
        keys: {
            auth: 'auth_key',
            p256dh: 'p256dh_key'
        }
    };
    
    const payload = JSON.stringify({
        title: 'Race Alert!',
        body: 'Your next race is in 15 minutes!'
    });
    
    webPush.sendNotification(pushSubscription, payload).catch(error => {
        console.error('Error sending notification:', error);
    });

    Key Takeaways:

    1. Push API: Like a coach, it sends messages to clients even when they’re not actively engaging with the application.
    2. Service Workers: These operate in the background and act as intermediaries, ready to activate the Notifications API upon receiving a push message.
    3. Notifications API: Functions like a loudspeaker, ensuring the messages are delivered to the user in a noticeable way.