Sobes.tech
Senior

What are cookies and what are they responsible for? How do cookies differ from localStorage?

sobes.tech AI

Answer from AI

Cookies are small pieces of data that a web server sends to the browser, which stores them and sends them back to the server on subsequent requests. They are used to store information about the user's session, authentication, preferences, and other data that needs to persist between requests.

Differences between cookies and localStorage:

  • Scope and server transmission: Cookies are automatically sent to the server with each HTTP request to the relevant domain, whereas localStorage is only accessible on the client side and is not transmitted to the server.
  • Storage capacity: Cookies are usually limited to about 4 KB, while localStorage can store around 5-10 MB of data.
  • Expiration: Cookies can have an expiration date after which they are deleted; localStorage stores data indefinitely until manually removed.
  • Security: Cookies can be marked as HttpOnly, making them inaccessible via JavaScript, which enhances security; localStorage is accessible via JavaScript and vulnerable to XSS attacks.

Example of using a cookie in an HTTP header:

Set-Cookie: sessionId=abc123; Path=/; HttpOnly; Secure; SameSite=Strict