Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk6 min

Push Notifications in Angular: How to Set Up Web Push with SwPush (and When to Use Firebase Instead)

Angular's service worker and SwPush handle browser push subscriptions and notification clicks, but your server must send the messages. This guide covers HTTPS requirements, permission handling, payloads, click routing, and how the Firebase Cloud Messaging web path differs.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To add browser push notifications to an Angular app, you enable Angular’s service worker, serve the app over HTTPS, request a push subscription with SwPush.requestSubscription(), send that subscription to your own server, and have the server send payloads that the service worker displays. Angular provides the client side of this flow. It does not send push messages, so you need a backend that does.

What Angular provides and what it leaves to you

Angular’s service worker can display push notifications and handle notification click events. In an app that uses it, SwPush is the documented API for requesting a subscription and for listening to incoming messages and notification interactions. The reference is in the Angular SwPush API documentation, and the end-to-end guide is in Angular’s push notifications guide.

As an Amazon Associate I earn from qualifying purchases.

Three parts of the flow belong to you rather than to Angular:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • A server that stores each user’s subscription and sends pushes to it, using the VAPID key pair.
  • The decision about when to ask for permission and what to do when the user refuses.
  • The fallback experience for browsers that do not support the Push API or service workers.

Requirements before you write code

  • HTTPS in deployment. Angular service workers require a secure origin. localhost is the development exception. The Angular Service Workers & PWAs overview documents both the HTTPS rule and the localhost exception.
  • Browser support. The browser must offer the Push API and service workers. Some browsers or private modes may not, so your code has to check this at runtime.
  • A VAPID key pair. Your server generates it. The public key goes to the client, and the private key stays on the server.
  • A backend endpoint that accepts and stores the subscription object the browser returns.

Step 1: Enable Angular’s service worker

In an Angular CLI project, add the PWA package. The Angular service worker getting-started guide describes this setup:

#1 Best Overall
Bluetooth Speaker, 20W HD Sound, Portable Wireless, IPX5 Waterproof, Up to 24H Playtime, TWS Pairing, for Home/Party/Outdoor/Camping/Beach Essentials, Electronic Gadgets, Birthday Gift (Black)
  • [Immersive Sound Experience & Dual Connectivity] Experience unparalleled sound quality with this wireless Bluetooth speaker's 2 drivers and advanced technology that delivers powerful, well-balanced sound with minimal distortion. Connect two speakers together to create an immersive stereo sound experience and fill any room with powerful sound. Perfect for gaming, music, and movie playback
  • [Tough & Weather-Resistant] Engineered to handle rough use and adverse weather conditions, this speaker features a durable design and an IPX5 rating for protection against water splashes and spills. It's an ideal choice for outdoor events, and is perfect for use at parties, at the pool, on the beach, while camping or hiking, and more
  • [Long-lasting Playtime & Extended Bluetooth Connectivity] Experience extended playtime with up to 24 hours(50% Vol and light off) per charge and extended wireless range with Bluetooth 5.3, reaching up to 100 feet from your device. The multicolor lights on the speaker can also be turned off with a simple button press to save the battery and adapt to your needs. Keep in mind that the actual playtime can vary depending on volume level, audio content, and usage
  • [Vibrant Light Effects] Bring a new level of excitement to your party with the dynamic multi-color light show that syncs to the beat of the music, you can easily customize the light effects to suit your preference by simply pressing the Light button. Make any gathering more memorable with these visually stunning light effects that will elevate the atmosphere
  • [Everything You Need] The package includes 1 waterproof Bluetooth speaker (Item Dimensions D x W x H: 7.87"D x 2.76"W x 2.81"H, Weight: 1.28lb), 1 Type-C charging cable, and a quick start guide, all backed by lifetime technical support. The built-in microphone allows for hands-free phone calls and you can also play music from other devices using the AUX jack (not included). It's a perfect gift for men and women. It is also suitable as white elephant gifts for adult, stocking stuffers for men and women, Christmas gifts,birthday gifts, mothers day gifts,fathers day gifts,Valentine's Day,mens gifts,and various anniversary gifts for him.
  1. From the project root, run ng add @angular/pwa.
  2. Confirm that the command added the service-worker package, the build configuration, and the registration code. Review the generated ngsw-config.json file.
  3. Build the app for production with ng build. Service workers are active only in production builds, so push testing should use a production build served locally or from HTTPS.

The guide recommends using current Angular and Angular CLI releases. The steps above do not depend on a particular release number, so check the guide for the version that matches your project.

Step 2: Check support and request a subscription

Inject SwPush and check isEnabled before you call any other method. Only ask for permission in response to a clear user action, such as a button labeled “Turn on order updates.” Asking on page load tends to produce refusals that are hard to reverse.

import { Injectable, inject } from '@angular/core';
import { SwPush } from '@angular/service-worker';

const VAPID_PUBLIC_KEY = 'your-server-public-key-here';

@Injectable({ providedIn: 'root' })
export class PushService {
  private swPush = inject(SwPush);

  async subscribe(): Promise<void> {
    if (!this.swPush.isEnabled) {
      // Show your non-push fallback, such as an in-app notification center or email opt-in.
      return;
    }
    try {
      const subscription = await this.swPush.requestSubscription({
        serverPublicKey: VAPID_PUBLIC_KEY,
      });
      await fetch('/api/push/subscriptions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(subscription),
      });
    } catch (err) {
      // The user denied permission, or the subscription could not be created.
      console.warn('Push subscription was not created', err);
    }
  }
}

