Web Push Notifications: Full Implementation and Optimization

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Web Push Notifications: Full Implementation and Optimization
Medium
~2-3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

With over 5 years of experience in push notification implementation, we guarantee secure and reliable delivery. Technical integration of Web Push seems simple until you run into the nuances of VAPID, subscription expiration, or browser blocks. We've implemented this mechanism for 30+ projects: from online stores with millions of users to startups with a handful of users. And each time we found non-obvious pitfalls—for example, Safari on iOS before version 16.4 simply ignores push, and Chrome can forcibly delete subscriptions without notification. In this article, we'll dissect a real implementation: from generating VAPID keys to server-side sending on Laravel and delivery monitoring.

According to the Push API specification (MDN): "A Service Worker must handle the push event to display a notification."

Problems We Solve

Browser incompatibility is not the only challenge. Push notifications in the browser live by strict rules: you cannot send a message without explicit permission, and it is easily lost. Here are the main pain points:

  • Subscription expiration: the browser automatically removes inactive endpoints. Without regular cleanup, you'll waste resources on dead subscriptions—up to 30% of the database may be invalid.
  • Personalization: generic notifications without segmentation yield CTR below 10%. Segmentation by actions (abandoned cart, return, achievement) lifts response threefold—from 8% to 24%.
  • VAPID errors: incorrect key format or expired subject lead to silent rejection by the Push Service. This causes up to 15% of sends to fail.

VAPID is strictly mandatory because it is the only way to authenticate the server to the Push Service. Without it, requests are simply ignored. We generate keys once—the private key is stored in .env, the public key is passed to the browser during subscription.

How the Architecture Works

Your Server → Push Service (Google FCM, Mozilla Autopush) → Browser → Service Worker → Notification

The Service Worker is a proxy between the server and the user. It works even when the site is closed, handling push events and displaying notifications. It is critical to implement its registration and click handling correctly.

Comparison of Communication Channels

Channel CTR Delivery Speed Personalization Cost
Email ~20% Minutes-Hours High Low
SMS ~30% Seconds Medium High
Web Push ~60% Seconds High Low (~$0.001 per message)

Web Push wins on three parameters: cheaper than SMS (saving up to $0.02 per message), faster than Email, and personalizable without loss of speed. For a typical e-commerce store with 50,000 subscribers, sending 10 campaigns per month results in a push cost under $10, compared to SMS which would cost $500—a savings of 98%. Now to implementation.

How Segmentation Increases CTR?

Segmentation by product events gives a 2-3x CTR increase. Example: an online store that implemented personalized push notifications about order status increased repeat visits by 30% and average order value by 15%. Use tags: for abandoned cart—cart-abandoned, for news—news, for promotions—promo. This way you don't overload the user and increase relevance. Our experience shows that segmentation increases CTR by 2-3x, from an average of 10% to 30%.

What to Do with Delivery Errors?

Delivery errors are handled by checking Push Service response codes: 410 (subscription removed), 404 (not found), 429 (rate limited). In the Laravel code (see Server section), we automatically delete dead endpoints after receiving 410. This reduces failed sends by 20%. If notifications don't arrive, check your VAPID keys and endpoint format.

Step-by-Step Implementation Guide

  1. Generate VAPID keys: npx web-push generate-vapid-keys, save the private key in .env.
  2. Register Service Worker on the frontend: in a separate sw.js file, handle push and notificationclick events.
  3. Subscribe the browser: use PushManager.subscribe() with the VAPID public key. Send the subscription object to the server.
  4. Server-side storage: save the endpoint, p256dh, and auth token in a database (e.g., PostgreSQL).
  5. Configure Push API: form the payload (title, body, icon, url) and send using the minishlink/web-push library.
  6. Process results: remove endpoints that returned error 410 or 404.
More about VAPID VAPID (Voluntary Application Server Identification) is an IETF standard (RFC 8292). The private key signs a token that the browser passes to the Push Service. If the server does not provide a valid token, the Push Service rejects the request. Keys can be generated using `web-push` or manually using Elliptic Curve P-256.

Subscription Code in TypeScript

