Expo login tokens in AsyncStorage: move them to SecureStore
Login tokens in AsyncStorage are plain text, so move the Supabase session to expo-secure-store, which uses the iOS Keychain and the Android Keystore. Write a small storage adapter, pass it to supabase-js, and add a one-time migration so that no user must sign in again.
This guide shows how to find the problem, how to write the adapter, how to migrate old sessions, and what SecureStore does not protect. It is the mobile twin of the guide on JWTs in localStorage.
Why is AsyncStorage a bad place for a token?
AsyncStorage is a simple key-value store for React Native. It is made for settings and small cached data. It does not encrypt anything. The values are plain text in the data folder of your app.
This matters for a session. A Supabase session holds an access token and a refresh token. The access token is short-lived. The refresh token lasts much longer, and it gives a new access token. A person who copies the refresh token can act as the user until it is revoked.
These are the usual ways that a plain-text value leaves the device:
- A device backup. Device backups can include app data. A backup that is not protected can expose the files.
- A compromised device. Malware or a person with root access can read the app folder.
- A support log. An app that logs the full storage object sends the token to a log service.
The Rork security checklist lists this as a critical item. It also says that regeneration can bring the problem back, because generated auth flows often use AsyncStorage. The official Supabase React Native examples show AsyncStorage as a storage option. Many generated apps copy it.
A token in AsyncStorage is not a remote hole. The attacker needs access to the device or its backup. The fix is small, so do it.
How do I check where my session lives?
- Open the file that creates the Supabase client. It is often
lib/supabase.ts. - Find the
authoptions in the call tocreateClient. - Read the value of
storage.
A finding looks like this:
import AsyncStorage from "@react-native-async-storage/async-storage";
import { createClient } from "@supabase/supabase-js";
export const supabase = createClient(url, key, {
auth: {
storage: AsyncStorage,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: false,
},
});
If storage is AsyncStorage, the session is in plain text.
- Search the whole project for other uses:
grep -rn "AsyncStorage.setItem\|AsyncStorage.multiSet\|setItem(" --include="*.ts" --include="*.tsx" . | grep -v node_modules
- Read each match. A value that holds a token, a refresh token, a password, or an API key is a finding. A theme setting or a flag for the onboarding screen is not.
- For Firebase, check the persistence setting of the Auth module. Look for the same pattern.
How do I fix it now?
Do these steps in order.
- Install the packages.
npx expo install expo-secure-store @react-native-async-storage/async-storage
You need AsyncStorage for the migration only. You can remove it after the migration period.
- Create the adapter file from the next section.
- Pass the adapter to
createClient. - Test on a real device. Sign in, close the app, and open it again. The user must stay signed in.
- Ship the new version. Existing users move to SecureStore on first launch.
- Remove the migration code after most users have updated.
How do I write a SecureStore adapter for supabase-js?
The storage option needs an object with getItem, setItem, and removeItem. The methods can be async. The Supabase documentation shows a custom storage object with these three methods.
SecureStore has two limits that matter here.
- Key names. A key can contain letters, numbers,
.,-, and_. The Supabase key looks likesb-<project-ref>-auth-token. It fits. - Value size. The Expo documentation says that Expo sets no limit, but the platform can reject large values. Some older iOS versions refused values above about 2048 bytes. A Supabase session with user data or provider tokens can be larger.
The adapter below splits each value into chunks. It stores the number of chunks last, so a half-written value is never read.
// lib/secure-storage.ts
import * as SecureStore from "expo-secure-store";
const CHUNK_SIZE = 1500;
const OPTIONS: SecureStore.SecureStoreOptions = {
keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
};
const countKey = (key: string) => `${key}.n`;
const partKey = (key: string, i: number) => `${key}.${i}`;
async function readCount(key: string): Promise<number> {
const raw = await SecureStore.getItemAsync(countKey(key), OPTIONS);
return raw ? Number(raw) : 0;
}
export const secureStorage = {
async getItem(key: string): Promise<string | null> {
const count = await readCount(key);
if (count === 0) return null;
const parts = await Promise.all(
Array.from({ length: count }, (_, i) =>
SecureStore.getItemAsync(partKey(key, i), OPTIONS),
),
);
if (parts.some((p) => p === null)) return null;
return parts.join("");
},
async setItem(key: string, value: string): Promise<void> {
await this.removeItem(key);
const parts = value.match(new RegExp(`[\\s\\S]{1,${CHUNK_SIZE}}`, "g")) ?? [];
for (let i = 0; i < parts.length; i++) {
await SecureStore.setItemAsync(partKey(key, i), parts[i], OPTIONS);
}
await SecureStore.setItemAsync(countKey(key), String(parts.length), OPTIONS);
},
async removeItem(key: string): Promise<void> {
const count = await readCount(key);
await SecureStore.deleteItemAsync(countKey(key), OPTIONS);
for (let i = 0; i < count; i++) {
await SecureStore.deleteItemAsync(partKey(key, i), OPTIONS);
}
},
};
The option keychainAccessible sets when iOS lets the app read the value. The default is WHEN_UNLOCKED. The _THIS_DEVICE_ONLY variant does not move to a new device through a backup. If a background task must read the session, use AFTER_FIRST_UNLOCK instead.
Now use the adapter in the client:
// lib/supabase.ts
import "react-native-url-polyfill/auto";
import { AppState } from "react-native";
import { createClient } from "@supabase/supabase-js";
import { secureStorage } from "@/lib/secure-storage";
export const supabase = createClient(
process.env.EXPO_PUBLIC_SUPABASE_URL!,
process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY!,
{
auth: {
storage: secureStorage,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: false,
},
},
);
AppState.addEventListener("change", (state) => {
if (state === "active") supabase.auth.startAutoRefresh();
else supabase.auth.stopAutoRefresh();
});
The URL and the anon key are public values. Use the EXPO_PUBLIC_ prefix only for these. See the guide for a key in an iOS app.
How do I migrate existing sessions without a logout?
Users who already signed in have a session in AsyncStorage. If you swap the storage only, the new adapter finds nothing and the user must sign in again. Add a fallback to the adapter. It reads the old value once, moves it, and deletes the old copy.
// lib/secure-storage.ts (add)
import AsyncStorage from "@react-native-async-storage/async-storage";
export const migratingStorage = {
async getItem(key: string): Promise<string | null> {
const secure = await secureStorage.getItem(key);
if (secure !== null) return secure;
const legacy = await AsyncStorage.getItem(key);
if (legacy === null) return null;
await secureStorage.setItem(key, legacy);
const check = await secureStorage.getItem(key);
if (check === legacy) await AsyncStorage.removeItem(key);
return legacy;
},
setItem: (key: string, value: string) => secureStorage.setItem(key, value),
async removeItem(key: string): Promise<void> {
await secureStorage.removeItem(key);
await AsyncStorage.removeItem(key);
},
};
Pass migratingStorage as the storage option in the release that does the move. The code deletes the old copy only after it reads the new copy back and the values match. If the write fails, the user stays signed in and the old copy stays.
Also clean other tokens that your code wrote to AsyncStorage. List the keys once and remove the ones that hold credentials:
const keys = await AsyncStorage.getAllKeys();
const old = keys.filter((k) => /token|session|auth|password/i.test(k));
await AsyncStorage.multiRemove(old);
Run this only for keys that you know. Do not remove keys that other libraries own.
Caution: Test the migration on a device that has an old build installed. Install the old build, sign in, then install the new build over it. The user must stay signed in.
After most users update, change storage to secureStorage and remove the AsyncStorage code. Keep the plan: a user who skips many versions loses the session and signs in again. This is acceptable.
What does SecureStore protect and what does it not protect?
Use the correct model. SecureStore is a good place for a session. It is not a vault against every attacker.
The Expo documentation says that on iOS the values go in the Keychain. It says that on Android they are stored in SharedPreferences and encrypted with the Android Keystore.
SecureStore protects against:
- A person who copies the app data folder or a file backup.
- A simple file read on a device that is locked.
- A tool that dumps plain-text app files.
SecureStore does not protect against:
- Code that runs in your app. Any JavaScript in the app can call
getItemAsync. A malicious package in your dependencies can read the token. See the guide on a malicious npm package. - A rooted or jailbroken device. An attacker with full control can read memory or hook your app.
- A stolen token sent from another place. A token is a bearer value. Whoever holds it can use it.
- A missing server check. If the API does not check ownership, a valid token of any user opens the data. SecureStore does not fix this. See the BOLA pattern.
- Reinstall effects. The Expo documentation says that on iOS the Keychain data can stay after an uninstall and reinstall with the same bundle ID. It also says not to rely on this. Call
supabase.auth.signOut()on first launch if you want a clean state.
Do not store irreplaceable data in SecureStore. The Expo documentation warns against this.
You can also use requireAuthentication: true for a value that needs Face ID or a passcode on each read. This adds friction to every session refresh, so it does not fit a normal login token. It fits a high-risk secret, such as a payment approval key. Biometric changes can invalidate such a value, and testing needs a real device.
What is the Android equivalent?
The same code works on Android. SecureStore uses the Android Keystore to encrypt values, and it stores them in SharedPreferences. Data is not kept after an uninstall.
Two points apply to Android:
- Auto Backup. The Expo documentation says that Auto Backup must exclude the SecureStore preferences, because the keys cannot be restored. The library configures this when you have no custom backup rules. If you have your own rules, exclude the
sharedprefpathSecureStoreand setconfigureAndroidBackuptofalsein the config plugin. - Keystore invalidation. If the user changes the lock screen or biometrics, some values can become unreadable. The adapter returns
null, and supabase-js treats that as a signed-out state. The user signs in again. Handle this case in the UI.
AsyncStorage on Android is also plain text. The same migration applies.
How do I stop this problem in the future?
- Search for
AsyncStorage.setItemandstorage: AsyncStoragebefore each release. - Add a lint rule or a code review item for the word
tokennear AsyncStorage calls. - Re-check the storage after each AI code regeneration. Generated auth code often returns to the default.
- Keep access tokens short-lived. Revoke sessions on the server when a user reports a lost phone.
- Test the backend with a valid token of user B against the data of user A. Storage does not replace server checks.
When should I get help?
Get help when you find that a token was logged or sent to a third party, or when you suspect that tokens were stolen. Revoke all sessions for the affected users first. In Supabase, call the admin sign-out for each user, or rotate the JWT secret if you must end all sessions. This signs out every user, so plan the change.
Common questions
Is AsyncStorage encrypted?
Why does the Supabase quickstart use AsyncStorage?
Why can I not store the full Supabase session in SecureStore directly?
Do users need to sign in again after the change?
Does SecureStore protect a token on a jailbroken phone?
Test the backend behind the token
A VibeEval scan tests the API and Supabase project that your app signs in to, and checks if a stolen or replayed token reaches data it must not reach.
14-day free trial · Cancel anytime