Sobes.tech
Middle

How do cookies differ from localStorage? What is the maximum size of cookies and localStorage? How does their lifetime differ?

sobes.tech AI

Answer from AI

Differences between cookie and localStorage:

  • Storage and access:

    • Cookie — data sent to the server with each HTTP request to the corresponding domain.
    • localStorage — data stored only on the client side and not sent to the server automatically.
  • Size:

    • Cookie is usually limited to about 4KB per cookie.
    • localStorage typically allows storing about 5-10MB of data per domain (depends on the browser).
  • Lifetime:

    • Cookies can have a set expiration time (via the Expires or Max-Age attribute). If no expiration is set, the cookie is session-based and deleted when the browser is closed.
    • localStorage stores data indefinitely until explicitly removed via script or browser settings.
  • Security:

    • Cookies can be marked as HttpOnly, which prevents access via JavaScript.
    • localStorage is accessible only through JavaScript.

Example of setting a cookie and writing to localStorage:

// Setting a cookie for 7 days
document.cookie = "username=John; max-age=" + 7*24*60*60 + "; path=/";

// Writing to localStorage
localStorage.setItem('username', 'John');

Thus, cookies are suitable for transmitting data to the server and managing sessions, while localStorage is used for storing large amounts of data on the client with a long storage duration.

How do cookies differ from localStorage? What is the… - sobes.tech