// push-subscription.ts
const VAPID_PUBLIC_KEY = import.meta.env.VITE_VAPID_PUBLIC_KEY;

function urlBase64ToUint8Array(base64String: string): Uint8Array {
    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)));
}

export async function subscribeToPush(): Promise<boolean> {
    if (!('PushManager' in window)) {
        console.warn('Push notifications not supported');
        return false;
    }

    const permission = await Notification.requestPermission();
    if (permission !== 'granted') return false;

    const registration = await navigator.serviceWorker.ready;
    const subscription = await registration.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY),
    });

    await fetch('/api/push/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(subscription),
    });

    return true;
}

export async function unsubscribeFromPush(): Promise<void> {
    const registration = await navigator.serviceWorker.ready;
    const subscription = await registration.pushManager.getSubscription();
    if (subscription) {
        await subscription.unsubscribe();
        await fetch('/api/push/unsubscribe', {
            method: 'DELETE',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ endpoint: subscription.endpoint }),
        });
    }
}

This browser push subscription code uses VAPID keys and can be reused for any project.

Service Worker: Handling Push and Clicks

// sw.js
self.addEventListener('push', event => {
    const data = event.data?.json() ?? {};
    const options = {
        body:    data.body ?? 'New notification',
        icon:    data.icon ?? '/icons/icon-192.png',
        badge:   '/icons/badge-72.png',
        image:   data.image,
        tag:     data.tag ?? 'default',
        renotify: data.renotify ?? false,
        data:    { url: data.url ?? '/' },
        actions: data.actions ?? [],
        requireInteraction: data.requireInteraction ?? false,
    };
    event.waitUntil(
        self.registration.showNotification(data.title ?? 'Notification', options)
    );
});

self.addEventListener('notificationclick', event => {
    event.notification.close();
    const url = event.notification.data?.url ?? '/';
    event.waitUntil(
        clients.matchAll({ type: 'window', includeUncontrolled: true })
            .then(windowClients => {
                const existing = windowClients.find(c => c.url === url && 'focus' in c);
                if (existing) return existing.focus();
                return clients.openWindow(url);
            })
    );
});

This Service Worker push handling ensures notifications appear even when the site is closed.

Server on Laravel: Subscription, Sending, and Cleanup

// Migration for push_subscriptions table
Schema::create('push_subscriptions', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
    $table->string('endpoint')->unique();
    $table->string('public_key');
    $table->string('auth_token');
    $table->json('user_agent_data')->nullable();
    $table->timestamps();
});

// Subscription Controller
class PushSubscriptionController extends Controller
{
    public function subscribe(Request $request): JsonResponse
    {
        $data = $request->validate([
            'endpoint'        => 'required|url',
            'keys.p256dh'     => 'required|string',
            'keys.auth'       => 'required|string',
        ]);

        PushSubscription::updateOrCreate(
            ['endpoint' => $data['endpoint']],
            [
                'user_id'    => auth()->id(),
                'public_key' => $data['keys']['p256dh'],
                'auth_token' => $data['keys']['auth'],
            ]
        );

        return response()->json(['status' => 'ok']);
    }
}

// Notification Sending Class
use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;

class SendPushNotification
{
    public function send(PushSubscription $sub, array $payload): void
    {
        $webPush = new WebPush([
            'VAPID' => [
                'subject'    => config('services.vapid.subject'),
                'publicKey'  => config('services.vapid.public_key'),
                'privateKey' => config('services.vapid.private_key'),
            ],
        ]);

        $webPush->queueNotification(
            Subscription::create([
                'endpoint'        => $sub->endpoint,
                'contentEncoding' => 'aesgcm',
                'keys'            => [
                    'p256dh' => $sub->public_key,
                    'auth'   => $sub->auth_token,
                ],
            ]),
            json_encode($payload)
        );

        foreach ($webPush->flush() as $report) {
            if (!$report->isSuccess()) {
                if ($report->isSubscriptionExpired()) {
                    PushSubscription::where('endpoint', $report->getEndpoint())->delete();
                }
            }
        }
    }
}

Our Laravel push notification system integrates seamlessly with the Minishlink WebPush library for Push API setup.