The requestSubscription() call prompts for permission and resolves to a browser PushSubscription. The /api/push/subscriptions endpoint in this example is hypothetical and stands in for your own server route. The sample uses the placeholder string only to show where the key goes. Replace it with your real public VAPID key and never put the private key in client code.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Anker soundcore 2 Portable Bluetooth Speaker, 24-Hour Playtime, IPX7
  • Outdoor-Proof Speaker: Portable design with IPX7 waterproof protection to safeguard against splashes, waves, and water vapor. Get incredible sounds at home, on camping trips, or for outdoor adventures.
  • 24H Non-Stop Music: With Anker's world-renowned power management technology and a 5,200mAh Li-ion battery, the soundcore 2 speaker delivers a full day of great sound.
  • Powerful Sound: The speaker features 12W power with enhanced bass from dual neodymium drivers. An advanced digital signal processor ensures pounding bass and zero distortion at any volume.
  • Intense Bass: Our exclusive BassUp technology and a patented spiral bass port boost low-end frequencies to make the beats hit even harder. The soundcore 2 speaker delivers vibrant audio for home theater nights, beach parties, and sitting around a campfire.
  • Grab, Go, Listen: A classic design refined with simple controls and effortless portability. Easy to use and take anywhere, and supports wireless stereo pairing.

Handle refusal and unsupported browsers

The subscription request is rejected when the user denies permission, when the browser blocks notifications, or when the Push API is unavailable. Treat each of these as a normal outcome. A product that breaks when push is refused is a bug. Offer a useful alternative, such as an in-app notification list that the user can check, and do not repeatedly prompt users who have already refused.

Step 3: Store the subscription on your server

The object you post is a serialized PushSubscription. It contains an endpoint URL and encryption keys that your server needs in order to send a message to that browser. Store it with the user’s account, and make sure the endpoint can be removed when a browser reports that the subscription has expired or has been revoked. Angular’s example stops at this handoff. Sending the push, retrying failed deliveries, and cleaning up stale subscriptions are server responsibilities.

Step 4: Send a payload and handle the click

Payload shape

A push payload must contain a notification object. Angular’s documentation lists title as the only required property, so the minimum valid payload is short:

Rank #3
Sale
JBL FLIP 5, Waterproof Portable Bluetooth Speaker, Black, Small
  • Wireless Bluetooth streaming
  • 12 hours of playtime
  • IPX7 waterproof
  • Pair multiple speakers with party boost
  • Premium JBL sound quality
{
  "notification": {
    "title": "Order shipped",
    "body": "Your package left the warehouse today.",
    "data": {
      "onActionClick": {
        "default": { "operation": "focusLastFocusedOrOpen", "url": "/orders/1042" }
      }
    }
  }
}

