Web Technology Basics
Which of the following correctly describes a difference between the browser's localStorage and cookies?
- AlocalStorage data is not attached to requests automatically; the JavaScript of pages of the same origin reads and writes it
- BlocalStorage data, like cookies, is put into a header and sent to the server automatically with every request to the same site
- ClocalStorage can also be given the HttpOnly attribute, so even if a session ID is stored there, the page's scripts cannot read it
Show answer and explanation
Answer: A. localStorage data is not attached to requests automatically; the JavaScript of pages of the same origin reads and writes it
localStorage is a storage area in the browser that keeps string keys and values per origin; it has no way to set an expiry and generally remains until deleted. It is not sent to the server automatically, so to send it, JavaScript puts it into a request. Cookies are small, generally up to about 4 KB each, and are sent automatically with every request, whereas larger data can be kept in localStorage. However, the page's JavaScript can read it at any time, so if there is an XSS flaw its contents can be stolen. This risk must be considered when storing values used for authentication.
- A. Correct. localStorage data is not sent automatically; scripts of the same origin read and write it.
- B. Cookies are what is attached to requests automatically. localStorage data is not sent automatically.
- C. HttpOnly is a cookie attribute. Scripts of the same origin can always read the contents of localStorage.