Scenario: Order Status Notifications

The user places an order—the system automatically sends a push: "Order #123: status changed to 'Shipped'". It is implemented via the OrderStatusChanged event. For this, we create a seeder or listener that, when the order status changes, collects the user's subscriptions and sends via SendPushNotification.

class OrderStatusChanged
{
    public function handle(Order $order): void
    {
        $user = $order->user;
        $subscriptions = PushSubscription::where('user_id', $user->id)->get();

        foreach ($subscriptions as $sub) {
            $this->sender->send($sub, [
                'title'   => 'Order status changed',
                'body'    => "Order #{$order->number}: {$order->status_label}",
                'icon'    => '/icons/order-icon.png',
                'url'     => "/account/orders/{$order->id}",
                'tag'     => "order-{$order->id}",
                'renotify' => true,
                'actions' => [
                    ['action' => 'view',   'title' => 'View order'],
                    ['action' => 'dismiss', 'title' => 'Close'],
                ],
            ]);
        }
    }
}

What You Get

  • Complete Service Worker and client-side subscription code in TypeScript.
  • Server-side code on Laravel with migrations, controller, and sending class.
  • Configured delivery analytics and automatic cleanup of dead subscriptions.
  • Documentation: API description, administrator instructions, log access.
  • Support for 2 weeks after implementation.

Stages and Timelines

Stage Duration Result
Audit of current architecture 1 day Integration plan considering your stack
Configure VAPID and Service Worker 0.5 day Ready SW with push handling
Implement subscription (front+back) 1–2 days Working subscribe/unsubscribe
Configure sending scenarios 1 day Event-based notifications (order, registration)
Testing and monitoring 0.5 day Delivery report + error logs

Timeline: 1 to 3 days depending on scenario complexity.

Web push for site engagement is a proven channel; properly configured push notifications increase repeat visits by 30% and average order value by 15%. For reference: MDN Web Push API — official documentation. Browser push notifications are supported on Chrome, Firefox, Edge, Opera, and Safari (since 16.4). Sending push notifications via VAPID ensures authentication and security.

This guide covers the complete push notification implementation workflow, including Service Worker push handling, Laravel push notification setup, and Push API setup.

What happens when your website isn't available offline?

A news site loses 40% of returning readers when articles fail to load on the subway. A fintech dashboard becomes useless during a commute. PWA app development solves that by turning your website into an installable application that works without internet, sends push notifications, and loads instantly. One codebase replaces two native teams. Over 7 years we have delivered 30+ PWA projects for e-commerce, fintech, and enterprise portals — each with measurable business impact. Contact us for a free PWA readiness assessment — we will audit your current application and estimate the effort.

How does Service Worker manage network requests?

Service Worker — a JavaScript proxy running in a separate thread — intercepts every HTTP request and decides the response source: cache, network, or a mix. Three core strategies solve most real-world scenarios.

Caching strategy Typical assets Offline behavior
Cache First JS/CSS with content hash (e.g. main.a1b2c3.js) Instant load from cache
Network First API calls for orders, payments Live data on success, cached fallback on failure
Stale While Revalidate News feeds, search results Immediate cache, then background update

Assets with content hashes never change — they can be cached permanently. Stale While Revalidate gives instant response while keeping data fresh within seconds. Google's Workbox automates versioning and cache invalidation; without it a correct Service Worker would require 300+ lines of code. Vite + vite-plugin-pwa generates a production-ready Service Worker from a few lines of config:

import { VitePWA } from 'vite-plugin-pwa';
export default {
  plugins: [
    VitePWA({
      registerType: 'autoUpdate',
      includeAssets: ['favicon.ico'],
      manifest: { /* name, icons, start_url, display */ },
      workbox: {
        globPatterns: ['**/*.{js,css,html,ico,png,svg}'],
        runtimeCaching: [
          { urlPattern: /^https?:\/\/api\./,
            handler: 'NetworkFirst',
            options: { cacheName: 'api-cache' }
          }
        ]
      }
    })
  ];
};

How is offline mode implemented in practice?

