Don't Assume localStorage Will Always Work In Your Hybrid App

17 June 2015Ionic, Cordova, PouchDB, Local Storage

There are several ways to store data locally in a Cordova/PhoneGap app and the simplest way is to use localStorage, which provides a way to store key-value pairs.

// simple example
localStorage.setItem('name', 'Pinky');
var name = localStorage.getItem('name');

// complex example
var records = [{ name: 'Pinky', age: 1 }, { name: 'Brain', age: 2 }];
localStorage.setItem('records', JSON.stringify(records));
var output = JSON.parse(localStorage.getItem('records'));

If you're using localStorage in a Cordova/PhoneGap app, you'll get a limit of 5 MB on both iOS and Android.

The data that is saved in localStorage is supposed to be persisted even if you close the app or turn off your phone. In most cases this will work, but there are issues with the way iOS and Android manage localStorage on the devices.

###iOS On iOS 8 the localStorage is sometimes cleared when memory is low, as you can read here.

I recently experienced it myself on an Ionic app I was working on. I got a notification on my iPhone that it was running low on memory and when I opened up the app the localStorage was empty. I had another app on my device that was using localStorage as well, but that one was not cleared.

###Android I haven't tested this extensively on Android, but if you read this thread, you'll see that there are several reports that localStorage doesn't work as expected.

So... Should I never use localStorage?

You should use localStorage only for data that does not need to be persisted. A good case would be caching data that you're retrieving from an external source. If localStorage is cleared unexpectedly, you can still get the data again.

###Alternatives For persisting user data, if you want to keep the users of your mobile app happy, you're better off using SQLite.

Or you could use PouchDB, an open-source JavaScript framework that encapsulates WebSQL, IndexedDB and SQLite. If you want to learn how to do that, read this tutorial I wrote about using PouchDB for local storage.

==Update: Instead of PouchDB you can also use LokiJS, a fast in-memory database. Read my tutorial for LokiJS.==

Have you experienced problems with localStorage or do you not agree with me? Let me know in the comments!

####Read More localStorage: Use it, Don't Abuse It

Ashteya Biharisingh

Full stack developer who likes to build mobile apps and read books.