React Native Data Encryption: Secure Redux Store Persistence

Implement Encryption for Mobile App Data Security

Isometric illustration on a dark navy ground of a phone with data cards on its screen, arrows passing through key-marked cubes into a glowing vault box with padlocks and shields, set on an exposed phone circuit board Image credits: Google Gemini

Users’ need for privacy and data security keeps increasing daily and it will always be in demand. So how do we store data on a mobile device without worrying about security? In this article, we’ll go through an effortless and quick way to:

  • Set up persistent storage for our app and store any user data locally.

  • Encrypt the data to make it secure so users feel less worried about their privacy.

So, let’s get started!


Setting Up Persistent Storage

First, we’ll set up persistent storage for our app. For this, we’ll use an excellent and easy-to-use library called redux-persist. Most of you must be familiar with redux. For those unfamiliar, it is a simple way to manage and share data in your React and React Native apps across various components and views. You can read more about it in my article on redux and how to use it in React and React Native apps.

Open the terminal and type the following command on your project’s root directory:

Terminal window
npm i redux-persist @react-native-async-storage/async-storage

This command will install redux-persist, which will help us to retain our data from previous sessions, and the Async Storage module it will write to.1

note

We’ll use redux-promise as our middleware for the examples in this article. You can use any middleware, like redux-saga or redux-thunk, based on your requirements!

Now let’s set up our store to make it persistent — so that the next time our app loads up, we’ll have data saved from the previous session. On your main store.js, set up persistent storage like this:

store.js
import { combineReducers, createStore, applyMiddleware } from 'redux';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { persistReducer, persistStore } from 'redux-persist';
import promise from 'redux-promise';
// Create the root reducer as you normally would.
const rootReducer = combineReducers({
myPersistentData: dataReducer,
someMorePresistentData: randomReducer,
});
/*
Create the configuration object to be used for transforming our simple
root reducer into a property on persistent storage.
*/
const config = {
key: '_myPersistentDataKey',
storage: AsyncStorage,
};
// Make your reducer persistent with persistReducer()
const reducer = persistReducer(config, rootReducer);
const store = createStore(
reducer, // Your persistent reducer
{}, // Initial store state
applyMiddleware(promise), // middleware(s)
);
// Convert your store to be persistent accross app sessions.
const persist = persistStore(store);
export default { store, persist };

In the main App.js file, modify the render function like this:

App.js
import { PersistGate } from "redux-persist/integration/react";
import { Provider } from "react-redux";
import store from "./store";
import MyRootComponent from "./src";
class App extends Component {
constructor(props) {
super(props);
// ...
}
render() {
return (
<Provider store={store.store}>
<PersistGate persistor={store.persist}>
<MyRootComponent />
</PersistGate>
</Provider>
);
}
}
export default App;

That’s it! We’ve set up our redux state to be persistent! Easy.


Encrypting Persisted Data

For this, we’ll use redux-persist-transform-encrypt. Run the following command on your project’s root directory:

Terminal window
npm i redux-persist-transform-encrypt

This will help us encrypt and decrypt user data across multiple sessions.2

important

Since this was just an example of how to encrypt your data, we hard-coded our secret key into the source code, but you must never do that! Anything in your app code can be read by someone who inspects the bundle, so keep the key in the platform’s secure storage (the iOS Keychain or the Android Keystore) and read it when the app starts.3

Now, open the store.js file again and update it to look like this:

store.js
import { combineReducers, createStore, applyMiddleware } from 'redux';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { persistReducer, persistStore } from 'redux-persist';
import promise from 'redux-promise';
import { encryptTransform } from 'redux-persist-transform-encrypt';
const rootReducer = combineReducers({
myPersistentData: dataReducer,
someMorePresistentData: randomReducer,
});
/*
Configure your encryptor with the secret key
NOTE: This secret key is required for access to data.
If the key is incorrect or changed after storing data
with some different key, the old data cannot be decrypted:
onError is called and the app starts from its initial state.
*/
const encryptor = encryptTransform({
secretKey: 'my-not-so-secret-encryption-key',
onError: (error) => {
console.warn('error occured on encryptor', error);
},
});
const config = {
key: '_myPersistentDataKey',
storage: AsyncStorage,
/* Add the encryptor as a transform property. This is will
tell the persistent storage to encrypt data using the
configuration given earlier,i.e., our secretKey. */
transforms: [encryptor],
};
const reducer = persistReducer(config, rootReducer);
const store = createStore(
reducer,
{},
applyMiddleware(promise),
);
const persist = persistStore(store);
export default { store, persist };

Awesome! We made the data in our store state persistent locally, along with encryption! 🎉 👏

Congrats now we’ve encrypted our locally persisted react native application data.

bonus

Happy hacking! Cheers! 🎉

Footnotes

  1. redux-persist/lib/storage is the web build, backed by localStorage. redux-persist’s README uses @react-native-async-storage/async-storage for React Native. In a probe in a runtime with no localStorage, importing the web storage logged “redux-persist failed to create sync storage. falling back to noop storage.” ↩

  2. The README of redux-persist-transform-encrypt 5.1.1 exports encryptTransform and says secretKey is a passphrase used to generate a 256-bit AES key. In a probe, each reducer’s slice was stored as U2FsdGVkX1... ciphertext with no plaintext in it, and a different key logged “Could not decrypt state” and started from the initial state. ↩

  3. React Native’s security docs say anything in your code can be read in plain text by anyone inspecting the app bundle. They call Async Storage unencrypted, fine for persisting Redux state, and not for tokens or secrets. They point to the iOS Keychain and the Android Keystore for sensitive data and keys. ↩

For clients Work with me Web, mobile, UI/UX design, performance, accessibility and DevSecOps projects, outside working hours and a few at a time.