Writing Web Push Notification Code With LLMs in November 2026: Ask for Permission After a Click, Store One Subscription per Device, and Delete the Ones That Come Back 410

Web push notifications look like a small feature: ask the browser for permission, save something on the server, send a message later. Ask an LLM for "push notifications for my web app" and you will get a service worker, a subscribe call, and a send function in a few seconds. The code usually runs. The problems show up a week later: the permission prompt fires on page load and most people block it forever, the server keeps one subscription per user and silently loses every device but the last one, and a pile of dead subscriptions makes every send slower and noisier.

This post walks through how to get an LLM to write web push code you can actually ship, using the standard Push API, the Notifications API, and VAPID keys. The examples use plain browser JavaScript and the web-push package for Node.js, but the same rules apply in any server language.

How the pieces fit together

Before you prompt anything, make sure you and the model agree on the moving parts. Mixed-up terms are where most generated push code goes wrong.

  • Service worker: a script the browser keeps registered for your site. It receives the push event even when no tab is open and shows the notification.
  • Push subscription: what the browser gives you when the user agrees. It contains an endpoint URL on the browser vendor's push service plus two keys (p256dh and auth) used to encrypt the message. It belongs to one browser profile on one device, not to a user.
  • VAPID keys: a key pair that identifies your server to the push service. The public key goes to the browser when it subscribes; the private key stays on the server and signs every send.
  • Push service: run by the browser vendor. Your server sends an encrypted message to the subscription's endpoint, and the push service delivers it to the device.

Put that list in your prompt. A model that knows a subscription is per device will design the storage correctly; a model that thinks it is per user will not.

A doorbell button beside a door

Like a doorbell, the permission prompt should only ring when the visitor chooses to press the button. Image: Doorbell button, Highwic by Bjankuloski06, CC BY 4.0, via Wikimedia Commons.

Rule 1: Ask for permission after a click, not on page load

The single most common thing generated code does is call Notification.requestPermission() as soon as the page loads. That is bad for two reasons. First, people who have no idea why you want to notify them tend to click "Block", and once a site is blocked the browser will not show your prompt again; the user has to dig into site settings to undo it. Second, browsers push back on this pattern: some only allow the prompt in response to a user action, and others show a quieter prompt for sites that ask too eagerly.

Tell the model plainly: the permission request must run inside a click handler on a button that explains what the notifications are for. Something like this:

// Shown next to a sentence like:
// "Get a notification when someone replies to your post."
document.querySelector('#enable-replies').addEventListener('click', async () => {
  if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
    showMessage('This browser does not support push notifications.');
    return;
  }

  const permission = await Notification.requestPermission();
  if (permission !== 'granted') {
    showMessage('Notifications are off. You can turn them on in your browser settings.');
    return;
  }

  const registration = await navigator.serviceWorker.register('/sw.js');
  const subscription = await registration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY),
  });

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

  showMessage('Reply notifications are on for this device.');
});

Things to check in whatever the model writes:

  • Feature detection first. Not every browser supports the Push API in every context. On iPhone and iPad, for example, Safari only offers web push to sites the user has added to their Home Screen. Your UI should handle "not supported" without throwing.
  • Handle "denied" and "default" separately from "granted". If Notification.permission is already "denied", do not show the enable button as if it will work; show how to change the setting instead.
  • userVisibleOnly: true. Browsers expect every push to show a visible notification. Generated code that tries to use push for silent background syncs will not behave the way the model claims.
  • The VAPID public key format. applicationServerKey wants the raw key bytes, usually decoded from the URL-safe base64 string your key generator printed. Ask the model to include the small helper that converts it, and test it once by hand.

Rule 2: Store one subscription per device, keyed on the endpoint

The second classic mistake is a push_subscription column on the users table. The first time a user turns on notifications on their laptop and then on their phone, the phone overwrites the laptop and the laptop goes quiet without anyone noticing.

Ask for a separate table where each row is one subscription, and make the endpoint unique:

CREATE TABLE push_subscriptions (
  id            BIGSERIAL PRIMARY KEY,
  user_id       BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  endpoint      TEXT NOT NULL UNIQUE,
  p256dh        TEXT NOT NULL,
  auth          TEXT NOT NULL,
  user_agent    TEXT,
  created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
  last_success_at TIMESTAMPTZ
);

Then make the save endpoint an upsert on endpoint, and take the user from the session, never from the request body:

