HTTP Cookie

An HTTP Cookie (also known as a Web Cookie or browser Cookie) is a small piece of data that the server sends to the user’s browser and keeps locally. It is carried and sent to the server the next time the browser makes a request to the same server.

The role of the Cookie

  • Session state management (such as user login status, shopping cart, game score, or other information that needs to be logged)
  • Personalization (such as user-defined Settings, themes, etc.)
  • Browser behavior tracking (e.g. tracking and analyzing user behavior, etc.)

The disadvantages of the Cookie

Since the Cookie is specified by the server, each browser request carries the Cookie data, incurring additional performance overhead (especially in a mobile environment)

A way to mitigate attacks involving cookies

  • Use the HttpOnly attribute to prevent access to cookie values through JavaScript.
  • Cookies for sensitive information, such as indicating authentication, should have a short lifetime and the SameSite property set to Strict or Lax. In browsers that support SameSite, the effect of this is to ensure that authentication cookies are not sent with cross-domain requests, so that the request is not actually authenticated to the application server.

localStorage

The read-only localStorage property allows you to access a Document source (Origin) object Storage; The stored data is stored in the browser session, and the key-value pairs in localStorage are always stored as strings.

sessionStorage

The sessionStorage property allows you to access a sessionStorage object corresponding to the current source. It is similar to localStorage. The difference is that data stored in localStorage can be retained for a long time if the expiration time is not set. The data stored in sessionStorage is cleared at the end of the page session.

  • The page session remains as long as the browser is open, and the original page session remains when the page is reloaded or restored.
  • The top-level browsing session context is copied as the context for the new session when a new TAB or window opens a page, unlike session cookies.
  • Opening multiple Tabs pages of the same URL creates their own sessionStorage.
  • Closing the corresponding browser Window (Window) or TAB clears the corresponding sessionStorage.