Mobile development · Intermediate · 24 min
Keep sign-in tokens safe on the phone with expo-secure-store
By Padding · Updated 18 Nov 2026
Expo SDK 58 · expo-secure-store 58.0 · jest-expo 58.0 · Node.js 26 (node:26 image)
You will have an Expo SDK 58 app that keeps its refresh token in the iOS Keychain or Android Keystore, holds the access token in memory only, asks for Face ID or a fingerprint before a transfer, starts clean after a reinstall and signs out by deleting every key, with Jest tests for all of it.
On this page
A signed-in mobile app holds two things an attacker wants: an access token that opens your API for a few minutes, and a refresh token that keeps minting new access tokens for weeks. Where you keep them decides what a stolen phone backup, a rooted handset or a copied app folder gives away. AsyncStorage and MMKV write plain files in the app's folder. expo-secure-store hands the value to the operating system instead: on iOS it becomes a Keychain item, and on Android it is encrypted with a key held in the Android Keystore, which the app itself cannot export.
You will build the token layer of a small money-transfer app in Expo SDK 58. The refresh token goes into secure storage with a deliberate keychainAccessible choice. The access token lives in memory and is refreshed when it expires, one request at a time. A transfer needs Face ID or a fingerprint, through requireAuthentication. The app starts clean after a reinstall or on a new phone, and signing out deletes every key, even with no signal. Jest tests cover each part, with secure storage replaced by an in-memory stand-in that follows the real module's rules.
Step 1 · Decide where each credential lives
Before writing code, sort what your sign-in hands you. This tutorial uses these rules:
- Refresh token: long-lived and powerful. It goes into
expo-secure-storeand nowhere else. Ask your server to rotate it, so each refresh returns a new one and the old one stops working. - Access token: short-lived, sent on every request. Keep it in a JavaScript variable. When the app is closed it is gone, and the refresh token gets a new one on the next launch. Writing it to disk only adds a copy to steal.
- ID token (if your provider uses OpenID Connect): read the name and email from it once at sign-in, then drop it. It is not a key for your API.
- A key that opens a sensitive action, such as confirming a transfer: secure storage, behind a biometric prompt.
- API keys for third-party services: none in the app. Anything you ship, including values in
EXPO_PUBLIC_variables, can be read by anyone who downloads the app. Calls that need a secret go through your own server.
The tokens themselves come from your sign-in flow. For OAuth, a native app is a public client that cannot keep a client secret, so it uses the authorisation code flow with PKCE. In Expo that is expo-auth-session, and the OAuth 2.1 and PKCE tutorial explains the flow. This tutorial picks up at the point where the code exchange returns access_token, refresh_token and expires_in.
Check it worked
Write down every credential your app receives or holds, with one of the destinations above next to each. If anything is headed for AsyncStorage, MMKV, a constant in the code or an EXPO_PUBLIC_ variable, and it would let someone act as the user or spend your money, change its destination before you continue.
Step 2 · Install expo-secure-store and set the Face ID text
Create a throwaway app to work in. When it asks to download create-expo-app, answer y:
cd ~
npx create-expo-app@5.0.0 secure-tokens-demoInstall secure storage and AsyncStorage (used later for one non-secret flag). npx expo install picks the versions that match SDK 58:
cd ~/secure-tokens-demo
npx expo install expo-secure-store @react-native-async-storage/async-storageexpo-secure-store has a config plugin with two options. faceIDPermission is the sentence iOS shows the first time the app asks for Face ID; without it, iOS refuses to store a value that needs biometrics. configureAndroidBackup (on by default) keeps secure-store data out of Android Auto Backup, because a restored copy cannot be decrypted: the Keystore keys never leave the original phone.
Set the plugin options, and an iOS bundle identifier and Android package name so the native settings can be generated. Replace com.example.securetokens with your own reverse-domain name. The script below writes these into app.json, replacing any plugin entry that npx expo install added:
cd ~/secure-tokens-demo
cat > configure-app.js <<'JS'
const fs = require('fs')
const config = JSON.parse(fs.readFileSync('app.json', 'utf8'))
const expo = config.expo
expo.ios = { ...expo.ios, bundleIdentifier: 'com.example.securetokens' }
expo.android = { ...expo.android, package: 'com.example.securetokens' }
expo.plugins = (expo.plugins || []).filter(
(entry) => (Array.isArray(entry) ? entry[0] : entry) !== 'expo-secure-store',
)
expo.plugins.push([
'expo-secure-store',
{
faceIDPermission: 'Allow $(PRODUCT_NAME) to use Face ID to confirm transfers.',
configureAndroidBackup: true,
},
])
fs.writeFileSync('app.json', JSON.stringify(config, null, 2) + '\n')
JS
node configure-app.js
rm configure-app.jsIf you prefer to edit by hand, the plugin entry in app.json looks like this:
[
"expo-secure-store",
{
"faceIDPermission": "Allow $(PRODUCT_NAME) to use Face ID to confirm transfers.",
"configureAndroidBackup": true
}
]Check it worked
Ask Expo to run the plugins in memory and print the iOS Info.plist value, then generate the Android project and read the backup setting from its manifest:
cd ~/secure-tokens-demo
npx expo config --type introspect --json > /tmp/secure-tokens-introspect.json
node -e "console.log(require('/tmp/secure-tokens-introspect.json').ios.infoPlist.NSFaceIDUsageDescription)"
npx expo prebuild --platform android --no-install
grep -o 'android:dataExtractionRules="[^"]*"' android/app/src/main/AndroidManifest.xmlThe first command prints Allow $(PRODUCT_NAME) to use Face ID to confirm transfers. (iOS fills in the app name). The last prints android:dataExtractionRules="@xml/secure_store_data_extraction_rules". Because these are native settings, Expo Go cannot use them: biometric storage needs a development build, made with npx expo run:ios, npx expo run:android or EAS Build.
Step 3 · Save the refresh token in the Keychain or Keystore
Every read must pass the same keychainService the value was written with, so keep the options in one object. keychainAccessible is iOS only and decides when the Keychain will hand the item back:
WHEN_UNLOCKED(the default): only while the phone is unlocked, and copied to a new iPhone from an encrypted backup.AFTER_FIRST_UNLOCK: after the first unlock since a restart, even when the phone is locked again, so a background task can use it.- The
_THIS_DEVICE_ONLYversions of both: the same, but never restored to another phone. WHEN_PASSCODE_SET_THIS_DEVICE_ONLY: only on a phone with a passcode, and deleted if the passcode is removed.ALWAYSandALWAYS_THIS_DEVICE_ONLY: deprecated. Do not use them.
For a refresh token, AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY is a sound choice: background refreshes work, and a token restored onto a different phone (where the server never saw it sign in) does not appear. If your app never refreshes in the background, WHEN_UNLOCKED_THIS_DEVICE_ONLY is stricter.
cd ~/secure-tokens-demo
mkdir -p src/auth/testing
cat > src/auth/token-store.ts <<'TS'
import * as SecureStore from 'expo-secure-store'
// Where the session lives on the phone. Only the refresh token is stored here:
// the access token stays in memory.
const SESSION: SecureStore.SecureStoreOptions = {
keychainService: 'auth.session',
// iOS: readable after the first unlock since a restart, so a background refresh
// works, and never restored from a backup onto another phone.
keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,
}
// Keys may only use letters, digits, ".", "-" and "_".
const REFRESH_TOKEN = 'refresh_token'
export function saveRefreshToken(token: string): Promise<void> {
return SecureStore.setItemAsync(REFRESH_TOKEN, token, SESSION)
}
export function readRefreshToken(): Promise<string | null> {
return SecureStore.getItemAsync(REFRESH_TOKEN, SESSION)
}
export function deleteRefreshToken(): Promise<void> {
return SecureStore.deleteItemAsync(REFRESH_TOKEN, SESSION)
}
TSJest runs on your computer, where there is no Keychain or Keystore. Replace expo-secure-store with an in-memory stand-in that keeps the rules your code relies on: the key characters, string-only values, items separated by keychainService, a prompt for items stored with requireAuthentication, and items dropped when biometrics change. It also records the options each item was saved with, so a test can check them.
cd ~/secure-tokens-demo
cat > src/auth/testing/secure-store-mock.ts <<'TS'
// For tests only: an in-memory stand-in for expo-secure-store. Never import it from
// app code. The constant values are placeholders; only their names matter here.
type Options = {
keychainService?: string
keychainAccessible?: number
requireAuthentication?: boolean
authenticationPrompt?: string
}
type Item = { value: string; options: Options }
export const AFTER_FIRST_UNLOCK = 0
export const AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY = 1
export const ALWAYS = 2
export const WHEN_PASSCODE_SET_THIS_DEVICE_ONLY = 3
export const ALWAYS_THIS_DEVICE_ONLY = 4
export const WHEN_UNLOCKED = 5
export const WHEN_UNLOCKED_THIS_DEVICE_ONLY = 6
const items = new Map<string, Item>()
const prompts: string[] = []
let biometricsEnrolled = true
let cancelNextPrompt = false
function slot(key: string, options: Options = {}): string {
if (typeof key !== 'string' || !/^[\w.-]+$/.test(key)) {
throw new Error('Invalid key provided to SecureStore.')
}
return `${options.keychainService ?? 'app'}/${key}`
}
export async function setItemAsync(key: string, value: string, options: Options = {}) {
const id = slot(key, options)
if (typeof value !== 'string') {
throw new Error('Invalid value provided to SecureStore. Values must be strings.')
}
if (options.requireAuthentication && !biometricsEnrolled) {
throw new Error('No biometrics are enrolled on this device')
}
items.set(id, { value, options: { ...options } })
}
export async function getItemAsync(key: string, options: Options = {}) {
const item = items.get(slot(key, options))
if (!item) return null
if (item.options.requireAuthentication) {
prompts.push(options.authenticationPrompt ?? '')
if (cancelNextPrompt) {
cancelNextPrompt = false
throw new Error('User canceled the authentication')
}
}
return item.value
}
export async function deleteItemAsync(key: string, options: Options = {}) {
items.delete(slot(key, options))
}
export async function isAvailableAsync() {
return true
}
export function canUseBiometricAuthentication() {
return biometricsEnrolled
}
// Helpers for tests.
export function __reset() {
items.clear()
prompts.length = 0
biometricsEnrolled = true
cancelNextPrompt = false
}
export function __item(service: string, key: string) {
return items.get(`${service}/${key}`)
}
export function __values() {
return [...items.values()].map((item) => item.value).sort()
}
export function __prompts() {
return [...prompts]
}
export function __cancelNextPrompt() {
cancelNextPrompt = true
}
export function __setBiometricsEnrolled(enrolled: boolean) {
biometricsEnrolled = enrolled
}
// Adding a fingerprint or a face makes the phone drop items stored with requireAuthentication.
export function __changeEnrolledBiometrics() {
for (const [id, item] of items) {
if (item.options.requireAuthentication) items.delete(id)
}
}
TS
cat > jest.setup.ts <<'TS'
// No Keychain or Keystore on a computer: every test gets the in-memory stand-in.
jest.mock('expo-secure-store', () => require('./src/auth/testing/secure-store-mock'))
TSInstall Jest with the Expo preset and point it at the setup file:
cd ~/secure-tokens-demo
npx expo install --dev jest-expo jest @types/jest
npm pkg set jest.preset=jest-expo 'jest.setupFiles[0]=<rootDir>/jest.setup.ts' scripts.test=jest
cat > src/auth/token-store.test.ts <<'TS'
import { deleteRefreshToken, readRefreshToken, saveRefreshToken } from './token-store'
const store = jest.requireMock<typeof import('./testing/secure-store-mock')>('expo-secure-store')
beforeEach(() => store.__reset())
test('keeps the refresh token in its own service, on this phone only', async () => {
await saveRefreshToken('rt-1')
expect(await readRefreshToken()).toBe('rt-1')
expect(store.__item('auth.session', 'refresh_token')?.options).toMatchObject({
keychainService: 'auth.session',
keychainAccessible: store.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,
})
})
test('reads null once the token is deleted', async () => {
await saveRefreshToken('rt-1')
await deleteRefreshToken()
expect(await readRefreshToken()).toBeNull()
expect(store.__values()).toEqual([])
})
TS
npx jest src/auth/token-store --ciCheck it worked
Jest reports Tests: 2 passed, 2 total. To see the test protect your choice, change AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY in token-store.ts to AFTER_FIRST_UNLOCK and run npx jest src/auth/token-store again: the first test fails. Change it back before you continue.
Step 4 · Put a transfer behind Face ID or a fingerprint
With requireAuthentication: true, the phone will only release the value after Face ID, Touch ID or a fingerprint. On iOS the item is tied to the biometrics enrolled now: if someone adds a new face or fingerprint, the item becomes unreadable and getItemAsync returns null. On Android the prompt appears for every operation, including saving; on iOS only when reading or updating.
Use this for a separate, server-issued approval key, not for the refresh token. If the refresh token needed a prompt, every background refresh would fail. The flow is: the person turns on quick approval after typing their password, your server issues a key for this phone, the app stores it behind biometrics, and each transfer sends that key alongside the access token. A cancelled prompt is a normal answer, not damaged data, and a missing key means "ask for the password again".
Give these items their own keychainService, apart from the items the app reads without a prompt:
cd ~/secure-tokens-demo
cat > src/auth/approval.ts <<'TS'
import * as SecureStore from 'expo-secure-store'
const APPROVAL: SecureStore.SecureStoreOptions = {
keychainService: 'auth.approval',
requireAuthentication: true,
authenticationPrompt: 'Confirm it is you to send money',
// iOS: needs a device passcode, never leaves this phone, deleted if the passcode is removed.
keychainAccessible: SecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY,
}
const APPROVAL_KEY = 'approval_key'
export type Approval =
| { status: 'approved'; key: string }
| { status: 'cancelled'; reason: string }
| { status: 'needs-password' }
export function canOfferBiometricApproval(): boolean {
return SecureStore.canUseBiometricAuthentication()
}
// Call after the person has confirmed their password and your server has issued a
// key for this phone.
export async function enableBiometricApproval(serverIssuedKey: string): Promise<void> {
await SecureStore.setItemAsync(APPROVAL_KEY, serverIssuedKey, APPROVAL)
}
export async function approveSensitiveAction(): Promise<Approval> {
if (!canOfferBiometricApproval()) return { status: 'needs-password' }
try {
const key = await SecureStore.getItemAsync(APPROVAL_KEY, APPROVAL)
// null: never turned on for this phone, or dropped because biometrics changed.
return key === null ? { status: 'needs-password' } : { status: 'approved', key }
} catch (error) {
// Cancelled, timed out or locked out after too many tries.
return { status: 'cancelled', reason: error instanceof Error ? error.message : String(error) }
}
}
export function forgetBiometricApproval(): Promise<void> {
return SecureStore.deleteItemAsync(APPROVAL_KEY, { keychainService: APPROVAL.keychainService })
}
TS
cat > src/auth/approval.test.ts <<'TS'
import { approveSensitiveAction, enableBiometricApproval } from './approval'
const store = jest.requireMock<typeof import('./testing/secure-store-mock')>('expo-secure-store')
beforeEach(() => store.__reset())
test('shows the prompt and returns the key', async () => {
await enableBiometricApproval('ak-1')
expect(await approveSensitiveAction()).toEqual({ status: 'approved', key: 'ak-1' })
expect(store.__prompts()).toEqual(['Confirm it is you to send money'])
expect(store.__item('auth.approval', 'approval_key')?.options.requireAuthentication).toBe(true)
})
test('a cancelled prompt is an answer, and the key stays', async () => {
await enableBiometricApproval('ak-1')
store.__cancelNextPrompt()
expect(await approveSensitiveAction()).toEqual({
status: 'cancelled',
reason: 'User canceled the authentication',
})
expect(store.__values()).toEqual(['ak-1'])
})
test('new biometrics on the phone mean the password again', async () => {
await enableBiometricApproval('ak-1')
store.__changeEnrolledBiometrics()
expect(await approveSensitiveAction()).toEqual({ status: 'needs-password' })
})
test('a phone without biometrics falls back to the password, with no prompt', async () => {
store.__setBiometricsEnrolled(false)
expect(await approveSensitiveAction()).toEqual({ status: 'needs-password' })
expect(store.__prompts()).toEqual([])
})
TS
npx jest src/auth/approval --ciMany low-cost Android phones have no fingerprint reader, or one that Android does not rate as strong enough. canUseBiometricAuthentication() returns false there, and the app asks for the password instead, so nobody is locked out of their own money.
Check it worked
Jest reports Tests: 4 passed, 4 total. On a development build on a real phone, turn on quick approval and confirm a transfer: the system sheet shows "Confirm it is you to send money". Cancel it and the app should say the transfer was not sent, not that something broke.
Step 5 · Keep the access token in memory and refresh it
The session object holds the access token in a variable and asks for a new one when it is within 30 seconds of expiring. Three details matter:
- One refresh at a time. With rotating refresh tokens, two screens refreshing at once would send the same token twice, and a server with reuse detection treats that as theft and ends the session. Concurrent callers share one promise.
- Save the rotated token. Each successful refresh returns a new refresh token; the old one no longer works.
- Tell rejection from bad signal. A
400or401from the refresh endpoint means the server no longer accepts the token, so delete everything and sign the person out. A network error or a5xxmeans try later, so keep the token. On prepaid data that runs out mid-week, signing people out every time the bundle ends would be a poor experience.
First, one place that deletes every secure item the app writes:
cd ~/secure-tokens-demo
cat > src/auth/forget.ts <<'TS'
import { forgetBiometricApproval } from './approval'
import { deleteRefreshToken } from './token-store'
// Every expo-secure-store item this app writes. Add new ones here.
export async function deleteAllSecureItems(): Promise<void> {
await deleteRefreshToken()
await forgetBiometricApproval()
}
TS
cat > src/auth/session.ts <<'TS'
import { deleteAllSecureItems } from './forget'
import { readRefreshToken, saveRefreshToken } from './token-store'
type HttpResponse = { ok: boolean; status: number; json(): Promise<unknown> }
export type Fetch = (
url: string,
init: { method: 'POST'; headers: Record<string, string>; body: string },
) => Promise<HttpResponse>
export type RestoreResult = 'signed-in' | 'signed-out' | 'try-later'
export class SignedOutError extends Error {
constructor() {
super('There is no session on this phone. Sign in again.')
this.name = 'SignedOutError'
}
}
type Tokens = { accessToken: string; refreshToken: string; expiresIn: number }
function parseTokens(data: unknown): Tokens {
const d = data as Record<string, unknown> | null
if (
!d ||
typeof d.access_token !== 'string' ||
typeof d.refresh_token !== 'string' ||
typeof d.expires_in !== 'number'
) {
throw new Error('The server sent an unexpected token response')
}
return { accessToken: d.access_token, refreshToken: d.refresh_token, expiresIn: d.expires_in }
}
type SessionOptions = { baseUrl: string; fetchImpl: Fetch; now?: () => number }
export function createSession({ baseUrl, fetchImpl, now = Date.now }: SessionOptions) {
// Memory only: gone when the app closes.
let accessToken: string | null = null
let expiresAt = 0
let refreshing: Promise<string> | null = null
function post(path: string, body: object) {
return fetchImpl(`${baseUrl}${path}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
function forgetMemory() {
accessToken = null
expiresAt = 0
}
async function keep(tokens: Tokens) {
// The server rotates refresh tokens: the previous one has stopped working.
await saveRefreshToken(tokens.refreshToken)
accessToken = tokens.accessToken
expiresAt = now() + tokens.expiresIn * 1000
}
async function refresh(): Promise<string> {
const refreshToken = await readRefreshToken()
if (refreshToken === null) throw new SignedOutError()
const response = await post('/auth/refresh', { refresh_token: refreshToken })
if (response.status === 400 || response.status === 401) {
// Revoked, expired or reused: the server will not accept this token again.
forgetMemory()
await deleteAllSecureItems()
throw new SignedOutError()
}
if (!response.ok) throw new Error(`Refreshing the session failed with HTTP ${response.status}`)
const tokens = parseTokens(await response.json())
await keep(tokens)
return tokens.accessToken
}
// Every API call asks here. Concurrent callers share one refresh.
function getAccessToken(): Promise<string> {
if (accessToken !== null && now() < expiresAt - 30_000) return Promise.resolve(accessToken)
refreshing ??= refresh().finally(() => {
refreshing = null
})
return refreshing
}
// Call with the token response from your sign-in, for example the PKCE code exchange.
async function signIn(response: unknown): Promise<void> {
await keep(parseTokens(response))
}
// On launch: does the stored refresh token still work?
async function restore(): Promise<RestoreResult> {
try {
await getAccessToken()
return 'signed-in'
} catch (error) {
// No signal or a server error: keep the token and try again later.
return error instanceof SignedOutError ? 'signed-out' : 'try-later'
}
}
async function signOut(): Promise<void> {
const refreshToken = await readRefreshToken()
forgetMemory()
await deleteAllSecureItems()
if (refreshToken === null) return
try {
await post('/auth/revoke', { token: refreshToken })
} catch {
// Offline: the phone has already forgotten the token, and the server lets it
// expire. Never keep someone signed in because the network is down.
}
}
return { signIn, getAccessToken, restore, signOut }
}
TSThe tests pass in a fake fetch that records each request and answers the way your API would, and a clock they can move forward:
cd ~/secure-tokens-demo
cat > src/auth/testing/fake-api.ts <<'TS'
import type { Fetch } from '../session'
type Reply = { status: number; body?: unknown }
// For tests only: records each request and answers with the reply function.
export function fakeApi(reply: (path: string, body: Record<string, unknown>) => Reply) {
const calls: { path: string; body: Record<string, unknown> }[] = []
const fetchImpl: Fetch = async (url, init) => {
const path = url.replace('https://api.test', '')
const body = JSON.parse(init.body)
calls.push({ path, body })
const answer = reply(path, body)
return {
ok: answer.status >= 200 && answer.status < 300,
status: answer.status,
json: async () => answer.body,
}
}
return { fetchImpl, calls }
}
export function tokens(n: number) {
return { access_token: `at-${n}`, refresh_token: `rt-${n}`, expires_in: 900 }
}
TS
cat > src/auth/session.test.ts <<'TS'
import { createSession, SignedOutError } from './session'
import { fakeApi, tokens } from './testing/fake-api'
const store = jest.requireMock<typeof import('./testing/secure-store-mock')>('expo-secure-store')
let clock = 0
const now = () => clock
const FIFTEEN_MINUTES = 15 * 60 * 1000
beforeEach(() => {
store.__reset()
clock = Date.UTC(2026, 10, 26, 8, 0, 0)
})
test('sign-in stores only the refresh token', async () => {
const api = fakeApi(() => ({ status: 500 }))
const session = createSession({ baseUrl: 'https://api.test', fetchImpl: api.fetchImpl, now })
await session.signIn(tokens(1))
expect(await session.getAccessToken()).toBe('at-1')
expect(store.__values()).toEqual(['rt-1'])
expect(api.calls).toHaveLength(0)
})
test('an expired access token is refreshed once and the rotated token saved', async () => {
let issued = 1
const api = fakeApi(() => ({ status: 200, body: tokens(++issued) }))
const session = createSession({ baseUrl: 'https://api.test', fetchImpl: api.fetchImpl, now })
await session.signIn(tokens(1))
clock += FIFTEEN_MINUTES
const both = await Promise.all([session.getAccessToken(), session.getAccessToken()])
expect(both).toEqual(['at-2', 'at-2'])
expect(api.calls).toEqual([{ path: '/auth/refresh', body: { refresh_token: 'rt-1' } }])
expect(store.__values()).toEqual(['rt-2'])
})
test('after a restart the stored refresh token brings the session back', async () => {
const api = fakeApi(() => ({ status: 200, body: tokens(2) }))
await createSession({ baseUrl: 'https://api.test', fetchImpl: api.fetchImpl, now }).signIn(tokens(1))
const afterRestart = createSession({ baseUrl: 'https://api.test', fetchImpl: api.fetchImpl, now })
expect(await afterRestart.restore()).toBe('signed-in')
expect(await afterRestart.getAccessToken()).toBe('at-2')
})
test('a refresh token the server rejects signs the person out', async () => {
const api = fakeApi(() => ({ status: 401 }))
const session = createSession({ baseUrl: 'https://api.test', fetchImpl: api.fetchImpl, now })
await session.signIn(tokens(1))
clock += FIFTEEN_MINUTES
await expect(session.getAccessToken()).rejects.toBeInstanceOf(SignedOutError)
expect(store.__values()).toEqual([])
})
test('no signal keeps the refresh token for later', async () => {
const api = fakeApi(() => {
throw new TypeError('Network request failed')
})
await createSession({ baseUrl: 'https://api.test', fetchImpl: api.fetchImpl, now }).signIn(tokens(1))
const afterRestart = createSession({ baseUrl: 'https://api.test', fetchImpl: api.fetchImpl, now })
expect(await afterRestart.restore()).toBe('try-later')
expect(store.__values()).toEqual(['rt-1'])
})
TS
npx jest src/auth/session --ciCheck it worked
Jest reports Tests: 5 passed, 5 total. The second test is the one to read closely: two callers, one request to /auth/refresh, and the stored value is now rt-2. To see why the shared promise matters, change refreshing ??= refresh().finally(...) so that getAccessToken returns refresh() directly, run the test again and watch it fail with two refresh calls, then put it back.
Step 6 · Sign out by deleting the keys
signOut in session.ts reads the refresh token first, because the server needs it to revoke the session. Then it clears memory and deletes every secure item before touching the network. If the revoke request fails, the phone has still forgotten everything. Revocation (RFC 7009 if your provider follows it) matters on shared phones, which are common in many households: the next person to pick up the phone must not be able to continue the session.
cd ~/secure-tokens-demo
cat > src/auth/sign-out.test.ts <<'TS'
import { enableBiometricApproval } from './approval'
import { createSession, SignedOutError } from './session'
import { fakeApi, tokens } from './testing/fake-api'
const store = jest.requireMock<typeof import('./testing/secure-store-mock')>('expo-secure-store')
beforeEach(() => store.__reset())
test('sign-out deletes every key and revokes the refresh token', async () => {
const api = fakeApi(() => ({ status: 200 }))
const session = createSession({ baseUrl: 'https://api.test', fetchImpl: api.fetchImpl })
await session.signIn(tokens(1))
await enableBiometricApproval('ak-1')
await session.signOut()
expect(store.__values()).toEqual([])
expect(api.calls).toEqual([{ path: '/auth/revoke', body: { token: 'rt-1' } }])
await expect(session.getAccessToken()).rejects.toBeInstanceOf(SignedOutError)
})
test('sign-out still forgets everything with no signal', async () => {
const api = fakeApi(() => {
throw new TypeError('Network request failed')
})
const session = createSession({ baseUrl: 'https://api.test', fetchImpl: api.fetchImpl })
await session.signIn(tokens(1))
await enableBiometricApproval('ak-1')
await expect(session.signOut()).resolves.toBeUndefined()
expect(store.__values()).toEqual([])
})
TS
npx jest src/auth/sign-out --ciCheck it worked
Jest reports Tests: 2 passed, 2 total. Both tests end with an empty store: no refresh token and no approval key, whether or not the server answered.
Step 7 · Start clean after a reinstall or on a new phone
Two situations leave the app with the wrong idea about who is signed in:
- iOS keeps Keychain items after the app is deleted. Someone deletes the app, reinstalls it months later, and is signed in as before, possibly as a different person who inherited the phone. Expo's documentation also warns not to rely on this behaviour either way.
- A new phone. With
_THIS_DEVICE_ONLYon iOS, and the Auto Backup exclusion on Android, the tokens do not come across.readRefreshToken()returnsnull,restore()returnssigned-out, and the person signs in again. That is the intended result.
For the first case, use a flag that does not outlive the app: AsyncStorage is deleted with the app. If the flag is missing, this is the first launch of this install, so delete any secure items left over and set the flag. The flag is not a secret, which is why AsyncStorage is fine for it.
cd ~/secure-tokens-demo
cat > src/auth/install.ts <<'TS'
import { deleteAllSecureItems } from './forget'
export interface MarkerStore {
getItem(key: string): Promise<string | null>
setItem(key: string, value: string): Promise<void>
}
const MARKER = 'auth.installMarker'
// AsyncStorage is removed with the app; iOS Keychain items are not. No marker means
// a fresh install, so drop anything an earlier install left behind.
export async function forgetTokensFromEarlierInstall(markers: MarkerStore): Promise<boolean> {
if ((await markers.getItem(MARKER)) !== null) return false
await deleteAllSecureItems()
await markers.setItem(MARKER, 'present')
return true
}
TS
cat > src/auth/install.test.ts <<'TS'
import AsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock'
import { enableBiometricApproval } from './approval'
import { forgetTokensFromEarlierInstall } from './install'
import { readRefreshToken, saveRefreshToken } from './token-store'
const store = jest.requireMock<typeof import('./testing/secure-store-mock')>('expo-secure-store')
beforeEach(async () => {
store.__reset()
await AsyncStorage.clear()
})
test('a fresh install drops tokens the Keychain kept from before', async () => {
await saveRefreshToken('rt-old')
await enableBiometricApproval('ak-old')
expect(await forgetTokensFromEarlierInstall(AsyncStorage)).toBe(true)
expect(store.__values()).toEqual([])
})
test('later launches leave the session alone', async () => {
await forgetTokensFromEarlierInstall(AsyncStorage)
await saveRefreshToken('rt-1')
expect(await forgetTokensFromEarlierInstall(AsyncStorage)).toBe(false)
expect(await readRefreshToken()).toBe('rt-1')
})
TS
npx jest src/auth/install --ciNow wire it together for the app. src/auth/index.ts creates the one session the app uses and runs the install check before restoring; a hook gives screens the result. The transfer screen uses all of it:
cd ~/secure-tokens-demo
cat > src/auth/index.ts <<'TS'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { forgetTokensFromEarlierInstall } from './install'
import { createSession, type RestoreResult } from './session'
// EXPO_PUBLIC_ values are written into the app bundle: public values only.
export const API_URL = process.env.EXPO_PUBLIC_API_URL ?? 'https://api.example.com'
export const session = createSession({
baseUrl: API_URL,
fetchImpl: (url, init) => fetch(url, init),
})
export async function startAuth(): Promise<RestoreResult> {
await forgetTokensFromEarlierInstall(AsyncStorage)
return session.restore()
}
TS
cat > src/auth/use-auth-start.ts <<'TS'
import { useEffect, useState } from 'react'
import { startAuth } from './index'
import type { RestoreResult } from './session'
export type AuthState = 'checking' | RestoreResult
// Runs the install check and restores the session once per app launch.
let started: Promise<RestoreResult> | null = null
export function useAuthStart(): AuthState {
const [state, setState] = useState<AuthState>('checking')
useEffect(() => {
started ??= startAuth()
started.then(setState, () => setState('try-later'))
}, [])
return state
}
TS
cat > src/app/transfer.tsx <<'TSX'
import { useState } from 'react'
import { Pressable, StyleSheet, Text, View } from 'react-native'
import { API_URL, session } from '@/auth'
import { approveSensitiveAction } from '@/auth/approval'
import { SignedOutError } from '@/auth/session'
import { useAuthStart } from '@/auth/use-auth-start'
export default function TransferScreen() {
const auth = useAuthStart()
const [message, setMessage] = useState('')
async function confirmTransfer() {
const approval = await approveSensitiveAction()
if (approval.status === 'cancelled') {
setMessage('Transfer not sent. Tap Confirm transfer to try again.')
return
}
if (approval.status === 'needs-password') {
setMessage('Enter your password to confirm this transfer.')
return
}
try {
const accessToken = await session.getAccessToken()
const response = await fetch(`${API_URL}/transfers/confirm`, {
method: 'POST',
headers: { Authorization: `Bearer ${accessToken}`, 'X-Approval-Key': approval.key },
})
setMessage(response.ok ? 'Transfer confirmed.' : `The server refused it (HTTP ${response.status}).`)
} catch (error) {
setMessage(
error instanceof SignedOutError
? 'Your session has ended. Sign in again.'
: 'No connection. Nothing was sent.',
)
}
}
async function signOut() {
await session.signOut()
setMessage('Signed out on this phone.')
}
if (auth === 'checking') return <Text style={styles.screen}>Checking your session</Text>
if (auth === 'signed-out') return <Text style={styles.screen}>Sign in to send money.</Text>
return (
<View style={styles.screen}>
{auth === 'try-later' && <Text>You are offline. Transfers will work when you reconnect.</Text>}
<Pressable accessibilityRole="button" onPress={confirmTransfer} style={styles.button}>
<Text>Confirm transfer</Text>
</Pressable>
<Pressable accessibilityRole="button" onPress={signOut} style={styles.button}>
<Text>Sign out</Text>
</Pressable>
<Text accessibilityLiveRegion="polite">{message}</Text>
</View>
)
}
const styles = StyleSheet.create({
screen: { gap: 12, padding: 16 },
button: { minHeight: 48, justifyContent: 'center', paddingHorizontal: 16, borderWidth: 1, borderRadius: 8 },
})
TSXCheck it worked
Jest reports Tests: 2 passed, 2 total for the install tests. On an iPhone development build, sign in, delete the app, reinstall it and open the transfer screen at /transfer: it says "Sign in to send money." rather than picking up the old session.
Step 8 · Check what ships in the app bundle
Everything in your JavaScript, including EXPO_PUBLIC_ values, is copied into the bundle that every user downloads. Put the API address in a .env file, export the Android bundle and search it:
cd ~/secure-tokens-demo
cat > .env <<'ENV'
EXPO_PUBLIC_API_URL=https://api.secure-tokens-demo.example
ENV
npx expo export --platform android
grep -a -o "https://api.secure-tokens-demo.example" dist/_expo/static/js/android/*.hbc | head -n 1The address prints, read straight out of the compiled bundle. An address is fine to publish. A payment provider's secret key, a database password or an LLM API key placed the same way could be read in the same way, so those stay on your server and the app calls your server instead. Tokens are different because they are issued per person at runtime and kept by the operating system, never compiled in.
A note on certificate pinning, which people often reach for next. Pinning makes the app refuse any TLS certificate except the ones it was built with, which stops interception through a certificate the user was tricked into trusting. The cost is that a certificate or key change on your server can lock out every installed copy until people update, and many people update apps rarely, especially on limited data. Expo has no built-in option; you would set Android's network security config (pin-set with a backup pin and an expiration date) and iOS NSPinnedDomains through a config plugin. For most apps, short-lived access tokens, rotating refresh tokens and server-side revocation give more protection for less risk. If you do pin, pin to keys you control, always include a backup pin, and plan the rotation before you ship.
Check it worked
Run the whole suite and confirm that only the two auth modules write to secure storage:
cd ~/secure-tokens-demo
grep -rl "setItemAsync" src --include=*.ts --exclude-dir=testing
npx jest --ciThe search lists src/auth/token-store.ts and src/auth/approval.ts only, and Jest reports five test suites with Tests: 15 passed, 15 total.
Next steps
- Learn how the tokens are issued in the first place with OAuth 2.1 and OpenID Connect with PKCE.
- Check that your server handles the tokens safely with the JWT mistakes that break API security.
- To delete the demo, remove the folder:
rm -rf ~/secure-tokens-demo.
Related tutorials
- Write end-to-end mobile tests with MaestroYou will have a small Maestro suite for a mobile app, with stable test IDs in React Native or Flutter, a shared sign-in flow fed by environment variables, smoke and full runs split by tags, and a CI job that runs the smoke flows on an Android emulator.
- Store data in a SwiftUI app with SwiftDataYou will build a small shop stock app that saves suppliers and products on the iPhone with SwiftData, lists them with sorted and filtered queries, survives a schema change through a migration plan, and is checked by tests that run against an in-memory store.
- Store data in a Flutter app with Drift and SQLiteYou will build a small shop credit book in Flutter 3.50 that keeps customers and what they owe in SQLite through Drift 2.35, with typed queries, a join, a list that redraws itself from a watch() stream, a tested schema migration and in-memory tests for all of it.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials