How to store data securely into local storage using react-secure-storage ?

Sushin Pv
3 min readJun 12, 2022

--

How to secure local storage using react-secure-storage

The problem statement!

Most users save data to local storage. Is this a secure means of storing data?
No!
Anyone with access to the device can read and manipulate the data written to local storage as a plain string.

Encryption and decryption is a ways to save data securely to localStorage. However, in this scenario, you’ll need a shared secure key to encrypt and decrypt data.

Consider the following scenario: you’ve encrypted the user’s login information and saved it locally. When you reload the platform, you’re decrypting the data that’s been written to local storage and marking the user as logged in or logged out. Your website and the platform use a single secure key to encrypt and decrypt, which means only your website knows how to decrypt.

If someone copies data from local storage and pastes it into a separate browser, then visits your site, your website will authenticate the user. Why?
because your website understands how to decode data!

This is the problem when you have a single secure key! Then how do we solve this issue ?

The solution is to produce a secure key depending on your website and browser; lets have a look at react-secure-storage library!

We have the ability to use Secure Storage in React Native; what if we had the same power in ReactJs?

Why React Secure Storage ?

React secure storage was created to securely write data to local storage (basically, it’s a wrapper written on top of default localStorage to write data securely to localStorage). The secure storage library generates a secure key for each browser and encrypts the data with this key, meaning that only the browser that encrypted the data can decrypt it.

Additionally react secure storage preserve the data format for every data type, As out of the box it supports the following data types

String | Object | Number | Boolean

Which means you don’t need to explicitly convert every data to string

How does it work ?

React secure storage is written in Singleton design pattern, When the library is initialized, it reads all the data from local storage and decrypts all the data written using react-secure-storage and saves it to memory. This ensures faster reading of all the data.

The key is created using a browser fingerprint, which is made up of 10+ browser key identifiers and a secure key entered by the user.

The user specific Secure key can be configured using .env file as

SECURE_LOCAL_STORAGE_HASH_KEY=xxxxxxxxxxxxxxxx

or

REACT_APP_SECURE_LOCAL_STORAGE_HASH_KEY=xxxxxxxxxxxxxxxx

How to use

To use the library first you need to install using

yarn add react-secure-storage

or

npm install react-secure-storage

You can use the following methods to read and write items to secure local storage

Read more about the library here https://www.npmjs.com/package/react-secure-storage

Sample Code

--

--