Storing data clientside is one of the new possibilities made available with HTML5 and the modern browsers. There are easy ways for storing strings and JS objects, but when we need to replicate a database structure there is no easy solution.
Use localStorage methods with a local Database abstraction as LocalStorageDB.js
Currently, I am developing a simple time tracker app. I need it to work both on desktops and on mobile browsers. As far as the serverside is concerned, I am using MySQL to save data and I want to bring the same data clientside. Unfortunately, there is no shared solution to manage a DB clientside.
The two solutions to manage a Database on the client are totally different and they have one big issue: they are not able to work both on mobile operative systems (iOS and Android) and on desktop browsers.
The only thing they share is their complex syntax.
The two available and incompatible solutions
There are two different solutions available to manage a Database on the client, but they do not work both on mobile and on desktops.
The only thing that they share is the complex syntax.
On the one hand, IndexedDB:
- Is a W3C draft implementation
- Works on desktop browsers
- Is not supported on mobile platforms
- Is implemented differently among browsers
On the other hand, WebSQL:
- Works on mobile
- Is deprecated
- Is not supported by Firefox and other browsers
Polyfill and libraries
As WebSQL is deprecated, there is no sense in developing an application with this technology, especially if we consider that several browsers (such as Firefox) do not support it. As a consequence, the only solution is to use IndexedDB.
By choosing IndexedDB, we can make it work on mobile browsers with a polyfill and also simplify its complex syntax with a library. The Modernizr team sums up the possible solutions in its polyfills page.
However, both polyfill and libraries are quite young, incomplete and they have bugs. I need a more reliable solution.
The easier way: a LocalStorage abstraction script
During my research, I came across an interesting solution: a local Database abstraction script called LocalStorageDB.js
It recreates methods similar to SQL to manage, retrieve and store data on the client with LocalStorage. The pros of this well developed library are:
- Wider browser support (IE8+ and modern browsers)
- Quite fast (even if not fast as IndexedDB)
- Easier syntax
Basically, this library uses browser’s localStorage API as the basis for a simple database. Indeed, LocalStorageDB methods allow you to create tables, update and retrieve data and perform basic query operations as SQL does.
If you want to read more about this solution, please check the project page or my blog post.