In the field of front-end knowledge, cookies are very basic things, but really have a comprehensive understanding of cookies I’m afraid not many. Now let’s lay down the basics and understand it more fully.

The birth of the cookie

We know that HTTP is stateless, which means that for the same request, as long as the request parameters are the same, HTTP cannot know which client sent the request, nor can it determine whether it is a login user request, which results in HTTP cannot remember the login status of the user. Therefore, the original intention of cookie design is to make up for the statelessness of HTTP, help record the user status of the client, and serve as the carrier of user login credentials.

The server sets cookies for login users to save the current user status. Every time a request is made, the browser automatically carries cookies under the domain name to tell the server the user ID of the current request, which matches the user sessionID of the server, so as to determine the current user and login status.

Operations related to cookies

Set the cookie

Set by JS

// Only one pair of keys can be set at a time, but unlike traditional JS, it is not overridden
document.cookie = 'name=xxx; ';
Copy the code

Server Settings (Node)

res.setHeader('Set-Cookie'.'name=xxx; ');
Copy the code

Modify the cookie

Just change the cookie and overwrite it

document.cookie = 'name=xxx; ';
Copy the code

Delete the cookie

Set the expiration time to the past time

document.cookie = 'name=xxx; expires=' + new Date('1999');
Copy the code

Cookie-related attributes

expires

The value is a time string used to set the expiration time. Cookies can be deleted only after the past time is set

document.cookie = 'name=xxx; expires=' + new Date('1999');
Copy the code

domain

Domain specifies which web sites can accept cookies. Default is Origin (domain must be the domain name or primary domain of the current request).

document.cookie = 'name=xxx; domain=a.xxx.com';
Copy the code

path

The path identifier specifies which paths under the host can accept cookies. The default is /, where path must exist in the current request (web page) path

document.cookie = 'name=xxx; path=/xxx; ';
Copy the code

Secure

Cookie restrictions marked Secure can only be set and transmitted in HTTPS.

// This parameter does not take effect if set in HTTP web pages
document.cookie = 'name=xxx; Secure';
Copy the code

HttpOnly

Setting cookies to be carried only by requests, not JS, can reduce XSS attacks. This property can only be set in the service.

res.setHeader('Set-Cookie'.'name=xxx; HttpOnly; ');
Copy the code

SameSite

SameSite can be set to the following values

  • None (default rule for older Chrome versions (below 80))

Browsers continue to send cookies under same-site and cross-site requests, case insensitive

  • Strict

The browser will only send cookies when visiting the same site.

  • Lax (default rule in the new Chrome version)

The rules are slightly relaxed, and third-party cookies are also not sent in most cases, except for GET requests that navigate to the target url.

A GET request to navigate to a target url consists of only three cases: links, preloaded requests, and GET forms. See the table below.

Request type The sample normal Lax
link <a href="..." ></a> Send a Cookie Send a Cookie
preload <link rel="prerender" href="..." /> Send Cookie send Cookie
GET the form <form method="GET" action="..." > Send Cookie send Cookie
POST form <form method="POST" action="..." > Send a Cookie Don’t send
iframe <iframe src="..." ></iframe> Send a Cookie Don’t send
AJAX $.get("..." ) Send a Cookie Don’t send
Image <img src="..." > Send a Cookie Don’t send

Setting Lax and Strict prevents many CSRF attacks

Cookie related knowledge concepts

Request autocarry

In browsers (older versions), requests (including GET and POST) automatically carry cookies of the request address (the domain name of the server, not the domain name of the web page that initiates the request). Cross-domain Ajax requires the withCredentials configuration. On newer browsers (Chrome 80 +), because the default value of SameSite is Lax, cross-domain cookie requests are limited and can no longer carry cross-domain cookies configured for Lax.

The life cycle

The default cookie life cycle is session. That is, the cookie is deleted after the browser is closed. If expires is set, it is controlled, and if the browser closes before it expires, it is stored on the hard drive.

The difference between cookies and sessions

Session is a mechanism on the server side that uses a hash like data structure to hold information for the user, such as login status.

Cookie can be used by the server to save the login status. For example, set a cookie for the client to save the sessionID corresponding to the session. The client will automatically carry the cookie in the next request, and the server will retrieve the sessionID from the cookie. Obtain user login status and user information from the session table.

Relationship between cookie and token

Tokens are another popular way to handle HTTP statelessness, typically set in the request header. When the user successfully logs in, the user returns the token to the client. When the client requests the token again, the server obtains the token and obtains the user information and login status from the session.

Compared with cookies, token can effectively avoid CSRF attacks because it is set in code and does not carry cookies when visiting third-party websites.

Cookie shortcomings

  • Cookie size is generally limited to 4KB by the browser

  • Requests to automatically carry cookies are actually an invalid waste of bandwidth

  • Security Issues (CSRF and XSS)

conclusion

Cookie used to be a popular mechanism used by various websites, but with the application of token mechanism and the rise of HTML5 storage, in fact, many websites no longer use cookies. However, cookies still have a lot of unique application scenarios, as a front-end is still necessary to learn and understand. If there are any mistakes in this article, please correct them.

reference

  • HTTP cookies

  • Predict the SameSite property of cookies in a recent interview

  • The SameSite property of the Cookie


Welcome to front end learning punch card group learning ~ 516913974