Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Local Storage and Cookies

Local Storage and Cookies

Local Storage and cookies are client-side storage mechanisms in web browsers that allow you to store data persistently. They serve different purposes and have distinct characteristics. Let's explore both:

Local Storage:

Local Storage is an API in web browsers that allows you to store key-value pairs locally in a web browser. The data stored in local storage persists even after the browser is closed.

Setting an Item:

localStorage.setItem('username', 'JohnDoe');
 

Getting an Item:

let username = localStorage.getItem('username');
 

Removing an Item:

localStorage.removeItem('username');
 

Clearing all Items:

localStorage.clear();
 

Limitations of Local Storage:

  • Capacity: Local storage has a limit of about 5MB, which varies depending on the browser.
  • Scope: Local storage is limited to the same origin (domain, protocol, and port) of the website. It can't be shared across different domains.
  • Synchronous API: It operates synchronously, which means that it can potentially block the main thread if a large amount of data is being stored or retrieved.

Cookies:

Cookies are small pieces of data that are sent by a web server to a user's browser and stored on their computer. They can be accessed and modified by both the server and the client.

Setting a Cookie:

document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2021 23:59:59 GMT; path=/";
 

Getting a Cookie:

let cookies = document.cookie.split(';');
for (let cookie of cookies) {
  let [name, value] = cookie.trim().split('=');
  if (name === 'username') {
    console.log(`Username: ${value}`);
  }
}
 

Removing a Cookie:

To remove a cookie, you can set its expiration date to a past time:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
 
Limitations of Cookies:
 
1.  Size: Cookies can only store up to 4KB of data.
2. Security Concerns: Cookies can be a security risk if sensitive information is stored in them without appropriate security measures.
3. Sent with Every Request: Cookies are automatically sent with every HTTP request, which can increase network traffic.

 

Use Cases:

  • Local Storage: Typically used for storing larger amounts of data that is specific to the client's browser, such as user preferences or settings.
  • Cookies: Commonly used for managing user sessions, remembering user preferences, and for tracking and analytics.

Choosing Between Local Storage and Cookies:

  • Security: If you need to store sensitive information, consider using cookies with secure and HTTP-only flags. Local storage is not suitable for sensitive data.
  • Size of Data: Local storage can store larger amounts of data compared to cookies.
  • Performance: Local storage provides faster access times compared to cookies.
  • Compatibility: Cookies have broader support and can be used even in older browsers.