app.post('/api/push/subscriptions', requireLogin, async (req, res) => {
  const { endpoint, keys } = req.body || {};
  if (typeof endpoint !== 'string' || !endpoint.startsWith('https://') ||
      !keys || typeof keys.p256dh !== 'string' || typeof keys.auth !== 'string') {
    return res.status(400).json({ error: 'Invalid subscription' });
  }

  await db.query(
    `INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth, user_agent)
     VALUES ($1, $2, $3, $4, $5)
     ON CONFLICT (endpoint) DO UPDATE
       SET user_id = EXCLUDED.user_id, p256dh = EXCLUDED.p256dh,
           auth = EXCLUDED.auth, user_agent = EXCLUDED.user_agent`,
    [req.user.id, endpoint, keys.p256dh, keys.auth, req.get('user-agent') || null]
  );
  res.status(204).end();
});

Why the upsert updates user_id: if two people share a browser profile and the second one logs in and turns notifications on, the device should now notify the second person, not the first. Decide this on purpose and write it down; the model will not think about shared devices unless you ask.

Also ask for the two flows the model usually skips:

  • Unsubscribe. A "turn off notifications on this device" button that calls subscription.unsubscribe() in the browser and deletes the matching row on the server.
  • Logout. Decide whether logging out should remove this device's subscription. For most apps it should, otherwise a logged-out browser keeps getting the previous user's notifications.

Rule 3: Delete subscriptions that come back 404 or 410

Subscriptions die all the time: the user clears site data, uninstalls the browser, revokes permission, or the browser rotates the subscription. Your server finds out only when it sends. The push service answers with an HTTP status, and the two you must act on are 404 Not Found and 410 Gone: that subscription is no longer valid and should be deleted.

Generated send code tends to wrap everything in one try/catch that logs and moves on. Ask instead for code that reads the status code and acts on it:

const webpush = require('web-push');

webpush.setVapidDetails(
  'mailto:alerts@example.com',
  process.env.VAPID_PUBLIC_KEY,
  process.env.VAPID_PRIVATE_KEY
);

async function sendToUser(userId, message) {
  const { rows } = await db.query(
    'SELECT id, endpoint, p256dh, auth FROM push_subscriptions WHERE user_id = $1',
    [userId]
  );

  const payload = JSON.stringify(message);
  await Promise.all(rows.map(async (row) => {
    const subscription = { endpoint: row.endpoint, keys: { p256dh: row.p256dh, auth: row.auth } };
    try {
      await webpush.sendNotification(subscription, payload, { TTL: 60 * 60 });
      await db.query('UPDATE push_subscriptions SET last_success_at = now() WHERE id = $1', [row.id]);
    } catch (err) {
      if (err.statusCode === 404 || err.statusCode === 410) {
        await db.query('DELETE FROM push_subscriptions WHERE id = $1', [row.id]);
      } else if (err.statusCode === 429) {
        // The push service is rate limiting us; retry later, honoring Retry-After if present.
        throw err;
      } else {
        console.error('push send failed', { id: row.id, status: err.statusCode });
      }
    }
  }));
}

A few details worth checking in review:

  • Never log the full endpoint and keys together. Together they are enough to send notifications to that device. Log the row id instead.
  • Set a TTL on purpose. The TTL tells the push service how long to hold the message if the device is offline. A "your code is 482913" message is useless after ten minutes; a weekly digest can wait a day. Zero means "deliver now or drop it".
  • Keep payloads small. Push messages are encrypted and have a size limit set by the push service, on the order of a few kilobytes. Send a short title, body, and URL, not a whole record. If the notification needs more data, have the service worker fetch it.
  • Send from a background job. Sending to every device of every follower inside the request that created a post makes that request slow and fragile. Put sends on a queue and let a worker do them, with retries for 429 and 5xx answers.
A restaurant guest pager

Each restaurant pager is one device with its own number, just like each push subscription. Hand back the ones that stop working. Image: Restaurant pager - Gott's Roadside - 2012 by star5112, CC BY-SA 2.0, via Wikimedia Commons.

The service worker: show something, and open the right page

The service worker code is short, which is exactly why it is easy to get subtly wrong. Ask the model for this shape and check each line:

// sw.js
self.addEventListener('push', (event) => {
  let data = { title: 'New activity', body: '', url: '/' };
  try {
    if (event.data) data = { ...data, ...event.data.json() };
  } catch (e) {
    // Bad payload: still show something rather than nothing.
  }

  event.waitUntil(
    self.registration.showNotification(data.title, {
      body: data.body,
      icon: '/icons/notify-192.png',
      tag: data.tag,            // same tag replaces an older notification
      data: { url: data.url },
    })
  );
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  const target = new URL(event.notification.data?.url || '/', self.location.origin);
  if (target.origin !== self.location.origin) return; // only open our own pages

  event.waitUntil((async () => {
    const windows = await clients.matchAll({ type: 'window', includeUncontrolled: true });
    for (const w of windows) {
      if (w.url === target.href) return w.focus();
    }
    return clients.openWindow(target.href);
  })());
});

