Case file 09Frontend8 min read

Ten copies of one login popup

A spinner stuck on 'Connecting…' led to ten copies of the same OAuth popup code, replaced by one shared hook.

Read by an AI voice of Sajib. Words light up as he reads.

One day QA reported a bug on our onboarding page. They clicked Connect on Instagram, a login popup opened, and they closed it without logging in. The Instagram card stayed on “Connecting…” with a spinner until they reloaded the page.

The product is a social media management tool. Users connect accounts like Facebook, Instagram, TikTok, LinkedIn, YouTube, X and Pinterest, and also Canva, Google Drive and Google Calendar. Each connection opens a login popup.

The bug looked small, but the cause was that the same popup code existed in ten copies. This article is about how copies like that drift apart and how to replace them with one shared hook.

How the popup works

These connections use OAuth. OAuth is a standard way for a user to let our app use their account on another site, without giving us their password. The user logs in on the other site and approves access, the site gives our app a code, and our backend exchanges that code for a token.

We do this in a popup. A popup is a small browser window that our page opens with window.open(). The steps look like this:

  1. Our app asks our backend for an authorization URL.
  2. The app opens that URL in a popup.
  3. The user logs in and approves access on the other site.
  4. The other site sends the popup back to a callback page on our own domain.
  5. The callback page sends a message to our main page with postMessage. This is a browser function that lets two windows send messages to each other.
  6. Our main page receives the message and updates the card.

The main page also checks once a second whether the popup has been closed. This is called polling. If the user closes the popup, the page should notice and reset the card.

Fig. 9.1 · Six steps for a happy path. Many more ways to stop in the middle.

What I suspected first

My first suspect was that polling check. Our popups go to instagram.com and facebook.com. Those sites send a security setting called Cross-Origin-Opener-Policy (COOP). Some COOP settings cut the connection between our page and the popup. If that happened, our page might never see that the popup was closed.

That would have explained everything, so before changing any code I tested it with the exact URLs our backend creates, in both Chromium and WebKit. Both sites use a COOP setting that keeps the connection, and our page saw the close correctly.

The polling check worked, so the problem was somewhere else.

The exits nobody was listening to

Next, I wrote down every way a login attempt can end. Success is only one of them; an attempt can also fail or stop in several ways.

The onboarding page kept its own “Connecting” flag. It cleared the flag only when the Instagram hook reported a success or a close. The hook reported a close from only one place in its code.

These four exits left the card stuck:

  1. The browser blocked the popup. The hook showed a “please allow popups” message, but it never told the page.
  2. The request for the authorization URL failed. The hook showed an error message, but again it never told the page.
  3. The user closed the popup after more than five minutes. Each copy stopped polling after five minutes, as a safety limit. If a user left the login screen open, came back later and closed it, the page never noticed.
  4. The popup opened behind the main window. On a second click, the browser reused the existing popup but did not bring it to the front. From the user’s side, nothing happened.

How ten copies grew apart

The ten hooks were written over about six months, one for each provider. Each new hook was copied from the last one that worked, and many of those copies were mine.

Copying is fast the first time, and the cost comes later. When someone reports a bug, the fix goes into the copy where the bug was found, and the other copies keep the bug.

Putting the ten hooks side by side showed exactly that:

  • The X hook had already removed the five-minute limit months earlier, after a slow login lost its success message. No other hook had that fix.
  • Only Pinterest and Google Calendar brought an open popup to the front on a second click. The other hooks asked for a new authorization URL instead. Our backend accepted both, so two open popups could both finish and save two tokens for the same account.
  • The Facebook hook never removed its message listener after a success. Earlier, I had traced one Facebook connection that called the token endpoint three times, partly because of old listeners that were still active. I fixed Facebook at that time, but I did not fix the pattern.
  • The Instagram hook ignored error messages from the callback page. The other nine showed them.

One thing every copy did right was check that a message came from our own domain before trusting it.

What actually worked

The fix was one shared React hook in place of the ten copies. It owns the whole life of a popup, from the request for the authorization URL to the final cleanup.

