Skip to content
Security Running · 6 min read

Supabase in React Native: Why Users Got Randomly Logged Out

A failed token refresh on weak network looked like "no session", so the app logged people out. Plus why past events kept showing as upcoming.

A colleague who uses a city app I maintain for a client sent me two complaints on the same day. First: the app kept logging her out, "randomly", with no pattern she could see. Second: events that were already over still showed up as upcoming.

Both sounded like server problems. Both were bugs in the mobile app. And both had the same shape: the app assumed something about time and state that only holds if the app is freshly opened on good Wi-Fi.

TL;DR: Supabase access tokens live 1 hour. When the app is opened after more than an hour, the client has to refresh the token first. On weak network that refresh fails, the library reports "no session", and my login gate treated that as "logged out". On top of that, in React Native the Supabase client does not auto-refresh unless you call startAutoRefresh() / stopAutoRefresh() yourself based on AppState, and the app never did. Fix: tie auto-refresh to AppState, and treat a network error during refresh as "unknown, retry", not "signed out". The stale events were the same class of bug: the list was filtered against "now" once, when the tab mounted, and the app then lived in the background for days.

The fix first: AppState-driven auto-refresh

This is what Supabase's React Native guide tells you to do, and what my app was missing:

// lib/supabase.ts
import { AppState } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createClient } from '@supabase/supabase-js';

export const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
  auth: {
    storage: AsyncStorage,
    autoRefreshToken: true,
    persistSession: true,
    detectSessionInUrl: false,
  },
});

// Register this exactly once, at module level, not inside a component.
AppState.addEventListener('change', (state) => {
  if (state === 'active') {
    supabase.auth.startAutoRefresh();
  } else {
    supabase.auth.stopAutoRefresh();
  }
});

autoRefreshToken: true alone is not enough on a phone. On the web the client can lean on browser visibility events to know when to refresh. In React Native there is no such thing, so the library's own docs spell it out: you start the refresh ticker when the app comes to the foreground and stop it when it goes to the background. Without that, nothing renews the token while the app is open, and nothing retries after one failed attempt.

It never showed up in testing, and in hindsight that's no surprise: open the app on good Wi-Fi, use it for a few minutes, close it. You never hit an expired token on a bad connection that way.

What actually happened on her phone

The server side was boring and correct. The auth service runs with the default token lifetime:

GOTRUE_JWT_EXP=3600

One hour, no forced session timeout. The refresh token itself is still valid for much longer, so a user who opens the app after a day should get a new access token silently.

The sequence on her phone:

  1. App not opened for more than an hour. Stored access token is expired.
  2. She opens the app. The client sees the expired token and tries to refresh it before handing out a session.
  3. The phone just woke up, signal is weak or the radio isn't fully up yet. The refresh request fails with a network error.
  4. The library returns no session (with an error attached). The refresh token is still sitting in storage, untouched.
  5. My login gate in the root layout looked at session, saw null, and redirected to the welcome screen.

That's why it felt random. It depended entirely on the signal at the second she opened the app. Good Wi-Fi at home: fine. Opening it outside with one bar: logged out.

The gate looked roughly like this:

useEffect(() => {
  if (!ready || loading) return;
  if (!session) {
    if (!PUBLIC_ROUTES.has(firstSegment)) router.replace('/welcome');
    return;
  }
  if (PUBLIC_ROUTES.has(firstSegment)) router.replace('/');
}, [ready, loading, session, firstSegment]);

Nothing wrong with the gate itself. The bug was in what fed it: "I couldn't reach the server" and "you are signed out" both ended up as session === null.

Separating "offline" from "signed out"

The fix in the session provider: a network error during refresh is not a logout. Keep the user in, retry, and only treat an explicit sign-out (or a real auth rejection) as logged out.

import { isAuthRetryableFetchError } from '@supabase/supabase-js';

async function loadSession() {
  const { data, error } = await supabase.auth.getSession();

  if (error && isAuthRetryableFetchError(error)) {
    // Network problem, not an auth decision. Keep the current state
    // and try again shortly.
    scheduleRetry(10_000);
    return;
  }

  setSession(data.session); // null here really means: no valid session
}

