Sobes.tech
Junior — Middle

What are the differences between storing data in cookies and sessionStorage in web applications?

sobes.tech AI

Answer from AI

Cookie and sessionStorage are two methods of storing data on the client side, but they have important differences:

  • Scope and lifespan:

    • Cookies are stored in the browser and sent to the server with each HTTP request to the domain until they expire or are deleted. You can set a cookie's lifetime.
    • sessionStorage stores data only within a single browser session (tab). Data is deleted when the tab is closed.
  • Data volume:

    • Cookies are usually limited to about 4 KB per cookie.
    • sessionStorage allows storing more data (usually up to 5 MB), but only on the client.
  • Accessibility:

    • Cookies are accessible both on the client (JavaScript) and on the server (when receiving requests).
    • sessionStorage is only accessible on the client via JavaScript.
  • Security:

    • Cookies can be protected with HttpOnly and Secure flags, which restrict access from JavaScript and ensure transmission only over HTTPS.
    • sessionStorage is not sent to the server and is only accessible from scripts in the current tab.

Example of using sessionStorage:

// Saving data
sessionStorage.setItem('user', 'John');

// Retrieving data
const user = sessionStorage.getItem('user');

// Removing data
sessionStorage.removeItem('user');

Thus, cookies are suitable for storing data that needs to be accessible to the server and persist across sessions, while sessionStorage is for temporary storage of data on the client within a single session.