myHotTake

Tag: server communication

  • How Do Servers Send Push Notifications? A Simple Guide

    If you find this story helpful, feel free to like or share it with others who might enjoy it!


    I’m a competitive swimming coach at a big swim meet. My job is to guide my swimmers to victory by sending them signals during the race. These signals are like push notifications from a server to a user’s device. Just like I stand at the edge of the pool, the server stands ready to communicate with devices.

    Now, picture my whistle as the server’s communication tool. Every time I blow the whistle, it’s like sending a push notification. This whistle is not just any whistle; it’s special, tuned to the specific frequency that only my swimmers can hear. This is akin to the server needing permission from the user’s device to send push notifications—like obtaining a special key or token.

    Before the race, my swimmers have to put on wristbands that vibrate when they receive the whistle’s signal. This is similar to a device subscribing to receive notifications, where the swimmer (device) agrees to listen for my signals (notifications) by wearing the wristband.

    As the race begins, I keep an eye on each swimmer. If one of them is falling behind, I blow the whistle in a unique pattern to signal them to speed up. In the digital world, this would be the server sending a notification to prompt the user to take action, like checking a new message or updating an app.

    Sometimes, I see a swimmer who is right on track, so I don’t need to send any signals. Similarly, a server doesn’t spam devices with unnecessary notifications. It’s all about timing and relevance—sending the right message at the right moment.

    As the race concludes, my swimmers know to remove their wristbands, just as users can choose to unsubscribe from notifications. They’ve completed their race, and my role as the signaling coach comes to a pause until the next event.

    And just like that, sending a push notification from a server is all about permission, precise signaling, and ensuring the message is received and acted upon at the right time. If you enjoyed this analogy and found it helpful, consider liking or sharing it with others who might benefit!


    Setting Up the Whistle: JavaScript Code

    First, we need to set up the environment, much like preparing our whistle. This involves configuring the server to send notifications. In JavaScript, we might use Node.js with a library like web-push to send notifications to the browser.

    Here’s a basic example of how the server (our coach) can send a notification:

    const webPush = require('web-push');
    
    // Configure web-push library
    webPush.setVapidDetails(
      'mailto:[email protected]',
      'PUBLIC_VAPID_KEY',
      'PRIVATE_VAPID_KEY'
    );
    
    // Subscription object representing the swimmer
    const subscription = {
      endpoint: 'https://fcm.googleapis.com/fcm/send/...',
      keys: {
        p256dh: 'PUBLIC_KEY',
        auth: 'AUTH_KEY'
      }
    };
    
    // Payload to be sent
    const payload = JSON.stringify({ title: 'Swim Faster!', message: 'You are falling behind!' });
    
    // Send the notification
    webPush.sendNotification(subscription, payload)
      .then(response => console.log('Notification sent successfully:', response))
      .catch(error => console.error('Error sending notification:', error));

    Receiving the Signal: Frontend JavaScript

    On the swimmer’s side (the user’s browser), we need to ensure the swimmer is listening for the whistle. This involves registering a service worker that can handle incoming notifications.

    // Register the service worker
    navigator.serviceWorker.register('/sw.js')
      .then(registration => {
        console.log('Service Worker registered with scope:', registration.scope);
      })
      .catch(error => {
        console.error('Service Worker registration failed:', error);
      });
    
    // Subscribe to push notifications
    navigator.serviceWorker.ready.then(registration => {
      return registration.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: 'PUBLIC_VAPID_KEY'
      });
    }).then(subscription => {
      console.log('User is subscribed:', subscription);
    }).catch(error => {
      console.error('Failed to subscribe the user:', error);
    });

    Key Takeaways

    • Permission is Key: Just as swimmers need to agree to wear wristbands, devices must consent to receive notifications by subscribing.
    • Precise Signaling: Notifications should be relevant and timely, like the coach’s whistle signals during the race.
    • JavaScript Tools: Libraries like web-push in Node.js help send notifications, while service workers on the frontend listen for and display them.
    • Security: Always use VAPID keys and secure endpoints to ensure the integrity and security of your notifications.