supabase.auth.onAuthStateChange((event, session) => {
  if (event === 'SIGNED_OUT') setSession(null);
  else if (session) setSession(session);
});

In my app the retry runs every 10 seconds and again whenever the app comes back to the foreground. A real sign-out still logs out immediately, same as before.

The rule I took away: a login gate needs three states, not two. "Signed in", "signed out", and "don't know yet". If you collapse "don't know" into "signed out", every flaky network moment becomes a forced logout.

Gotcha: register the AppState listener only once

The Supabase docs literally say "make sure you register this only once". If you put AppState.addEventListener inside a component, every remount adds another listener. Put it at module level next to createClient, or keep the subscription and call .remove() in the cleanup.

The second bug: yesterday's event as "next up"

The home tab has a tile with the next event from the city calendar. My first suspicion was the calendar API sending old events. I checked the live API directly: it wasn't. The server only returns events that haven't ended.

The real cause was on the phone again. The home tab and the personal tab stay mounted as long as the app process is alive. On a phone that can mean days in the background. The event list was loaded once when the tab opened and filtered against the current time once, at that moment. After that, nothing ever looked at the clock again. Open the app days later, the process is still alive, the tab never remounted, and the "next event" tile happily shows yesterday's event.

The fix in the calendar data hook:

  • Re-filter the list against the current time every minute and whenever the app comes back to the foreground.
  • Reload from the server if the last successful load is older than 30 minutes.
const [now, setNow] = useState(() => Date.now());

useEffect(() => {
  const tick = setInterval(() => setNow(Date.now()), 60_000);
  const sub = AppState.addEventListener('change', (state) => {
    if (state !== 'active') return;
    setNow(Date.now());
    if (Date.now() - lastLoadedAt.current > 30 * 60_000) reload();
  });
  return () => {
    clearInterval(tick);
    sub.remove();
  };
}, [reload]);

const upcoming = useMemo(
  () => events.filter((e) => e.endMs > now),
  [events, now],
);

Here the listener lives inside a hook, so it gets cleaned up with sub.remove(). Different situation from the auth listener above, which should exist once for the whole app.

Gotcha: "now" computed once is a cache you forgot about

Any Date.now() inside a useMemo with no time dependency is a snapshot. On the web, people reload pages often enough that you never notice. In a mobile app that the OS keeps alive for days, that snapshot gets old fast. Same family as the daylight saving time bugs on servers: code that silently assumes time stands still between two points.

Gotcha: no over-the-air updates means the fix waits for review

This app has no over-the-air updates set up. Everything above is native-bundle JavaScript, so users only got the fixes with the next store build (1.3.2), after Apple and Google review. Until then, the honest message to the colleague was: "Two bugs in the app. If the app was closed for over an hour and the network was weak when you opened it, it logged you out by mistake. And if it ran in the background for days, it didn't refresh the events. Both are fixed and come with the next update."

What I didn't verify

I wanted to read the auth server's logs to rule out the server actively rejecting refresh attempts. I didn't get to do that, so strictly speaking I can't prove there was zero server-side component. What I can say: the server config is default (1 hour tokens, no session timeout), the client code had a clear path from "network error" to "logged out", and that path matches the "random" pattern exactly. I also hadn't tested the fix on a real phone when it went into the build, only typecheck and lint.

If you run a Supabase-backed React Native app and your users say "it logs me out sometimes", check these two things before you touch the server:

  1. Is there an AppState listener calling startAutoRefresh() / stopAutoRefresh()?
  2. Does your auth gate distinguish a failed refresh from a real sign-out?

Both are a few lines. Both are invisible in testing on office Wi-Fi.

Retry logic has a cousin problem on the server side, by the way: when a retry repeats a side effect it shouldn't. I wrote about that in the idempotency bug that uploaded the same file 153 times. And if you like the "it was stale state the whole time" kind of bug, backups that silently died is the server version of the same lesson: check how old your data is, don't just check that it exists.


Related posts