Explain the difference between cookies, sessionStorage, and localStorage.
sobes.tech AI
Answer from AI
Scope: Cookies are accessible both on the client side and the server side. sessionStorage and localStorage are only accessible on the client side.
Lifetime: For cookies, the lifetime is set when created (using the expires or max-age attribute). If not specified, the cookie is deleted when the browser is closed. sessionStorage stores data only for the current session (until the tab or browser window is closed). localStorage stores data permanently until explicitly deleted.
Size: The maximum size for cookies is about 4 KB. For sessionStorage and localStorage, it ranges from 5 MB to 10 MB, depending on the browser.
Sending with each request: Cookies are automatically sent with each HTTP request to the domain they are set for, which can increase traffic. Data in sessionStorage and localStorage are not sent to the server.
Access method: Cookies are accessed via document.cookie (string). Access to sessionStorage and localStorage is through their respective objects using methods setItem, getItem, removeItem, and clear.
// Setting a cookie
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";
// Getting cookies
let x = document.cookie;
// Setting data in sessionStorage
sessionStorage.setItem("lastname", "Smith");
// Getting data from sessionStorage
let y = sessionStorage.getItem("lastname");
// Setting data in localStorage
localStorage.setItem("firstname", "Jane");
// Getting data from localStorage
let z = localStorage.getItem("firstname");
| Feature | cookies | sessionStorage | localStorage |
|---|---|---|---|
| Scope | Client and Server | Client only | Client only |
| Lifetime | Set at creation (expires/max-age), otherwise until browser is closed | Until the tab or browser window is closed | Indefinitely (until explicitly deleted) |
| Size | ~4 KB | ~5-10 MB (depends on browser) | ~5-10 MB (depends on browser) |
| Sent with request | Yes | No | No |
| Access | document.cookie |
sessionStorage.getItem/setItem |
localStorage.getItem/setItem |