Browser Thematic Series – Local storage

There are several storage schemes available in modern browsers

  • cookie
  • localStorage
  • sessionStorage
  • indexDB

The following is a detailed description of the application scenarios and disadvantages of various schemes

Cookie

Introduction to the

Data stored on a user’s local terminal primarily for identification purposes

It can record the user’s visit to the website (stay time, visit depth, record account password, online status, etc.)

It is mainly generated and delivered by the server, and the client can control its content

Each request will automatically carry the cookie of the corresponding domain name

How to use

The service side

The server adds a set-cookie field to the Response Header

The sample

Set-Cookie:"name=value; expires=session; path=/; domain=.sugarat.top; HttpOnly; secure; sameSite=lax"
Copy the code

Client (browser)

document.cookie
Copy the code

Cookies can be obtained or modified through this API

Set-Cookie

This section describes the properties of the set-cookie field

Cookie attribute Introduction to the Special instructions
name key
value value
Expires Expiration time A fixed time
Max-Age Expiration time How long after this cookie is received Expires. Priority is greater than Expires
Domain Deliverable host name (domain name)
path Effective path The path must appear in the path of the resource to be requested before it can be sent
Secure Safety sign This cookie is carried only when the HTTPS protocol is used
HTTPOnly Safety sign Scripts to change/retrieve this cookie are not allowed
SameSite Safety sign Controls cross-site requests to get cookies

Attribute Description

  • Expires: The value is the default session, meaning that the cookie Expires when the browser is closed
  • Max-age: The effect varies with the value range
    • Greater than 0: the cookie is saved to a local file
    • If the value is 0, the vm is deleted immediately
    • Less than 0: equivalent to a session cookie
    • Priority exceeds Expires
  • Domain: specifies the host name to which cookies can be delivered
    • Not specified: The default is the host part of the current document access address (excluding the subdomain)
    • If set to.a.comthena.com.a.a.com.b.a.comEtc., i.ea.comThe cokie is accessible to all subdomains of the
  • HTTPOnly
    • Prevents client scripts from passingdocument.cookieTo access or change the Cookie
    • Helps avoid XSS attacks
  • SameSite: Prevents cross-site request forgery attacks (CSRF) by setting cookies so that they are not sent during cross-site requests
    • Strict: Only one party is allowed to request with cookies, that is, the browser will only send cookies requested by the same site, the current web page URL is exactly the same as the request target URL
    • Lax: Allows partial (Get request to navigate to target URL) third-party requests to carry cookies
    • None: Cookies are sent across sites or not
    • The default value is None on earlier versions of Chrome, and Lax on Chrome Stable 80 and later

SameSite = Lax effect

Set-Cookie:'name=value; SameSite=Lax; '
Copy the code

Third-party cookies are not sent in most cases, except for Get requests that navigate to the target url

  • hyperlinks
  • GET the form
  • Preload request
Request type The sample SameSite = Lax whether to send cooie
hyperlinks <a href=”…” ></a>
GET the form <form method=”GET” action=”…” ></form>
preload <link rel=”prerender” href=”…” />
POST form <form method=”POST” action=”…” ></form>
image <img src=”…” />
iframe <iframe src=”…” ></iframe>
ajax fetch(url)

Cookie scope

Together, the Domain and Path identifiers define the scope of the Cookie: that is, which URL requests carry the target Cookie

use

  • Session status management :(such as user login status, account information, etc.)
  • Personalization :(e.g., user-defined Settings, themes, etc.)
  • User behavior analysis: Embedded systems (depth of access, length of stay, etc.)

disadvantages

  • Capacity problem: there is a maximum of 4KB
  • Performance problem: All requests under the same domain name carry cookies. Some requests (such as those sent by tags such as A, IMG, and Link) may not need cookies. As a result, the header of transmission will be increased and some time and space costs will be lost
  • Security problem: The client can obtain it by certain means (script, DevTools, locally stored files, host file modification). XSS,CSRF and other security problems exist

Solutions to security problems

  • Diminishes the duration of the cookie
  • Add an HttpOnly attribute to prevent local scripts from reading cookies
  • The server encrypts the cookie transmitted
  • Add Secure: Use HTTPS for transmission
  • Set the samesite property to the desired value: strict card control cookie carrying scope

LocalStorage and sessionStorage

Data store apis provided by browsers have the same function but different life cycles and scopes

window.sessionStorage.setItem()
window.localStorage.setItem()
window.sessionStorage.getItem()
window.localStorage.getItem()
Copy the code

The life cycle

  • LocalStorage is persistent localStorage that never expires unless manually deleted
  • SessionStorage is temporary local storage and the stored contents are released at the end of the session (closing the page)

scope

Local Storage, Session Storage, and Cookie all follow the same-origin policy

However, Session Storage has a special feature: even if two pages under the same domain name are not opened in the same Tab in the browser, their Session Storage content cannot be shared

advantages

  • Large storage capacity: The storage capacity of a domain name ranges from 4 to 20 MB depending on the browser (space occupied by characters in different encoding codes varies).
    • Some data is usually said to be 5M: actually refers to the length of the stored content string, i.elengthIs equal to the5 * 1024 * 1024(5*1024*1024) (key + value) (5*1024*1024)
    • Utf-8 – English: 1 byte
    • Utf-8 – Chinese: 3 bytes
    • Utf-16 – Chinese/English: 4 bytes
  • Stored on the client, no server communication occurs

The calculation demo of storage capacity can be skipped to view

disadvantages

  • Only strings can be stored. JSON objects need to be converted to JSON strings
  • Only suitable for storing small amounts of simple data
  • LocalStorage needs to be manually deleted

Application scenarios

  • Base64 Image storage: Stores logos
  • Interface data persistence: For content generated depending on the interface (with a long change period), storage can be used to speed up the first screen rendering

IndexedDB

A non-relational database running on a browser

It’s still restricted by the same origin policy

advantages

  • No storage is theoretically online
  • You can store strings, you can store binary data
  • Browsers provide a set of apis that can be easily manipulated

Application scenarios

  • IndexDB is used when the complexity and size of the data increases beyond what LocalStorage can handle
  • Temporary storage of complex data, such as temporary articles in a page
  • Offline saving of some complex form content

Using the tutorial

I will not repeat the use of methods here, there are better information online

Here are two recommended articles for you

  • MDN: Use IndexedDB
  • How to get started with IndexedDB

reference

  • SameSite update log
  • devTools Storage
  • Chrome Platform Status
  • SameSite cookies explained

The original text is first published in personal blog, the special series will sort out many articles, and we learn together, common progress, if there is a mistake, please correct

Browser series

  • 1. Browser Thematic series – Caching Mechanisms
  • 2. Browser Thematic series – Principles of rendering
  • 3. Browser Thematic series – Block rendering
  • 4. Browser Thematic Series – Local Storage
  • 5. Browser Special Series – Web Security
  • 6. Browser Series – Browser kernel
  • 7. Browser Thematic series – Cross domain and cross site
  • 8. Browser Thematic Series – Event loops