Difference between Local Storage, Session Storage, and Cookies?
Local Storage, Session Storage, and Cookies are all web solutions, but they have different features and use cases:
1. Local Storage:
- Persistence: Data stored in Local Storage has no expiration time and persists even after the browser is closed.
- Scope: Accessible within the entire domain.
- Capacity: Can store up to 5MB or more per domain.
- Example:
-
// Saving user preferences like theme color: localStorage.setItem('theme', 'dark') // Fetch theme color: localStorage.getItem("theme");
2. Session Storage:
- Persistence: Data stored in Session Storage is cleared when the page session ends (i.e. when the tab or browser is closed).
- Scope: Accessible only within the same tab and session.
- Capacity: Can store up to 5MB per domain.
- Example:
-
// Storing a user's progress on a form they are filling out: sessionStoreage.setItem('formProgress','step2'); // We can access fill out details: sessionStorage.getItem("formProgress");.
3. Cookies:
- Persistence: This can be set to expire at a specific time or when the browser closes.
- Scope: Send to the server with every HTTP request, accessible across subdomains if configured.
- Capacity: Can store about 4KB per cookie.
- Example:
-
// Storing a user's login session ID. document.cookie = "sessionId=abc123; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";