Each provider now describes only what is different about it: a label for messages, a unique window name, a prefix for the messages it expects, and a function that gets the authorization URL.

Two providers, TikTok and X, also use PKCE. PKCE (Proof Key for Code Exchange) is an extra safety step in OAuth. Before opening the popup, the app creates and saves a secret value called a code verifier. Later it sends the verifier to prove that the same app started and finished the login. These two providers have one small step that saves the verifier before the popup opens, and another that deletes it if the attempt stops.

The hook returns only two things: a start function and an isAuthorizing flag. The flag is true from the moment the app asks for the URL until the attempt ends, in any way.

The hook follows a few rules:

  • Every exit that is not a success goes through one function. Blocked, closed or failed, the flag becomes false and the caller is told once.
  • Pages show “Connecting” only from isAuthorizing. I deleted the onboarding page’s own flag, since a separate flag that every caller must remember to clear is how this bug happened.
  • There is no five-minute limit. Cleanup happens on success and on close instead.
  • After opening, the hook calls popup.focus() to bring the popup to the front.
  • Only one attempt runs at a time. A second click brings the open popup to the front instead of starting a new attempt.

After the change, each provider hook is a small config object and one line of code:

const LINKEDIN = { label: "LinkedIn", windowName: "linkedin-auth", messagePrefix: "LINKEDIN", getAuthUrl };
export const useLinkedInAuth = (opts?: PopupCallbacks) => useOAuthPopup(LINKEDIN, opts);

Together, the ten old hooks had 948 lines. Now the ten provider hooks have 257 lines, plus about 190 lines in the shared hook.

The tricky part: old attempts

Because polling runs once a second, a user can close a popup and click Connect again before the old polling check notices. Without care, the old check would then clean up the new attempt.

The fix is to check which popup each polling check belongs to, which is what the superseded line does in the simplified version below. The starting value is true while a new attempt is still getting its URL. If a newer attempt exists, the old check removes only its own listeners and stops:

const poll = setInterval(() => {
  if (!popup.closed) return;
  const superseded = currentPopup.current !== popup || starting.current;
  stopListening();          // always remove this attempt's own listeners
  if (superseded) return;   // a newer attempt owns the exit now
  currentPopup.current = null;
  abort();                  // report the exit once
}, 1000);
Fig. 9.2 · Before, four of these exits left the card on 'Connecting'. Now they all end the same way.

What the review found

A code review of the pull request found three gaps, all fixed within the hour. All three came from removing the five-minute limit, which had been cleaning up anything that lived too long. Without it, anything that outlived the popup would stay forever.

First, if the user went to another page in the app while the popup was still open, the polling and the message listener stayed active for the rest of the session. Now the hook also cleans up when its component is removed from the page.

Second, an old check could notice a close while a new attempt was still getting its URL, and report an exit for the new attempt. The starting check in the code above fixes that.

Third, the old hooks returned more than they needed to. When I changed the hook to return only start and isAuthorizing, it showed four places still using old fields. Two of them were old TikTok modules that skipped every guard and that nothing used anymore, so I deleted them.

Testing

The shared hook has 18 tests, using a fake popup and fake timers. They check that every exit that is not a success clears the flag, including a close long after five minutes. They also check that only one attempt runs at a time, that old attempts do not clean up new ones, and that messages from other providers are ignored.

A second, smaller set of tests runs once for each provider. It checks only what is different about that provider, such as the PKCE steps.

What I learned

Make a shared version on the second copy, not the tenth. By the time we added Pinterest there were already four copies, and one of them had a fix the others needed. That was the right moment to stop copying.

Let the code that owns a process also own its “in progress” state. When every caller must remember to clear its own flag, some exit will be forgotten.

Safety time limits can hide leaks. Removing the five-minute limit was right, but it exposed everything the limit had been cleaning up. Plan the cleanup before you remove the limit.

Test the obvious suspect before you build around it. The COOP theory sounded right, but a quick test showed it was wrong.

If I did this again, I would write down the list of exits before writing any code. The bug was a missing branch. With that list as the test plan, the four stuck exits would have been four failing tests.

Product names and some details are changed or left out. The engineering is real.