Secure token storage
You can persist an access and refresh token pair in SecureStore while publishing session changes to the protected route.
Learning outcomes
- Explain why access and refresh tokens belong together in expo-secure-store rather than AsyncStorage or the app bundle.
- Model the token pair with a TokenStore interface that separates persistence from API requests.
- Implement an in-memory cache that stays consistent with SecureStore and rejects corrupt or incomplete token pairs.
- Publish sign-in and sign-out changes through subscriptions so AuthProvider and Stack.Protected stay synchronized.
After login, the Go API gives the app an access token and a refresh token. The app must retain both across restarts, replace them together when the API rotates them, and tell the navigation layer when the session ends. The storage choice matters because these tokens grant access to a customer's account.
Storage for credentials
React Native offers several places to keep data, but they solve different problems.
- A JavaScript variable disappears when the app process ends. The customer would have to log in again after every restart.
- AsyncStorage persists values, but it does not encrypt them. It is suitable for ordinary app data such as the cart, not credentials.
- The app bundle is public. Anyone with the installed app can inspect bundled source and configuration. A token in source code,
app.config.tsor anEXPO_PUBLIC_variable is not secret. - Secure storage is designed for small secrets. Expo SecureStore uses Android Keystore-backed encrypted storage on Android and the Keychain on iOS.
On the web, you might reach for localStorage to preserve a session. In a mobile app, persistence alone is not enough. You need storage designed for credentials.
SecureStore stores strings, not JavaScript objects. You therefore serialise the token pair as JSON before writing it.
This app uses one key, auth.tokens:
export type Tokens = {
access: string;
refresh: string;
};
const storageKey = "auth.tokens";The key contains only characters supported by SecureStore. Both tokens are stored as one JSON value.
One value for two tokens
The access token and refresh token have different responsibilities.
The access token is valid for 15 minutes. You send it with protected API requests in the Authorization: Bearer header. The Go API can identify the customer from the token without querying the database for every request.
The refresh token lets the app obtain a new token pair without asking for the customer's password again. The Week 3 API rotates it on every successful refresh. The old refresh token becomes invalid.
This rotation creates a storage problem if you use two separate keys.
Imagine the API returns a new pair. Your app writes the new access token first, then the process crashes before writing the new refresh token. The device now holds a new access token alongside an old refresh token that the server has already invalidated.
The next refresh fails, even though the app had received a valid pair.
A single JSON value avoids this partial update:
const tokens: Tokens = {
access: response.access_token,
refresh: response.refresh_token,
};
await SecureStore.setItemAsync(
"auth.tokens",
JSON.stringify(tokens)
);Both values are replaced together in one storage write. You do not have to coordinate separate writes or recover from a mismatched pair.
The TokenStore boundary
The API client needs two operations from token storage: reading the current pair and replacing or clearing it. It does not need to know which native storage implementation provides those operations.
Define that contract as an interface:
export interface TokenStore {
get(): Promise<Tokens | null>;
set(tokens: Tokens | null): Promise<void>;
}This TokenStore interface separates the consumer of tokens from their persistence mechanism.
The app supplies a SecureTokenStore backed by Expo SecureStore. The Jest tests supply an in-memory implementation with the same two methods. The API client can therefore be tested without Android Keystore, the iOS Keychain or a physical phone.
This separation also means the API client does not need to change if you later replace the storage implementation.
Validating stored values
SecureStore returns a string or null. It does not guarantee that the string contains a valid token pair.
A stored value might be malformed JSON. It might also be valid JSON containing only one token. Neither case represents a usable session.
The parser should accept an object only when both fields are strings:
function parse(raw: string | null): Tokens | null {
if (!raw) return null;
try {
const value: unknown = JSON.parse(raw);
if (typeof value !== "object" || value === null) return null;
const pair = value as Record<string, unknown>;
return typeof pair.access === "string" &&
typeof pair.refresh === "string"
? { access: pair.access, refresh: pair.refresh }
: null;
} catch {
return null;
}
}Consider this value in SecureStore:
{"access":"abc123"}It is valid JSON, but it is not a valid session. The parser returns null because refresh is missing.
Returning null lets the app treat the customer as signed out. It avoids crashing during startup or sending requests with an incomplete session.
The in-memory cache
Every authenticated API request needs the access token. Reading SecureStore on every request would repeatedly perform asynchronous calls into native storage.
An in-memory cache avoids that work. It also gives the app one current token pair to use throughout the running process.
The cache needs three states:
| Cache value | Meaning |
|---|---|
undefined | SecureStore has not been read yet |
null | Storage was read, but no valid pair exists |
Tokens object | A valid pair is available |
The distinction between undefined and null matters. Without it, the getter cannot distinguish an unread cache from a completed read that found no session.
A simplified getter looks like this:
private cached: Tokens | null | undefined;
async get(): Promise<Tokens | null> {
if (this.cached === undefined) {
const raw = await SecureStore.getItemAsync("auth.tokens");
this.cached = parse(raw);
}
return this.cached;
}After the first read, subsequent calls return the cached value. If the app has no stored pair, null is cached too. You do not repeatedly query native storage to confirm that the customer is signed out.
The cache must also remain consistent with persisted storage. That determines the order of operations in set().
async set(tokens: Tokens | null): Promise<void> {
if (tokens) {
await SecureStore.setItemAsync("auth.tokens", JSON.stringify(tokens));
} else {
await SecureStore.deleteItemAsync("auth.tokens");
}
this.cached = tokens;
this.listeners.forEach(listener => listener(tokens));
}Notice that the cache changes only after the storage operation succeeds.
If the write or deletion fails, execution never reaches the cache assignment or listener notifications. The in-memory state cannot claim that a change succeeded when SecureStore rejected it.
Passing null deletes the stored pair. Passing a token object replaces the entire pair.
Session subscriptions
The API client is not the only part of the app that changes authentication state.
Login and signup store a token pair. Logout deletes it. A rejected refresh also clears it. The navigation layer needs to respond to every one of these events.
Polling the token store from the navigation layer would be unnecessary. Instead, the store can notify listeners whenever its value changes.
A listener receives the new pair or null:
type Listener = (tokens: Tokens | null) => void;
private listeners = new Set<Listener>();
subscribe(listener: Listener): () => void {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
}The Set keeps each registered listener once. Calling subscribe returns an unsubscribe function, which removes that listener.
The set() implementation shown earlier notifies every registered listener after a successful storage operation. This means listeners receive sign-in, token replacement and sign-out changes through the same interface.
Authentication state in the provider
In the earlier authentication setup, AuthProvider read the token store once when the app started. That was enough while the login screen was the only place that changed tokens.
Now the API client can also clear the pair. For example, the backend might reject a refresh token because it has already been used. If the provider never receives that change, isSignedIn could remain true even though the store is empty.
The provider must subscribe to the store and perform an initial read.
useEffect(() => {
const unsubscribe = store.subscribe(
tokens => setIsSignedIn(tokens !== null)
);
store.get()
.then(tokens => setIsSignedIn(tokens !== null))
.catch(() => setIsSignedIn(false))
.finally(() => setIsLoading(false));
return unsubscribe;
}, [store]);The initial read determines the session after an app restart. The subscription handles changes while the app is running.
isLoading remains true until the initial read finishes. The root layout can show a loading screen during that time instead of briefly displaying the wrong route.
The signed-in state has one source of truth: whether a valid token pair exists. You do not need a separate login flag that could disagree with storage.
Session changes and navigation
The store now connects three parts of the app: the login screen, the API client and the authentication provider.