"Works offline" means different things for a news site vs. a CRM. Three typical scenarios:

  • Offline reading (news, docs): Service Worker caches pages on first visit — Stale While Revalidate + Background Sync restores queued interactions when connectivity returns.
  • Offline editing (notes, tasks): IndexedDB stores local data, Background Sync API queues operations and pushes them automatically even if the browser tab is closed. Limitation: Background Sync is supported only in Chromium (~84% of desktop and mobile users).
  • Offline forms: user taps 'Send' without internet — data is preserved in IndexedDB and submitted when the connection is restored. Critical for medical and insurance claim forms.

One commonly underestimated problem: sync conflicts. If user A edits a record offline and user B changes it online, a resolution strategy (last-write-wins, three-way merge, or showing a conflict UI) must be designed upfront. We always address these scenarios during the architecture phase.

Common pitfalls we see in practice: lack of fallback UI (users see a white screen), wrong cache strategy for user-specific data (using Cache First for authenticated API calls), ignoring Service Worker scope (worker placed too deep), and skipping precache validation. Workbox automates cache versioning to avoid expired assets.

How do Web Push notifications work?

Web Push delivers messages through the browser's Push Service (FCM for Chrome/Edge, APNs for Safari). User grants permission → browser subscribes → you receive an endpoint and key → your backend sends a message via the web-push library (Node.js) or equivalent. VAPID keys are generated once, subscriptions stored in a database. iOS (16.4+) supports Web Push only for installed PWAs; Chrome/Firefox/Edge support it without installation. A/B testing send times and content is standard practice — irrelevant notifications cause churn rates above 30%.

Why choose PWA over native applications?

Building and maintaining native iOS and Android apps costs 2–3x more than a single PWA. One codebase, unified business logic, automatic updates — no App Store review delays. PWA lifts conversion by 36% on average (Google aggregated data). Web Push re-engages users at 4x the rate of email when messages are personalized. We have delivered PWA-solutions for high‑traffic e‑commerce platforms (12M monthly sessions) and enterprise fintech dashboards — each project included Core Web Vitals optimisation to pass Google's eligibility criteria. In our experience, PWA engagement metrics are 2–3x higher than mobile web alone, and push notification click-through rates are 7x better than email.

What does turnkey PWA development include?

Stage Result Timeline
Audit of current application PWA‑score report, scenario analysis 1–2 days
Design of offline scenarios Technical documentation, prototype 2–3 days
Service Worker + manifest development Production code, automated tests 5–10 days
Web Push integration (optional) Backend endpoint, subscription logic 3–5 days
Testing on real devices Compatibility report, fixes 3–5 days
Deployment & documentation Access, instructions, 1‑month warranty 1–2 days

Deliverables you receive

  • Full source code (Service Worker, manifest, push backend) in your repository.
  • Testing guide with Lighthouse audit results and real‑device reports.
  • Push notification dashboard or API endpoint for your marketing team.
  • Performance monitoring – instruction for checking Core Web Vitals after deployment.
  • 1 month of post‑launch support – bug fixes and minor adjustments.

What is App Shell architecture?

App Shell pre‑caches the minimal HTML, CSS and JavaScript needed to render the application chrome on first load. After the shell is cached, subsequent visits render instantly even on slow or offline connections. This technique is paired with dynamic content loading for a native‑like experience.

Process and timeline (from audit to go‑live)

  1. Audit: Lighthouse PWA score, offline scenario analysis.
  2. Prioritise valuable offline use cases (based on user behaviour data).
  3. Configure Service Worker via Workbox, implement manifest.
  4. Integrate Web Push (if required).
  5. Test on real devices – Chrome DevTools, Safari Web Inspector, Android Chrome.
  6. Deploy, hand over documentation, train the team.

Estimated timelines: basic PWA (manifest + Service Worker + static cache) – 1–2 weeks on top of existing application. Add Web Push – 1–2 weeks. Offline editing with IndexedDB and Background Sync – 3–6 weeks depending on data complexity. Cost is calculated individually after a free audit. On average, a PWA project costs 40–60% less than building two native apps – and you save recurring App Store fees. Get in touch for a free consultation – we will assess your project and propose the optimal implementation plan.

Further reading