Skip to content
Download resume

Writing

How to Store Auth Tokens Securely in React Native

Where to keep tokens, sessions and keys in React Native: expo-secure-store, react-native-keychain and encrypted MMKV, with logout and reinstall handling.

Published Last updated 7 min read

  • React Native
  • Expo
  • Security
  • MMKV
  • TypeScript
  • iOS
  • Android

Short answer: keep the refresh token (and any long lived session id) in expo-secure-store or react-native-keychain, which hand it to the iOS Keychain and the Android Keystore. Keep the short lived access token in memory. For larger sensitive data, use MMKV with encryption and store only its encryption key in secure storage. Never put tokens in AsyncStorage or plain MMKV.

Every app I build with a login, has to answer the same question on day one: where does the session live between launches? This article is the setup I use, with the two platform quirks that catch people out (iOS reinstalls and Android backups). It is part of a small series on local storage; the overview is MMKV vs AsyncStorage vs SQLite vs SecureStore.

What counts as sensitive data

A simple test: if someone copied this value off the phone, could they act as the user or read their private data? If yes, it is sensitive.

Data Sensitive? Where to keep it
Refresh token, session id Yes SecureStore or Keychain
Access token (short lived JWT) Yes Memory, refreshed from the refresh token
User PIN or password Yes, avoid storing it at all Keychain with biometric protection, if you must
Encryption key for a local database Yes SecureStore or Keychain
Cached private messages, health or finance data Yes, and often large Encrypted MMKV or SQLCipher, key in secure storage
Theme, language, onboarding flag No Plain MMKV or AsyncStorage

Why AsyncStorage and plain MMKV are not enough

Both write to files inside your app’s sandbox. The sandbox stops other apps from reading them on a normal phone, but the values are stored as plain text. On a rooted or jailbroken device, from an unencrypted device backup, or through a debugging tool on a developer’s phone, anyone can open those files and read the token.

The React Native security guide says the same: AsyncStorage is unencrypted and should not hold tokens or secrets. Secure storage is different because the secret goes to the operating system:

  • iOS: values go into the Keychain, which is encrypted by the system and tied to the device passcode.
  • Android: values are encrypted with a key that lives in the Android Keystore. On most modern phones that key sits in dedicated secure hardware, so it never enters your app’s memory and cannot be copied off the device.

Option 1: expo-secure-store

expo-secure-store is the easiest choice, and it runs in Expo Go. Versions here are from Expo SDK 58 (expo-secure-store 58.0.2):

npx expo install expo-secure-store
import * as SecureStore from 'expo-secure-store';

const REFRESH_TOKEN = 'refreshToken';

export async function saveRefreshToken(token: string) {
  await SecureStore.setItemAsync(REFRESH_TOKEN, token, {
    // Readable after the first unlock since boot, so background refresh still works.
    // THIS_DEVICE_ONLY keeps it out of backups restored onto another phone.
    keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,
  });
}

export function getRefreshToken() {
  return SecureStore.getItemAsync(REFRESH_TOKEN);
}

export function deleteRefreshToken() {
  return SecureStore.deleteItemAsync(REFRESH_TOKEN);
}

Keys may only contain letters, numbers, ., - and _. Keep values small: the Expo docs note that some iOS versions rejected values above roughly 2048 bytes. A token fits easily, a whole user profile does not.

Option 2: react-native-keychain

react-native-keychain (version 10.0.0 at the time of writing) gives you more control: biometric access rules, security level checks and separate “services” for different secrets. It is a common choice in bare React Native apps.

import * as Keychain from 'react-native-keychain';

const SERVICE = 'com.example.app.session';

export async function saveSession(userId: string, refreshToken: string) {
  await Keychain.setGenericPassword(userId, refreshToken, {
    service: SERVICE,
    accessible: Keychain.ACCESSIBLE.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,
  });
}

export async function loadSession() {
  const credentials = await Keychain.getGenericPassword({ service: SERVICE });
  return credentials ? { userId: credentials.username, refreshToken: credentials.password } : null;
}

export function clearSession() {
  return Keychain.resetGenericPassword({ service: SERVICE });
}

The username and password pair looks odd for a token, but it maps neatly onto a session: the user id goes in username and the token in password.

Which one should you pick? In an Expo app, expo-secure-store covers most needs with less setup. Reach for react-native-keychain when you need finer biometric rules or you are in a bare app that already uses it.

Option 3: encrypted MMKV for larger sensitive data

Secure storage is built for small secrets, not for a cache of private messages or financial records. For those, I use MMKV with encryption turned on and keep only the key in secure storage:

import * as Crypto from 'expo-crypto';
import * as SecureStore from 'expo-secure-store';
import { createMMKV } from 'react-native-mmkv';

const KEY_NAME = 'mmkvEncryptionKey';

function getOrCreateEncryptionKey() {
  let key = SecureStore.getItem(KEY_NAME);
  if (!key) {
    // 16 random bytes as hex = 32 characters, the maximum for AES-256 in MMKV
    key = Array.from(Crypto.getRandomBytes(16), (b) => b.toString(16).padStart(2, '0')).join('');
    SecureStore.setItem(KEY_NAME, key, {
      keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,
    });
  }
  return key;
}

export const secureCache = createMMKV({
  id: 'secure-cache',
  encryptionKey: getOrCreateEncryptionKey(),
  encryptionType: 'AES-256',
});

