CodeBlanks Logo Icon CodeBlanks

Token storage

Learn secure auth token storage.

Token storage

The session token lets the user continue their session. The server returns a token when the user logs in; you write this token to the secure store. On each API request you read the token and add it to the Authorization header. This pattern prevents the user from re-entering the password.

The token is usually a long string: like 'eyJhbGciOiJIUzI1NiIs...'. This value is sensitive; it is not written to AsyncStorage, only to expo-secure-store. When making an API request you add headers: { Authorization: `Bearer ${token}` }. When the token expires a refresh flow runs; the user logs in again.

The Bearer scheme

In API requests the token is sent with the Bearer scheme. The Authorization header has the form Bearer <token>. This tells the server that the token is a 'bearer token'. It is written with a template string: `Bearer ${token}`.

The word Bearer starts with a capital letter and a space is left. This syntax is part of the OAuth 2.0 standard. If the server does not see the Bearer prefix in the header it rejects the request. So the correct syntax is mandatory. After reading the token with getItemAsync you add it to the header immediately; the token is not kept in memory after the request completes.

Practice Add the token to an API request

Complete the fetchWithAuth function. Read the token with const token = await SecureStore.getItemAsync('token'). If !token, return null. Otherwise call return fetch(url, { headers: { Authorization: `Bearer ${token}` } }). url is passed as a parameter.

Starter code

App.js
import * as SecureStore from 'expo-secure-store';

export async function fetchWithAuth(url) {
  // read the token, call fetch with the Authorization header
}

Sample solution

App.js
const token = await SecureStore.getItemAsync('token');
if (!token) return null;
return fetch(url, {
  headers: { Authorization: `Bearer ${token}` },
});

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Where should the token be stored?

App.js
const token = 'eyJhbGciOiJIUzI1NiIs...';
  • AsyncStorage (plain text)
  • In state (memory)
  • SecureStore (encrypted) Correct answer
  • With console.log

Explanation: The token is written to SecureStore; encrypted and safe.

2 Write the Authorization header

Question
headers: { Authorization: `Bearer ____` }
Answer
headers: { Authorization: `Bearer ${token}` }

Explanation: ${token} embeds the token in the string.

3 Match each part to its role

Term Meaning
setItemAsync Writes the token
getItemAsync Reads the token
deleteItemAsync Deletes the token
Bearer Authorization scheme

All lessons in Advanced