What to look for:

  • event.waitUntil around showNotification. Without it the browser may stop the service worker before the notification appears.
  • Always show a notification for every push. Code that returns early on a malformed payload breaks the "user visible" expectation. Fall back to a generic message.
  • Use tag for things that update. Five "3 new replies", "4 new replies" notifications are noise; one that gets replaced is useful.
  • Check the click URL. The payload comes from your server, but treat it like any other input and only open pages on your own origin.
  • Remember the service worker is cached. When you change sw.js, browsers pick up the new version on their own update schedule. Do not serve it with a long cache lifetime, and test an update on a real device before relying on new behavior.

A prompt that gets you most of the way

Here is a prompt you can adapt. It front-loads the decisions instead of hoping the model guesses them:

I'm adding web push notifications to a Node.js (Express) + Postgres app.
Use the standard Push API, a service worker at /sw.js, VAPID keys from
environment variables, and the web-push npm package on the server.

Requirements:
- Notification.requestPermission() only runs inside a click handler on an
  "Enable reply notifications" button. Handle unsupported browsers and an
  already-denied permission with a clear message.
- A push subscription is per device. Store them in a push_subscriptions table
  with a UNIQUE endpoint; upsert on endpoint; take user_id from the session.
- Provide unsubscribe (browser + server) and remove this device's
  subscription on logout.
- sendToUser(userId, {title, body, url, tag}) sends to every subscription,
  deletes rows on 404/410, rethrows on 429 so the job queue retries, and
  never logs endpoint+keys together. Set TTL explicitly.
- Service worker: always show a notification inside event.waitUntil, use tag,
  and on click focus an existing tab or open the URL only if same-origin.
Write the code, then list anything you were unsure about.

The last line matters. Asking the model to list its own uncertainties often surfaces exactly the spots you need to check against the documentation, such as the key conversion helper or how a particular browser behaves.

How to test it before users do

  1. Generate VAPID keys once and keep them. The web-push package can generate a pair. If you rotate the keys later, existing subscriptions were created with the old public key and will stop working, so treat a rotation as "everyone resubscribes".
  2. Subscribe from two browsers as the same user. Send one message and confirm both devices get it. This is the test that catches the one-column-on-users bug.
  3. Kill a subscription on purpose. Unsubscribe or clear site data in one browser, send again, and confirm the server got a 404 or 410 and deleted the row.
  4. Test with the tab closed. Close every tab for your site and send a message. If nothing appears, look at the service worker, not the server.
  5. Click the notification. Confirm it focuses an existing tab when one is open and opens the right page when none is.
  6. Try a denied permission. Block notifications in site settings and make sure your UI explains what happened instead of showing a broken button.
  7. Test on the phones your users have. Mobile behavior differs between browsers and operating systems, and on iOS the Home Screen requirement changes the whole flow. Desktop testing alone will not tell you what your mobile users see.

Respect the user's attention

The technical part is the easy half. The other half is not abusing the channel. Let people choose categories ("replies", "mentions", "weekly summary") instead of one all-or-nothing switch, keep a settings page that lists the devices that are subscribed, and send only what someone would be glad to be interrupted for. A user who turns off notifications at the operating system level is much harder to win back than one who unticks a single category on your settings page.

Checklist

  • Permission is requested only from a click on a button that explains the benefit.
  • Unsupported browsers and denied permission get a clear message.
  • Subscriptions live in their own table, one row per device, unique on endpoint, user taken from the session.
  • Unsubscribe and logout remove the device's subscription.
  • Sends run from a background job, set a TTL, and keep payloads small.
  • 404 and 410 delete the subscription; 429 and 5xx retry later.
  • Endpoints and keys are never logged together.
  • The service worker always shows a notification inside waitUntil and only opens same-origin URLs on click.
  • You tested two devices, a dead subscription, a closed tab, and a real phone.

An LLM can write all of this quickly, but only if you tell it the rules up front. Give it the per-device model, the permission rule, and the cleanup rule, and review the output against this list before you ship.

Comments

Popular posts from this blog

Grok Bot - a step closer to AGI

Tencent Hy4 Preview: Open 770B MoE Built for Real Work

Structured Outputs and Constrained Decoding for Reliable LLM APIs in Production (September 2026)