RORK LABJP
CLOUD — Rork Max compiles native Swift on a fleet of cloud Macs, so you never download Xcode or need to own a MacPLATFORM — Rork Max targets iPhone, iPad, Apple Watch, and Vision Pro, and reaches games, widgets, and Live ActivitiesSHIP — Build in the browser, preview through a streaming simulator, install on device via QR code, and submit to the App Store without leaving RorkSPLIT — Regular Rork generates cross-platform apps with React Native and Expo. Reach for it to ship broadly and fast, and for Max when you need Apple-specific depthCREDIT — The free tier works out to roughly five prompts a week. It helps to budget the cost of trying something separately from the cost of finishing itPRICE — Rork Max sits on the $200/month Max plan, while regular Rork starts free with paid plans from $25/monthCLOUD — Rork Max compiles native Swift on a fleet of cloud Macs, so you never download Xcode or need to own a MacPLATFORM — Rork Max targets iPhone, iPad, Apple Watch, and Vision Pro, and reaches games, widgets, and Live ActivitiesSHIP — Build in the browser, preview through a streaming simulator, install on device via QR code, and submit to the App Store without leaving RorkSPLIT — Regular Rork generates cross-platform apps with React Native and Expo. Reach for it to ship broadly and fast, and for Max when you need Apple-specific depthCREDIT — The free tier works out to roughly five prompts a week. It helps to budget the cost of trying something separately from the cost of finishing itPRICE — Rork Max sits on the $200/month Max plan, while regular Rork starts free with paid plans from $25/month
Articles/Dev Tools
Dev Tools/2026-06-15Advanced

Keeping Login Alive in a Rork-Built Expo App — Preventing Token-Refresh Races with Single-Flight

Add login to the Expo app Rork generates and it works at first, but in production the 'I got logged out on my own' reports creep in. Most are token-refresh races. This covers a reliability design that single-flights refresh, stores tokens safely, and handles expiry correctly.

Expo156Authentication8TokensReliability2Rork525

Premium Article

About a week after shipping an app with login added, "I keep finding myself logged out" reports started trickling in. I could not reproduce it. My own device never logged me out, yet specific users were rejected over and over.

Lining up the logs, I found multiple requests starting a token refresh at the same instant: one invalidating the old token, the other overwriting storage with the now-invalidated token. A token-refresh race. Add login as-is to the Expo app Rork generates and this race stays hidden, then bares its teeth in production once users grow. Here I share a reliability design that keeps login alive.

Why it does not reproduce on your device

During development, operations are usually serial. Open a screen, press a button, see the result. Requests do not overlap. In production, though, when the app resumes, several screens fetch data at once and all the requests receive 401 at nearly the same time.

If each request then starts its own refresh, refreshes multiply simultaneously. Many auth backends rotate the refresh token on first use and revoke the old one, so the second and later refreshes fail holding an "already-used token." As a result, the freshly obtained new token gets overwritten by a late-arriving failure response, and the user is suddenly logged out.

It does not reproduce on your device because you are not overlapping requests. This kind of bug grows in proportion to user count and network slowness, so it is hardest to find right after launch. I myself passed App Store review with no issue, yet watched the tickets grow over the first week.

Single-flight to unify refresh

The core of the fix is this: no matter how many requests hit 401 at once, run the token refresh only once. Only the first to start refresh actually talks to the network; the rest wait and share its result. This is called single-flight.

let refreshPromise = null;
 
async function getFreshToken(refreshFn) {
  // If a refresh is already in flight, share and await that Promise
  if (refreshPromise) return refreshPromise;
 
  refreshPromise = (async () => {
    try {
      const tokens = await refreshFn();   // the actual refresh call runs once
      await saveTokens(tokens);
      return tokens.accessToken;
    } finally {
      refreshPromise = null;              // always release on completion
    }
  })();
 
  return refreshPromise;
}

The key is releasing in finally. Forget it and after one failed refresh refreshPromise lingers, leaving later refreshes returning the old result forever. I once forgot this release and created the worse bug of "log out once, never log in again."

Retry once on 401

Once single-flight yields a new token, retry the failed request with it exactly once. Unlimited retries loop infinitely when the token truly is revoked, so cap retries at one.

async function fetchWithAuth(url, options, deps) {
  let token = await deps.getStoredAccessToken();
  let res = await fetch(url, withAuth(options, token));
 
  if (res.status === 401) {
    token = await getFreshToken(deps.refreshFn);   // single-flight here
    if (!token) return res;                         // refresh itself failed = logout confirmed
    res = await fetch(url, withAuth(options, token)); // retry once only
  }
  return res;
}

Not pressing on when the refresh itself fails matters too. If the refresh token is genuinely revoked, no number of tries will pass. In that case, cleanly returning to the login screen makes behavior more predictable for the user.

Thank you for reading this far.

Continue Reading

What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.

WHAT YOU'LL LEARN
An implementation that prevents the race where multiple requests hit 401 at once and double-fire refresh, using single-flight
Criteria for balancing revocation and leak risk with refresh-token rotation and SecureStore storage
How clock skew and offline recovery cause 'spontaneous logout,' and the retry-and-grace design that cut my support tickets by about 80%
Secure payment via Stripe · Cancel anytime

Unlock This Article

Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.

or
Unlock all articles with Membership →
Share

Thank You for Reading

Rork Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

Related Articles

Dev Tools2026-04-24
Adding Sign in with Apple to Your Rork App — What Review Actually Requires and Where People Get Stuck
A practical walkthrough for adding Sign in with Apple to an existing Rork app. Covers the exact Guideline 4.8 requirements that reject Google/Facebook-only apps, the non-obvious parts of expo-apple-authentication, backend token verification with identityToken, and the account deletion requirement most tutorials skip.
Dev Tools2026-08-02
When Two-Character Queries Silently Return Nothing: Measuring Japanese Search Indexes in an Expo App
SQLite FTS5's trigram tokenizer returns zero rows for Japanese queries shorter than three characters, without raising anything. I benchmarked linear scan, a bigram inverted index, and FTS5 over a 20,000-item catalog to find the real threshold.
Dev Tools2026-07-30
What Renovate may bump in an Expo app, and what it must never touch
Turning on automated dependency updates in a Rork-generated app also hands Renovate the 123 packages Expo SDK 57 pins. Measured on 2026-07-30, six of them sit a full major version behind npm latest. Here is how to generate the ignore list from the SDK instead of maintaining it by hand.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →