Getting To Know: HTML5 Local Storage

HTML5 local storage is an underutilized feature which allows developers to store data as key/value pairs within a user’s browser. While local storage may not be a replacement for cookies, it does offer 5MB to persist data beyond page refreshes and browser sessions. A working knowledge of HTML5 local storage is certainly worth adding to your tool belt.

Example Code: GitHub

The API
The local storage API exposes three methods for our consumption:
1.)localStorage.getItem(“[id]”)
2.)localStorage.setItem(“[name]”,”[value]”)
3.)localStorage.removeItem(“[id]”)
In a simple example, the API can be used as follows:

Storing Objects
It is also quite simple to store fully formed objects in local storage. The only caveat is remembering to serialize and deserialize between entry and retrieval.

Putting it Together
I put together a small example storing a user’s form input in local storage, allowing them to close the browser and come back to finish the form later. This particular example may be a bit contrived, but it does show the potential and versatility of HTML5 local storage should you choose to utilize it in a project of your own.

Conclusion
While the use of the local storage API may not make or break a project, it does offer an interesting take on persisting data on a user’s browser. Hopefully you will be able to find a use for this mechanism on a project of your own. Until next time, happy coding!

Next ArticlePractice Makes Perfect: Streamline Your JavaScript Learning Experience