320 words
2 minutes
A Case Study of Bugs Caused by Asynchronous setCookie Operations

A recent requirement: after login, blacklisted users must be blocked from the page and shown a notice.

This project doesn’t use a traditional username/password login. Instead, users subscribe to the software through the JD (Jingdong) service marketplace, and logging in happens via a button-triggered redirect combined with a setCookie operation. The details:

Login flow

The plan I initially agreed on with the backend was to check whether the token field exists in the cookie — no token means a blacklisted user — and then have the frontend show an overlay with the notice.

With this approach, since setCookie is asynchronous, several things can go wrong:

  1. Logic errors: because setCookie is async, the cookie may not be set yet by the time the blacklist check runs, so the check returns the wrong answer.
  2. Poor UX: users might see the page content before the cookie is set, and only then get hit with the blacklist notice — a jarring experience.
  3. Instability: async operations complete at unpredictable times, so the flow can’t be guaranteed to behave the same way every run.

To solve this, a few options:

  1. Loading screen: show a Loading state while the cookie is being set, so users never see the page before the cookie is ready.
  2. Delayed check: set a timer and re-check whether the cookie landed after a fixed delay; if not, prompt the user.
  3. Talk to the backend: have the backend return a flag on successful login instead of relying on the cookie.
  4. Backend-side detection: let the backend detect blacklisted users up front and redirect them to a /black route.

We went with option 4! Detecting blacklisted users on the backend avoids the whole class of async problems on the frontend and keeps both the UX and the logic correct.

In this setup, the backend decides whether a user is blacklisted and performs the redirect; the frontend simply follows the backend’s response, redirecting and passing parameters along. That simplifies the frontend logic considerably and makes the redirects and parameter passing reliable.

A Case Study of Bugs Caused by Asynchronous setCookie Operations
https://www.mihouo.com/en/posts/front/case-studies-on-issues-caused-by-asynchronous-setcookie-operations/
Author
Jia
Published at
2024-03-15
License
CC BY-NC-SA 4.0