Sam Croft

Full-stack developer

Quick tip: using HTML5 localstorage to store JSON objects on a device in your PhoneGap app


Filed in: android, cordova, iOS, javascript, JSON, PhoneGap

I’ve written a couple of articles about loading remote data into PhoneGap apps (sans framework), but I haven’t mentioned a good little method of storing that data on the device so you don’t need to request it from a server again. This is a quick tip for how you can do that.

Of course, it depends on the type of data that you are loading from your server in the first place. You wouldn’t necessarily want to store data that would be out of date quickly – such as share prices or live sports scores. But there will certainly be times when you want to save the data you’ve just loaded for use at a later time, without having to load it again.

Loading data from a remote source

When loading data from a remote source I’d use jQuery or Zepto’s ajax() function like this:

    url: '',
    dataType: 'JSONp',
    success: function(data, status) {
        $.each(data, function(key, value){
            //handle the data                
    error: function() {
        //handle the error

In this example I’m accessing a fictional data source to load a news article.

Once the article is loaded the user might browse another article but later on may return to read this particular one again. You could load the article from your server again. But that’s a bit inefficient if you have already loaded it before. You could just as easily store the article locally, using HTML5’s localStorage, on the device and request the details from there. That’s pretty simple to setup.

HTML5 local and session storage

HTML5 introduced several methods of storing data within the clients browser. Two of these methods are local and session storage. localStorage saves data until it is removed by the client or app whereas sessionStorage saves data until the session ends, when the browser window/tab is closed.

Mark Pilgrim sums up HTML5 local storage as:

a way for web pages to store named key/value pairs locally, within the client web browser. Like cookies, this data persists even after you navigate away from the web site, close your browser tab, exit your browser, or what have you. Unlike cookies, this data is never transmitted to the remote web server (unless you go out of your way to send it manually).

Storing a key/value pair is very straightforward:

localStorage.setItem('yourKeyName', 'your value');

This works great for simple key/value pairs.

Storing a JSON object in local storage

Attempting to store a JSON object, or an ordinary array of data, in local storage will yield an error. Local storage requires you to store strings of information. To store a JSON object in local storage you will need to convert it into a JSON-formatted string, using the JSON.stringify() function.

Referring back to the ajax example above, we could take the data object and stringify it:

var dataToStore = JSON.stringify(data);

Then it’s just a case of storing the new JSON-formatted string in local storage:

localStorage.setItem('someData', dataToStore);

Loading a JSON object from local storage

Now that the JSON object is stored locally you can access the data directly from the device, without having to make a request to the remote server. However, because the object was previously converted to a JSON-formatted string, you will have to reverse the effects of the stringify function before you can access the data within the object. This is easily done through use of the JSON.parse() function:

var localData = JSON.parse(localStorage.getItem('someData'));

Now you can access the object and handle it as you normally would:

$.each(localData, function(key, value){
    console.log(key + ' = ' + value);

Using PhoneGap’s local storage api

The above example will work in any modern browser as well as in your PhoneGap app, but PhoneGap also provides local storage access via its api:

//setting an item
window.localStorage.setItem('key', 'value');

//loading an item
var value = window.localStorage.getItem('key');

The only difference here being window. prepended to the ordinary localStorage methods.

Putting it all together in a PhoneGap app

Taking all of this into account you might end up with something like this:

    url: '',
    dataType: 'JSONp',
    success: function(data, status) {
        $.each(data, function(key, value){
            //handle the data                
        var localData = JSON.stringify(data);
        window.localStorage.setItem('newsArticle12', localData);
    error: function() {
        //handle the error

And when you want to get access to that data the next time:

var localData = JSON.parse(window.localStorage.getItem('newsArticle12');

$.each(function(key, value){
	//handle the data

This is a useful technique to use in PhoneGap apps, it can be a significant optimisation when used appropriately. It reduces server requests and loads your [previously loaded] data faster.

Some considerations

There are some considerations with using local storage though.

There is a limit to how much data you can store via localStorage – approximately 5mb. If you are dealing with a lot of data you could soon reach that limit.

The main consideration should always evaluating the type of data that you are storing locally. Maybe sessionStorage is the better choice if your users require up to date information each time they open your app. Or maybe you need to include an expiry data in your JSON object and check against that before serving the data.

Related articles

About the author

I'm Sam Croft a full-stack developer with over 15 years experience in web and app development. For the last six years I have been a partner of Running in the Halls, an app and game design studio based in Huddersfield, UK. During this time I have developed many web and applications. Highlights include a node.js/ app to create the worlds largest crowd-based game on the first series of Channel 4's Gadget Man with Stephen Fry and Librarygame, a Library gamification platform for Universities. Librarygame is being played by over 6,000 students at The Open University, The University of Manchester, The University of Glasgow and The University of Huddersfield.

In my spare time I enjoy long distance running, watching all sports (especially F1) and playing video games. I live in the Holme Valley in West Yorkshire with my wife, Alex.

Sometimes I tweet.

  • Jamie Reynolds

    Nice write up Sam. I used local storage extensively in my last phonegap project and it worked very well.

    As weather app, storing the huge list of locations reports are available for made sense. There is no point fetching that data from the API each time a user wants to search for a location. Plus – once stored the this whole process is much faster.

    However, the expiry date point is a good one. You need to have some method of updating the data.

  • Thanks Jamie. Which weather app was this? Would love to have a look :]

  • Jamie Reynolds

    Sure! I’ll get you a promo code.

  • Ah great, look forward to having a play!

  • Burak

    can u make a tutorial how i can make app they load data from external server (images, text etc.) and save it offline. Please :D :D :D

    PS: Love u r articles

  • Mirco


    this is my landmarks.php, but dosn’t work

    1, ‘b’ => 2, ‘c’ => 3, ‘d’ => 4, ‘e’ => 5);
    $data = json_encode($arr);

    echo $data;

  • Nice post. With regards to placing an expiry data or date into your json object… I went a different route. I’m also storing a large json object as a string in localstorage, but I just added a second localstorage variable/record (lets call it “country-state-json-version”) containing a version number for my JSON object. This way when my app loads I can quickly compare my local version with my latest version on the server to determine if I need to reload the json obj.

  • Checkout HTML5’s Cache Manifest feature… That’s how you would accomplish loading external resources such as images and files, and saving them for offline use.

  • Hi Jason, that’s very clever. I will definitely use that approach from now on. Thanks for sharing!

  • Pingback: Quick tip: using HTML5 localstorage to store JSON objects on a device in your PhoneGap app | Snabbels Blog()

  • Vee

    Hi, how to know the right url for the application?

  • platzh1rsch

    perfect, exactly what I was looking for. Thx a lot!

  • Mark

    Thanks for the info, helpful~~

  • Kyle Traveler


  • Yingshen Chen

    web app is the future, no doubt

  • Deepan

    Sam, iam Working in Social Networking app like facebook walls… is there any metodolgy to folow that wall post storages, and Static storage as well

  • Simona Butnaru

    Hi Sam. I enjoyed this article and it was easy to understand. Still I have one question, how can I store locally an JSON object bigger than 5mb? Thanks.

  • Hi Simona,

    That’s a large JSON object! I think you would need to use the HTML5 file API. There is a Cordova plugin – I haven’t used it before, but it should be good for a 5mb file.

  • Simona Butnaru

    What do you think about Storage support from Phonegap? As I was doing research I found that using Sql Lite Database is a good way to manipulate data and storage objects of big dimension.

  • That would work. You’d have to use a native SQLite database though as I believe the storage API for PhoneGap just uses the HTML5 localStorage and Web SQL database API. Which both have 5mb limits. This plugin looks good –

  • Simona Butnaru

    I’ll have a look. Thanks Sam, for your help. Have a nice weekend!

  • No problem. You have a nice one too!

  • saurabhgupta0508

    Hi ,

    I am using local storage in my cordova app with localstorage-db.js for sql like functinality. It provides a neat solution, but i am just wondering about the life of localstorage. Can local storage be used as a alternative to the native storage provided in the native apps. Whether it will be flushed if we update the application.

  • Hi,

    In my experience localstorage will persist until the app is uninstalled, or the data/cache is cleared manually in settings. App updates should not affect localstorage.

  • Midix

    Does localStorage or PhoneGap’s localStorage work on Windows Phone? I tried localStorage on my desktop IE in a local file and IE told me that it does not support localStorage for local files. As we know, PhoneGap/Cordova apps are essentially a bunch of files accessed locally from a folder, thus I’m curious if IE on Windows Phone also has the restriction regarding localStorage and local files.

  • Hi Midix,

    It sounds like Windows has some quirks with localstorage. I noticed this on Phonegap’s documentation…

    Windows Phone 7 Quirks

    Dot notation is not available on Windows Phone 7. Be sure to use setItem or getItem, rather than accessing keys directly from the storage object, such as window.localStorage.someKey.

  • can you please give me one example on this

  • megs654

    If I store an object in local storage e.g.

    var testObject = { ‘firstName’: fname, ‘secondName’: sname};
    localStorage.setItem(‘testObject’, JSON.stringify(testObject));
    var retrievedObject = localStorage.getItem(‘testObject’);
    console.log(‘retrievedObject: ‘, JSON.parse(retrievedObject));

    how do i access the testObjects firstname value only eg is there a way to do something like retrievedObject.firstName?

  • Absolutely. That is exactly how you would do that. Or you could use square brackets for the key name. Just make sure use JSON.parse on the string beforehand, e.g.

    console.log(‘firstName: ‘, JSON.parse(retrievedObject).firstName);


    var retrievedObject = JSON.parse(localStorage.getItem(‘testObject’));
    console.log(‘firstName: ‘, retrievedObject.firstName);

    Hope that helps!

  • She Ramirez

    Hi Sam,

    I was confused. Is it possible to create a pagination if all the data is stored in LocalStorage not in database?

    Thank you

  • Mustafa

    Extremely useful! Exactly what I was looking for. Just one question. How to accomplish “next time” part. Means every time code for loading data from server will run. How app will know: this is “not first time”, data is already stored locally. I (app) need not fetch it from server.

    Please rpy am really looking forward towards it.

  • Ganesh

    Nice one Thanx..

  • Nishanth Vijayan

    Thank you.This was really helpful.

  • GreenDome

    Hi Jason, do you have working example of this method? I need to compare local version with online and replace if outdated. Please can you point me in the right direction? Thanks,