When login or signup succeeds, the authentication API stores the returned pair. The provider receives the notification and sets isSignedIn to true.
When the customer signs out, the store receives null. The provider sets isSignedIn to false. A rejected refresh follows the same path.
The protected route uses that state to control access to the (auth) and (tabs) route groups through Stack.Protected.
This is preferable to calling router.replace() from login, logout or the API client. Those operations change authentication state. The navigation layer reacts to that state independently.
The same separation works in the other direction: the API client does not need to know which screens exist or how the app navigates between them.
Local sign-out and server sessions
Deleting auth.tokens ends the local session on this device. The app no longer has a refresh token to use for another request.
That does not automatically revoke a copy of the refresh token that someone might have obtained elsewhere. Local storage deletion and server-side token revocation are separate operations.
A production application can pair local sign-out with a server-side revocation endpoint. The authentication contract in this exercise handles local sign-out through the token store.
Failure modes
Several mistakes can make authentication appear correct during one session but fail after a restart or token change.
- Storing tokens under separate keys: A crash between writes can leave a new access token with an invalid refresh token. Keeping one JSON pair under
auth.tokensprevents this mismatch. - Accepting partial JSON: A value with
accessbut no validrefreshcould incorrectly be treated as signed in. The parser must returnnullfor malformed and incomplete pairs. - Updating the cache before persistence: If SecureStore rejects a write, the cache would show tokens that were never successfully stored. Update the cache and notify listeners only after persistence succeeds.
- Reading SecureStore on every request: This repeats native asynchronous work unnecessarily. Cache the first result, including
null. - Forgetting to unsubscribe: A provider that unmounts can leave an old listener registered. Fast Refresh during development can expose this problem. Return the unsubscribe function from the effect cleanup.
The W4B2 storage tests check the behaviour at this boundary. They cover empty storage, persistence across store instances, deletion, corrupt and partial values, cache updates, failed writes and listener notifications.
The storage boundary in the API client and auth screens
The next exercise, API client and auth screens, uses this storage boundary for the complete authentication flow.
The API client depends on TokenStore, not on SecureStore. Login and signup store the token pair, and logout clears it. When the API rejects a refresh, the client clears the same store.
The subscribed AuthProvider then keeps isSignedIn synchronized with those changes. Your responsibility is to keep persistence and session state consistent so the API client and navigation layer can rely on the same token pair.
Check your understanding
Why does this app store the access token and refresh token together under auth.tokens?
References
Everything above is explained on this page; these are where it comes from (expo-secure-store (Expo SDK 58)).