Web Storage and Cookies are used to store data on client side. Both got its own storage and expiration limits.
The benefits of using web storage and cookies is that more secure and large amounts of data can be stored locally and not affecting the website performance.
Note:
- Some browsers have cookies disabled then local storage is the best option to use.
- local storage are vulnerable to XSS attacks
Web Storage
The web storage limit is 5MB and data is never transferred to the server, it remains with the client side. The storage is per domain or protocol.
Web storage allow you to store JavaScript primitives but not Objects or Arrays.
Objects:
- window.localStorage – stores data with no expiration date or can use javascript to clear or use clear browser cache
- window.sessionStorage – stores data for one session lost when the browser tab is closed
Syntax to check if browser support web storage
if (typeof(Storage) !== "undefined") { console.log("HTML 5 support"); } else { console.log("no support"); }
localStorage and sessionStorage are perfect for persisting non-sensitive data needed within client scripts between pages, for example: preferences, scores in games.
Cookies
Cookies are included in every server request and it is mainly used for server-side reading. Cookies allow you to store strings.
Cookies are used for authentication purposes and persistence of user data, all cookies valid for a page are sent from the browser to the server for every request to the same domain – this includes the original page request, any subsequent Ajax requests, all images, style-sheets, scripts and fonts.