Click behavior is configured through onActionClick. Angular’s push guide describes options for opening or focusing a page, navigating within the app, or sending a simple GET request. Set the URL deliberately. Relative URLs are resolved against the service-worker registration scope where that applies, so an absolute path such as /orders/1042 is easier to reason about than a bare relative path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Listen for messages and interactions

Use the SwPush observables to react inside the app. The messages observable receives incoming push data while the app is open. The notificationClicks observable reports clicks, and it is the right place to route the user to the right screen if your onActionClick configuration is not enough. Interactions such as closing a notification are also reported through SwPush; check the API reference for the exact members in your Angular version before depending on them.

import { Injectable, inject } from '@angular/core';
import { SwPush } from '@angular/service-worker';
import { Router } from '@angular/router';

@Injectable({ providedIn: 'root' })
export class PushListener {
  private swPush = inject(SwPush);
  private router = inject(Router);

  start(): void {
    this.swPush.notificationClicks.subscribe(({ notification }) => {
      const target = notification.data?.orderId
        ? `/orders/${notification.data.orderId}`
        : '/';
      this.router.navigateByUrl(target);
    });
  }
}

Choosing Angular SwPush or Firebase Cloud Messaging

Firebase Cloud Messaging (FCM) is a separate, documented web path. It uses Firebase’s client SDK, its own permission flow, and its own delivery service. It is not a plug-in for SwPush, so pick one integration rather than mixing them by default.

Rank #4
Portable Bluetooth Speaker Gift Ideas: Outdoor Travel Essentials Waterproof
  • Compact and Powerful Design: Engineered with premium craftsmanship, this portable speaker features a space-saving form measuring a mere 2.99 inches (7.6 cm) in width and length, and 4.25 inches (10.8 cm) in height. Ultra-lightweight at just 0.582 lbs (264g), it slips effortlessly into any bag. Driven by a robust 20W peak power, it delivers immersive audio with punchy bass and crisp highs, while its 15W continuous output ensures crystal-clear sound for indoor relaxation or outdoor adventures
  • 【IPX5 Waterproof – Beach, Pool & Outdoor Adventures】Built for everyday outdoor fun, this portable Bluetooth speaker features IPX5 waterproof protection to handle splashes, light rain, and wet environments. Take it to the beach, pool, campsite, backyard, patio, or shower for music wherever you go. A reliable companion for travel, camping, outdoor gatherings, and weekend adventures
  • 【Portable Companion – Travel, Camping & Everyday Use】At just 0.58 lbs, this compact wireless speaker easily fits into a backpack, tote, suitcase, or travel bag. The built-in lanyard makes it easy to carry or hang from a backpack, bike, hook, or shower caddy. Great for road trips, beach days, camping trips, dorm rooms, home offices, and relaxing at home
  • 【Dynamic Lights – Create the Right Mood Anywhere】Dynamic LED lights add colorful visual effects to your favorite music, bringing extra energy to parties, gatherings, and everyday listening. Use it in the bedroom, dorm, backyard, patio, campsite, or party space. A fun choice for Halloween music, movie nights, sleepovers, game nights, and outdoor hangouts
  • 【15W HD Sound & 15H Playtime – Music for Every Moment】Powerful 15W HD sound delivers clear, enjoyable audio for music, podcasts, games, and more. With up to 15 hours of playtime, enjoy your playlist during travel, beach trips, camping, pool days, backyard gatherings, or a relaxing night at home. Keep the music going without frequent recharging
Decision point Angular SwPush Firebase Cloud Messaging web
Client API Angular service-worker API with SwPush observables (SwPush reference) Firebase Messaging JavaScript API inside a Firebase app setup (FCM web guide)
Service worker Angular’s service worker, registered by ng add @angular/pwa A firebase-messaging-sw.js file unless an existing worker is configured for the integration
Recipient identity The browser PushSubscription, which your server stores and uses to send Firebase installation identifiers used to designate recipients
Sending messages Your own backend, using the VAPID key pair Firebase delivery services, configured through the Firebase project
Transport requirement HTTPS, with localhost as the development exception HTTPS, because the web SDK is supported on pages served over HTTPS

