React Native course · Module 9: Data storage
expo-secure-store - Secure data
In this lesson3
Store sensitive data like tokens and passwords securely!
Installation
npx expo install expo-secure-storeUsage
import * as SecureStore from 'expo-secure-store';
// Save
await SecureStore.setItemAsync('authToken', 'jwt-token-xxx');
// Read
const token = await SecureStore.getItemAsync('authToken');
// Remove
await SecureStore.deleteItemAsync('authToken');
// Check availability
const isAvailable = await SecureStore.isAvailableAsync();Auth Storage Service
const AuthStorage = {
setToken: async (token: string) => {
await SecureStore.setItemAsync('auth_token', token);
},
getToken: async () => {
return SecureStore.getItemAsync('auth_token');
},
setRefreshToken: async (token: string) => {
await SecureStore.setItemAsync('refresh_token', token);
},
getRefreshToken: async () => {
return SecureStore.getItemAsync('refresh_token');
},
clearAll: async () => {
await SecureStore.deleteItemAsync('auth_token');
await SecureStore.deleteItemAsync('refresh_token');
},
};Code for this lesson: App.tsx
import React, { useState } from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';
import * as SecureStore from 'expo-secure-store';
// Secure storage for authentication tokens
const AuthStorage = {
setToken: async (token: string) => {
// TODO: save the token via SecureStore.setItemAsync('auth_token', token)
},
getToken: async () => {
// TODO: return the token via SecureStore.getItemAsync('auth_token')
},
clearAll: async () => {
// TODO: remove the token via SecureStore.deleteItemAsync('auth_token')
},
};
export default function App() {
const [status, setStatus] = useState('No token');
const handleLogin = async () => {
await AuthStorage.setToken('jwt-poseidon-xxx');
const token = await AuthStorage.getToken();
setStatus(token ? 'Logged in: ' + token : 'Error');
};
return (
<View style={styles.container}>
<Text style={styles.text}>{status}</Text>
<Pressable style={styles.button} onPress={handleLogin}>
<Text style={styles.buttonText}>Log in</Text>
</Pressable>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#1a5276',
},
text: {
fontSize: 18,
color: '#aed6f1',
marginBottom: 16,
textAlign: 'center',
paddingHorizontal: 20,
},
button: {
paddingVertical: 12,
paddingHorizontal: 24,
borderRadius: 8,
backgroundColor: '#2980b9',
},
buttonText: {
color: '#fff',
fontSize: 16,
fontWeight: '600',
},
});Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How to install expo-secure-store?
2. When to use SecureStore instead of AsyncStorage?
These are 2 of 5 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Horizontal ordering
Arrange writing to SecureStore:
- Code editor
Complete the AuthStorage code with SecureStore.