Dev.to WebDev 🛠 Dev 👁 0 📖 6 min read

A second hidden modal ate my Buy button, and my checks looked in the wrong places for four days

I run a small AI song generator on Next.js 14. Free users get one song. After that, a pay modal offers song packs, and each "Buy" button is a plain link to a Stripe payment page. The site is small, so begin_checkout in

I run a small AI song generator on Next.js 14. Free users get one song. After that, a pay modal offers song packs, and each "Buy" button is a plain link to a Stripe payment page.

The site is small, so begin_checkout in Google Analytics was never a big number, just a steady trickle. From November 6 it was zero, and stayed there. People still reached the paywall. Nobody clicked Buy, or so the numbers said.

It took four days to find the cause. The cause was small. The useful lesson was why my checks kept missing it.

What I checked first, and why it all came back fine

A sudden drop to zero looks like something broke on the payment side, so that is where I looked:

  • Stripe account and charges: fine, no failed payments.
  • The four payment links: active, all returned 200.
  • The webhook endpoint: enabled, and fulfilment had worked for the last real purchases.
  • Recent deploys: nothing that touched the pay modal or the buy links.
  • Traffic: sign-ups and paywall views per day looked normal.

Every check passed because every check started at Stripe. Nothing reached Stripe at all. The break was one step earlier, in the browser, between the modal opening and the link being followed.

What found it was the dull test: open the site on a phone-sized browser as a logged-in user with zero credits, let the pay modal open, tap "Buy 10 songs". The modal closed. No Stripe page. No error in the console.

Several modals, one boolean

The pay modal is a component called PayModal, built on Headless UI's Dialog (v1.7). Its open state lives in shared React context, so any part of the page can open it:

const {showPayModal, setShowPayModal} = useCommonContext();

return (
  <Transition.Root show={!!showPayModal} as={Fragment}>
    <Dialog as="div" className="relative z-30" onClose={setShowPayModal}>
      {/* packs, Buy links to Stripe */}
    </Dialog>
  </Transition.Root>
);

Over a few months, four components started rendering their own <PayModal />: the song generator form, the gift song form, the audio player and the "My songs" page. Each needed "open the pay modal" and the easy way was to drop the component in. They are never all on one page, but the main pages have at least two: the home page has the generator form plus the player of an example song, a song page has two players, and the birthday song page has a player per example song plus the gift form.

They all read the same showPayModal. So when one part of the page set it to true, every mounted copy opened at once: two or more identical dialogs stacked on top of each other. You only ever see the top one.

Why a tap on Buy closed the modal

Headless UI dialogs close on outside clicks. Each Dialog registers document-level capture listeners. On desktop that is a click listener; on mobile it handles touchend instead. When a pointer event ends on an element that is not inside this dialog's panel, the dialog calls onClose.

Sibling dialogs are not a stack. They were not nested in each other's React tree, so none of them knew the others were dialogs. For dialog #2 (and #3 and up, on pages with more), the panel of dialog #1 is simply "outside".

So a tap on Buy in the top dialog went like this:

  1. The top dialog sees a tap inside its own panel and does nothing.
  2. The other copies see a tap outside their panels and call onClose, which is setShowPayModal(false). Headless UI's outside-click handler can also call preventDefault() on that event, which cancels the link's default action.
  3. That is the same shared boolean, so the top dialog closes too.
  4. With the event cancelled and the modal gone, the browser never navigates to Stripe, and the onClick that sends begin_checkout never runs.

No exception, no failed request, no log line. From the outside it looks exactly like a user who opened the modal, thought about it and left.

I still can't say which change turned this from a latent bug into a total one. Several instances had existed for weeks while purchases came in. It doesn't matter much: once two dialogs can be open together, whether a click lands depends on timing and event order, and that can change with any re-render.

The fix: only the first mounted instance renders

I didn't want to change the four call sites and the shared context in a hurry while the site wasn't taking money. The smallest safe fix was to let every PayModal mount, but render only one of them:

const owners: string[] = [];
const subscribers = new Set<() => void>();
const notify = () => subscribers.forEach((f) => f());

function useIsPrimaryModal(id: string) {
  useEffect(() => {
    owners.push(id); notify();
    return () => {
      const i = owners.indexOf(id);
      if (i >= 0) owners.splice(i, 1);
      notify();
    };
  }, [id]);
  return useSyncExternalStore(
    (cb) => { subscribers.add(cb); return () => { subscribers.delete(cb); }; },
    () => owners[0] === id,
    () => false, // server render: nothing
  );
}

export default function PayModal(props) {
  const primary = useIsPrimaryModal(useId());
  // ...
  if (!primary) return null;
  return <Transition.Root show={!!showPayModal}>...</Transition.Root>;
}

useId gives each instance a stable id. A module-level list records mount order, and useSyncExternalStore re-renders the instances when the first one unmounts, so the next one takes over. On the server every instance renders nothing, which is fine for a modal that only opens after a user action.

The cleaner long-term design is one PayModal at the layout level and a openPayModal(reason) function in context. The hook was a 20-line change I could verify the same morning, and it stops the next copy that someone drops into a component from breaking checkout again.

Right after the deploy, the same phone-sized test opened the Stripe page on the first tap, and real purchases came back over the following days.

The analytics bug hiding behind it

The modal also sends a paywall_view event when it opens:

useEffect(() => {
  if (showPayModal) trackEvent('paywall_view', {reason});
}, [showPayModal]);

Every mounted instance sent it, so each view was counted once per instance: twice on the home page, more on pages with several players. My funnel showed far more people reaching the paywall than really did, so the paywall-to-checkout rate looked far worse than it was. That made "people just don't want to buy" a believable story, which is exactly the wrong story when the button is broken.

Now only the primary instance sends the event. Paywall numbers from before the fix can't be compared with numbers after it, and I wrote that down next to the chart so I don't trip on it in three months.

What changed besides the code

  • A real-browser purchase test runs after every deploy and once a day. Playwright with a test account at zero credits opens the pay modal on a phone viewport, taps Buy and checks that the Stripe checkout page loads with the right price. It never pays. If it fails, I get an urgent mail.
  • A watcher on the funnel itself. A small daily script compares checkout starts and payments with the previous 14 days. It would have flagged this on day one instead of day four.
  • Test from the user's side first. All my early checks went from Stripe backwards. The one that worked went from the user forwards. When a step in a funnel drops to zero, I now start by doing that step myself in a real browser, on the device most visitors use.

The bug cost about four days of sales on a small site. It could have been worse: the same pattern (shared open state, several dialogs mounted, outside-click to close) is easy to build with any headless dialog library, and it fails silently.

If you want to see the pay modal that now works on the first tap, it is on AISong.Fun, after your first free song.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.