How to save login state locally using AsyncStorage & Redux in React Native

Kit Bunrong

Bunrong / February 10, 2022

3 min read

Why save locally?

  • To "remember" their situation (logged in : true or false).
  • Depending on what the status is you can choose to show some app screens (like profile page, content page) and skip others (like login page, sign up page).

What about Redux?

Redux can only maintain the state till the app in "on". If the user exits the app, or say for example, reboots the phone or the app crashes the state resets.

Where to store user information after login — React Native

  • Usually, the first solution that developers think about is AsyncStorage. It’s a simple key/value database. AsyncStorage simply saves data into documents on the phone’s hard drive, and therefore anyone with access to the phone’s file system can read that data.
  • On iOS, the data is indeed only available to the app that wrote it, because of Apple’s sandboxing policy. This doesn’t stop jailbroken iPhones with root access to the file system from getting whatever they want, since AsyncStorage does not encrypt any of its data. But in general, don’t save sensitive data to AsyncStorage, for the same reason you shouldn’t hard code sensitive data in your javascript code, since it can be easily decompiled and read

So we can agree that AsyncStorage is not an option. Wouldnt it be great if there would be a solution similar to AsyncStorage just secure? Luckily, there are quite many libraries that can be used. For example, there are react-native-keychain and react-native-encrypted-storage

How do react-native-encrypted-storage and other similar packages securely store data? »

They do not use any new technologies developed exclusively for React Native and they do not use encryption. What they do is create a bridge between JavaScript and Keychain Services (iOS) and Secure Shared Preferences (Android) or Keystore (Android).

iOS — Keychain Services

Keychain Services allows you to securely store small chunks of sensitive info for the user. This is an ideal place to store certificates, tokens, passwords, and any other sensitive information that doesn’t belong in Async Storage.

Android — Secure Shared Preferences

Shared Preferences is the Android equivalent for a persistent key-value data store. Data in Shared Preferences is not encrypted by default, but Encrypted Shared Preferences wraps the Shared Preferences class for Android, and automatically encrypts keys and values.