Choose SwPush when you already run a backend that can send Web Push messages and you want the push logic to live in your own infrastructure. Choose Firebase when your team already uses Firebase services and wants Google’s delivery infrastructure. Neither documentation set establishes that one approach is universally better, and neither provides performance or cost comparisons.

If you choose Firebase, follow its web setup as a separate integration. Its messaging service-worker file and Angular’s service worker both control the page’s worker, so combining them requires deliberate configuration. Do not assume they will coexist without checking how the registration scope and file names are set up.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Limits of Angular’s built-in service worker

Angular’s overview describes its service worker as a basic caching utility. The documentation states: “The Angular Service Worker is a basic caching utility for simple offline support with a limited featureset.” It adds: “We will not be accepting any new features other than security fixes.”

Best Value
JBL Charge 6 - Portable Waterproof & DropProof Bluetooth Speaker (Black)
  • Powerful JBL Pro Sound with AI Sound Boost: How does the already great JBL Charge sound profile get even better? It helps that we have some of the best engineers in the game retooling our kit to deliver our most realistic sound reproduction yet. Surprisingly rich, powerful bass and crisp higher frequencies give the Charge 6 a whole new reason to humble brag. We also added our new proprietary tech, AI Sound Boost, which analyzes your music in realtime to deliver maximum acoustic performance with less distortion. It's like our own little audio genie in every Charge 6. All-in-all, the Charge 6 comes out swinging, with bigger booms and baps, cleaner belts and claps, and everything in between.
  • Up to 28 hours of playtime + Fast charge: Keep the mood alive for 24 hours on a single charge - and when we really need to squeeze some extra juice out of our jubilee, or another dance with our darling, we can get an extra 4 hours with JBL Playtime Boost. No need for the low battery blues when you can give your Charge 6 a quick boost! 10 minutes on the charger gets you up to 150 minutes of playtime.
  • Multi-speaker connection by Auracast: Wouldn't it be great to share the vibes with our tribe? Now we can. With Auracast, we can effortlessly stereo pair two Charge 6 speakers for a wider sound stage & connect multiple Auracast-enabled JBL speakers to cover more ground with the same playlist.
  • Waterproof, dustproof, and drop-proof: Have you ever dropped your speaker, had it roll down a dusty hill and land in a lake? No? Well, believe it or not, it happens. So, we built the JBL Charge 6 to be as life-proof as they come. On top of our legendary water-proof and dust-proof design (an industry-leading IP68*, BTW), we've also made sure that if you drop it from 1-meter onto your concrete floor, it'll keep kicking. But please, don't go throwing your speaker around just to flex on your friends. Throw parties instead. *Based on lab test conditions for submersion in up to 1.5 meters of freshwater for up to 30 minutes.
  • Sturdy handle strap: Now we can carry our sound our way with a handy removable handle strap - for those of us who love to make it from the car to the house in one trip no matter the cost.

In practice, this means you should use SwPush for the behavior it documents, and evaluate native browser APIs or a dedicated messaging integration if your project needs capabilities outside that scope. Treat the statement as a current constraint of the documentation, and check the overview page for changes before you plan a long-lived feature around it.

Checklist before release

  • The production site is served over HTTPS, and localhost is used only in development.
  • The permission request runs from a user action, and refusal leaves the page usable.
  • The app checks SwPush.isEnabled and shows a fallback where push is unavailable.
  • The server stores each subscription and removes ones that the browser reports as expired.
  • Every payload includes a notification object with a title.
  • Click targets are absolute, app-owned paths, and each one has been tested in a production build.

Push delivery depends on the browser, the operating system, and the user’s notification settings. Test on each browser your users actually use before you rely on it.

Quick Recap

SaleBestseller No. 3
JBL FLIP 5, Waterproof Portable Bluetooth Speaker, Black, Small
JBL FLIP 5, Waterproof Portable Bluetooth Speaker, Black, Small
Wireless Bluetooth streaming; 12 hours of playtime; IPX7 waterproof; Pair multiple speakers with party boost
$89.95
Bestseller No. 5
JBL Charge 6 - Portable Waterproof & DropProof Bluetooth Speaker (Black)
JBL Charge 6 - Portable Waterproof & DropProof Bluetooth Speaker (Black)
. But, of course, in order for it to work, you need a compatible lossless audio source*.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.