Cookies are something which everyone in web development must have heard off and would have used although I am bit surprised to know the awareness of HTML5 Web Storage among people.
It wouldn’t be fair to say that it’s a new concept as it’s been a while since Web Storage is around and yesterday post encountering another blank face to Web Storage, I thought of writing and sharing this on my blog. So let’s get on to it.
HTTP Cookies
HTML 5 Web Storage
Enlightenment
There are three major difference between how Cookies and Web storage works.
- Web storage provides far more storage capacity than cookies. Where cookies are limited to 4 KB, the benchmark capacity for Web Storage is 5 MB and even this limit varies with browsers. Some browsers provide even higher storage.
- Second and the most significant difference is, Cookies are sent with each HTTP request once they are set but web storage data is not. This can improve the performance of your site.
- Web Storage is more secure than Cookies as it is designed to operate at domain & protocol level.
- Web Storage also been around from a while now but is only supported on browsers supporting HTML 5. Hence if you need to provide support for legacy browsers then this could be an issue for you.
- Web Storage is completely client based hence it cannot be accessed or modified from server side.
As I mentioned earlier, Web storage comes in two forms. Local Storage and Session Storage. The difference is really simple and straight forward as explained below.
Local Storage
This is how you can set/get local storage from JavaScript as below:-
// Set
localStorage.setItem("fullName", "Piyush Gupta");
// Get
var name = localStorage.getItem("fullName");
Or below is also valid
// Set
localStorage.fullName = "Piyush Gupta";
// Get
var name = localStorage.fullName;
Session Storage
Please note, the data can survive page load or redirects but is bound to one specific tab. Any new tab or window cannot access session data set by previous tab.
You can set/get session storage from JavaScript as below:-
// Set
sessionStorage.setItem("fullName", "Piyush Gupta");
// Get
var name = sessionStorage.getItem("fullName");
Or below is also valid
// Set
sessionStorage.fullName = "Piyush Gupta";
// Get
var name = sessionStorage.fullName;
Word of advice:-
As I mentioned already, although Web Storage is now supported by almost all browsers but please don’t blindly assume this and always perform a check whether web storage is supported by user's browser or not before using it. You can do this by below:-
if(typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}
You can check the list of supported browsers here.
That’s all I had to share with you. Choose wisely when deciding how you want to keep you data on client side. Cookies are good and still widely used but Web Storage does provide some benefits over it.
No comments:
Post a Comment