Sobes.tech
Junior

Selgitage erinevust küpsiste, sessionStorage ja localStorage vahel.

sobes.tech AI

Vastus AI-lt

Visibility area: 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 at creation (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 — 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: Access to cookies is via document.cookie (string). Access to sessionStorage and localStorage is via the 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 a cookie
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
Visibility area Client and server Client only Client only
Lifetime Set at creation (expires or max-age), otherwise until browser closes Until tab or browser window closes Indefinite 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 method document.cookie sessionStorage.getItem/setItem localStorage.getItem/setItem