DEV Community

Adel
Adel

Posted on

Browser Storage APIs

1- Cookies

Cookies are small pieces of text data stored in the browser mainly used for authentication, tracking and personalization.

Cookies can be read and set by browser and server with certain rules, hold 4069 bytes of data.

For more details I have an article “Cookies: simple and comprehensive guide

To set a cookie using javascript

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
Enter fullscreen mode Exit fullscreen mode

2- Web Storage

Similar to cookies, pieces of text data stored in the browser. It can hold up to 5MB and can be read and set only by the browser.

It offers simpler APIs than cookies and all Web Storage calls are synchronous.

The two mechanisms within Web Storage are as follows:

  • Local Storage

    No expiration date.

  • SessionStorage

    data is stored until the tab is closed.

Code Example

localStorage.setItem('myCat', 'Tom');
const cat = localStorage.getItem('myCat');
localStorage.removeItem('myCat');
localStorage.clear();
Enter fullscreen mode Exit fullscreen mode

3- IndexedDB

A Transactional NoSQL database system built in the browser. It can be used synchronously and asynchronously.

If you have big amount of data or files that needs to be stored in the browser, IndexedDB is a good option.

While it includes more features than traditional Web Storage API, using IndexedDB is also more complex, for that there are open source libraries to simplify it like localForage which wraps IndexedDB API and makes it as simple as using Web Storage API

4- Cache

Used mainly to optimize the performance of the website by storing its files to not be downloaded again when you open the same website again.

You can cache any response whether it’s HTML, Javascript, CSS, image, font or even API response.

The storage allowed for cache storage is different per browser, for example Chrome allow to take 80% of available disk space.

Top comments (0)