I use the synchronous getItem and setItem from expo-secure-store here so the encrypted instance can be created at startup, before the first screen. The key length matters: react-native-mmkv rejects keys longer than 16 bytes with AES-128 and 32 bytes with AES-256, which I checked in its source. You keep MMKV’s speed (more on that in how to make local storage fast in React Native) and the data on disk is useless without the key from the Keychain or Keystore.

If the sensitive data is relational, the same idea works with SQLite: expo-sqlite and op-sqlite both support SQLCipher, and you keep its key in secure storage.

The full token flow

Putting it together, this is the flow I set up in apps with a login:

  1. Login: the server returns an access token and a refresh token. Save the refresh token in secure storage. Keep the access token in a variable or your state store, not on disk.
  2. App launch: read the refresh token. If it exists, ask the server for a new access token. If that fails with 401, send the user to login.
  3. API calls: attach the access token from memory. On a 401, refresh once and retry.
  4. Logout: delete the refresh token, clear per user MMKV instances, clear the query cache, and tell the server to revoke the session.

A minimal token holder:

import * as SecureStore from 'expo-secure-store';

let accessToken: string | null = null;

export const tokens = {
  getAccess: () => accessToken,
  setAccess: (token: string | null) => {
    accessToken = token;
  },
  async clearAll() {
    accessToken = null;
    await SecureStore.deleteItemAsync('refreshToken');
  },
};

Keeping the access token only in memory means a stolen app backup or file dump has nothing useful beyond the refresh token, which is in the Keychain or Keystore and which your server can revoke.

Two platform quirks to handle

iOS keeps Keychain data after the app is uninstalled

On iOS, Keychain items can survive an uninstall. A user deletes your app, reinstalls it weeks later, and is “already logged in” with an old session, or worse, a session that belongs to someone else on a shared device. The Expo docs warn about this and say not to rely on it either way.

The fix uses the fact that MMKV files are deleted on uninstall:

import * as SecureStore from 'expo-secure-store';
import { appStorage } from './storage';

export async function clearKeychainOnFreshInstall() {
  if (appStorage.getBoolean('hasLaunchedBefore')) return;
  await SecureStore.deleteItemAsync('refreshToken');
  appStorage.set('hasLaunchedBefore', true);
}

Call it once at startup, before you read the session. If the flag is missing, this is a fresh install, so any leftover Keychain item gets removed.

Android backups cannot restore encrypted values

Android Auto Backup can copy your app’s shared preferences to the cloud, but the Keystore key used to encrypt them is never backed up. After a restore on a new phone, the values cannot be decrypted. expo-secure-store excludes its own data from Auto Backup by default. If your app has a custom backup configuration, exclude the SecureStore shared preferences yourself, as the Android Auto Backup section of the docs explains, and make sure your app handles a missing token by asking the user to log in again.

Biometric protection

Both libraries can require Face ID, Touch ID or a fingerprint before a value is read. With expo-secure-store, pass requireAuthentication: true; with react-native-keychain, set accessControl: Keychain.ACCESS_CONTROL.BIOMETRY_ANY.

Use it for high value actions, such as unlocking a banking app or confirming a payment, not for the refresh token your app reads silently at every launch. Also know that values protected this way become unreadable when the user changes their biometrics (adds a new fingerprint, for example), so always have a fallback to a normal login.

What secure storage does not protect

Secure storage protects data at rest on the device. It does not help if:

  • You log tokens with console.log or send them to a crash reporter.
  • You put tokens in URLs, where they end up in server and proxy logs.
  • The device is compromised and an attacker hooks your running app, reading the token from memory after you load it.

For the last one there is no perfect answer on a device you do not control. Short lived access tokens, refresh token rotation and server side revocation limit the damage. The OWASP Mobile Application Security project is the reference I use when an app needs a proper security review.

FAQ

Where should I store a JWT in React Native?

Store the refresh token in expo-secure-store or react-native-keychain, and keep the short lived access token in memory. If your backend only issues one long lived JWT, treat it like a refresh token and keep it in secure storage.

Is AsyncStorage secure for tokens?

No. AsyncStorage stores values unencrypted in the app’s sandbox. The React Native documentation recommends against storing tokens or secrets in it. Use the iOS Keychain and Android Keystore through a secure storage library.

Is expo-secure-store safe?

Yes, for small secrets. It stores values in the iOS Keychain and, on Android, encrypts them with a key held in the Android Keystore. It is not meant for large data, and some iOS versions rejected values larger than about 2048 bytes.

Is encrypted MMKV as secure as the Keychain?

Only if the encryption key is kept safe. Hardcoding the key in your JavaScript bundle makes the encryption pointless, because anyone can extract it. Generate a random key on the device and store it in SecureStore or Keychain, as shown above.

Why is my user still logged in after reinstalling on iOS?

The iOS Keychain can keep items after an uninstall. Store a “has launched before” flag in MMKV or AsyncStorage, which are deleted on uninstall, and clear the Keychain items when the flag is missing.

Does secure storage work in Expo Go?

expo-secure-store works in Expo Go. react-native-keychain and react-native-mmkv need native code, so they require a development build.


This is the last part of my local storage series. Start from MMKV vs AsyncStorage vs SQLite vs SecureStore if you skipped it. If you want a security minded React Native developer on your app, get in touch.

More articles

Have an app in mind?

Tell me what you're building. I reply to every serious enquiry within two working days.