[Recommended collection] A summary of the latest cookie interview questions in 2020, continuously updated~

Cookie is a content that front-end engineers deal with every day, so almost all front-end interviews will ask about cookie-related knowledge. This article organizes cookie knowledge related to the front-end into 18 questions, covering all interview situations.

Past and present: Cookie and Session system

We know that HTTP is a stateless protocol. Stateless means that every request sent by the client is considered by the server as a new request, and there is no connection between the previous session and the next session. However, in many scenarios, we need to know the relationship between the next session and the previous session (for example, we need to remember the login status after logging in). At this time, the Cookie and Session system is introduced .

Cookie: When the client requests the server, if the server needs to record the user's status, it will issue a Cookie to the client browser through response headers, and the client browser will save the Cookie. When the browser requests the server again, the browser submits the requested URL together with the cookie to the server. The server obtains the user status by checking the cookie.

Session: When the server receives a request, it will look up the state of the cookie brought by the client from the countless session information stored on the server. If there is no such session information in the server, add a session information.

Usually, the unique Id (sessionId) of the session information stored in the cookie is calculated.

18 problems with cookies

1. Where are the cookies stored?

Cookies are generally stored in the hard disk of the computer in the form of txt by the browser for the browser to read and write.

2. How do cookies work?

  • request

When the browser initiates a request, the browser will automatically check whether there is a corresponding cookie, and if there is a cookie, it will be added to the Cookie field of the Request Headers (the cookie field is a string of name=value separated by semicolons).

[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-0T3A7rcj-1610629444364)(https://upload-images.jianshu.io/upload_images/24944724-e2b3b665b6c39afb.image ?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]

  • response

When the server needs to seed a cookie, add the Set-Cookie field to the Response Headers of the http request. After receiving it, the browser will automatically analyze and identify it and seed the cookie.

3. The difference between cookie and session?

  • The storage location is different: the cookie data is stored on the client's browser, and the session data is stored on the server.
  • Different storage sizes: Generally, the data saved by a single cookie cannot exceed 4k, and a single domain name can save up to 30 cookies (different browsers are different); there is no limit on the size and number of sessions.

4. What is a session level cookie?

The session-level cookie only exists for the current session, and the cookie disappears when the session is terminated.
When the cookie does not set expires, the cookie will only exist during the web page session, and the cookie will disappear when the browser exits.

The content of Expires/Max-Age in the browser is Session.

5. Who can manipulate cookies?

Both the server and js can read/write cookies.

6. Detailed explanation of cookie attributes

  • Name: cookie名

  • Value: cookie值。

  • Domain : The domain name of the cookie. If it is set to .example.com, then both the subdomains a.example.com and b.example.com can use the cookies of .example.com; otherwise, they cannot.

  • Path : URL path that allows cookies to be read, generally set to /.

  • Expires : cookie expiration time. If it is not set, it is the Session period, and the cookie becomes invalid when the page exits.

  • HttpOnly : When set to true, only http can read. js can only read cookies without HttpOnly set.

  • Secure : Cookies marked as Secure, only https requests can be carried.

  • SameSite : Restrict whether third-party URLs can carry cookies. There are 3 values: Strict/Lax (default)/None. (New attributes of chrome51, enforced by chrome80+)

    • Strict : Only allow sending cookies requested by the same site
    • Lax : Allow some third-party requests to carry cookies, that is, get requests that navigate to the target URL. Include hyperlink , Preload and get form to send cookies
    • None : Send cookies arbitrarily, set to None, (Secure needs to be set at the same time, which means that the website must use https)
  • Priority : Priority, chrome's proposal (firefox does not support), defines three priority levels, Low/Medium/High, when the number of cookies exceeds, low priority cookies will be cleared first.

7. What is the difference between js and server-side operations on cookies?

A cookie has an attribute of HttpOnly. When HttpOnly is set, it indicates that the cookie can only be read by http requests, but not by js. The specific manifestation is: the content read by document.cookie does not contain the cookie with HttpOnly set.

8. How does js manipulate cookies

The api for js operation to read/write cookies is document.cookie .

  • Read cookie

document.cookie。

console.log(document.cookie); 
// cna=8fDUF573wEQCAWoLI8izIL6X; xlly_s=1; t=4a2bcb7ef27d32dad6872f9124694e19; 
_tb_token_=e3e11308ee6fe; hng=CN%7Czh-CN%7CCNY%7C156; thw=cn;  v=0; 

The read cookie is a string containing the name and value of all cookies (separated by semicolons), and we need to parse the cookie by ourselves.

  • Write cookie
document.cookie = 'uid=123;expires=Mon Jan 04 2022 17:42:40 GMT;path=/;secure;'
document.cookie = 'uid=123;expires=Mon Jan 04 2022 17:42:40 GMT;path=/caikuai;domain=edu.360.cn;secure;samesite=lax' 

You can only write one cookie at a time, and you need to operate multiple times if you want to write multiple cookies.

1. expires默认为session级别。
2. path默认为当前url的路径。
3. domain默认为当前访问域名。
4. samesite默认为Lax。
5. secure默认为false(即http)。
  • Delete cookie

Just set the expiration time of an existing cookie name to the past time.

document.cookie = 'uid=dkfywqkrhkwehf23;expires=' + new Date(0) + ';path=/;secure;'
  • Modify cookie

Just re-assign the value, the old value will overwrite the new value.

Note: You need to ensure that the two values ​​of path and domain are unchanged, otherwise a new cookie will be added.

Q: What if I want to set multiple cookies?
A: document.cookie can only set one cookie at a time, and document.cookie needs to be operated multiple times.

9. How does the server read and write cookies

Section 2 "How cookies work" tells us that the server can read and write cookies. From the figure, we can see that when a cookie is written, a Set-Cookie writes a cookie. When reading a cookie, all cookie information is put into the cookie field.

Take express as an example:

  • Write cookie
res.setHeader('Set-Cookie', ['uid=123;maxAge: 900000; httpOnly: true']);
// 或者
res.cookie("uid",'123',{maxAge: 900000, httpOnly: true});
  • Read cookie
console.log(req.getHeader('Cookie')); // 拿到所有cookie
// 或者
console.log(req.cookie.name);

10. Limitations on the size and number of cookies

Different browsers have different restrictions on the size and number of cookies. Generally, the number of cookies set under a single domain name should not exceed 30, and the size of each cookie should not exceed 4kb. After exceeding, the cookie will be ignored. Will be set.

Due to limited space, only part of the interview questions can be shared. More front-end interview questions and answers can be read and downloaded by [click me] ~ Share it with everyone for free, it is a thankful feedback.

11. Check whether the cookie function is turned on in the browser

window.navigator.cookieEnabled // true

12. What is the cookie sharing strategy

The domain and path together determine which URLs the cookie can be accessed by.

When accessing a url, if the host of the url is the same as the domain or a subdomain of the domain, and the path of the url matches the path part, then the cookie can be read.

If the cookie is as shown in the figure above, the corresponding relationship between a URL and a readable cookie is:

url uid1 uid2 uid3
edu.360.cn/caikuai/
edu.360.cn/ ×
360.cn/article/123… × ×

13. Cookies in cross-domain requests (CORS)

First, SameSite of cookie needs to be set to None. Secondly, for the interface with Access-Control-Allow-Credentials set to true (indicating that cookies are allowed to be sent), we need to set the withCredentials attribute to true when sending an ajax request.

14. Encoding of cookies

document.cookie = 'uid=123;expires=Mon Jan 04 2022 17:42:40 GMT;path=/caikuai;domain=edu.360.cn;secure;samesite=lax' 

From the assignment of document.cookie, we can see that there are special characters such as equal signs, colons, semicolons, spaces, commas, and slashes . Therefore, when these types of symbols exist in the key and value of the cookie, they need to be Encoding, generally use encodeURIComponent/decodeURIComponent for operation.

Q: Why not use escape and encodeURI for encoding?
A: Compared with these two APIs, encodeURIComponent can encode more characters, such as "/".

15. Cookies and web security

1. How cookies deal with XSS vulnerabilities*

The principle of the XSS vulnerability is that the form data or url parameters submitted by the user are displayed on the page without processing, resulting in the content submitted by the user being parsed and executed as html on the page.

Conventional scheme : processing special characters, such as "<" and ">", etc. to escape.

Cookie response plan : For users to use script to collect cookie information, we can set important cookie information to HttpOnly to prevent cookies from being collected by js.

2. How cookies respond to CSRF attacks

CSRF, the Chinese name is cross-site request forgery. The principle is that a user logs in to website A, and then visits website B for some reasons (such as redirects, etc.). Website B directly sends a request for website A to perform some dangerous operations. A website is in the login state, and a CSRF attack occurs (the core is to use cookie information to be carried across sites)!

Conventional scheme : use verification code or token, etc.

Cookie response plan : Since the core of CSRF attack is to use cookie information to be carried across sites, then we can set the SameSite of the core cookie to Strict or Lax to avoid it.

16. Do different browsers share cookies?

Different browsers do not communicate with each other and are independent cookies. Therefore, when we log in to a certain website on one browser, we need to log in again when we switch to another browser.

17. The difference between cookie and localStorage/sessionStorage

characteristic Cookie localStorage sessionStorage
operator Server and js js js
Data lifetime Set expiration time Save forever unless cleared Only valid in the current session, cleared after closing the page or browser
Storage data size Around 4K Generally 5M Generally 5M
Communicate with the server Every time it will be carried in the HTTP header every time it will be carried in the HTTP header Not communicating with server Not communicating with server
Ease of use The native Cookie interface is not friendly and needs to be encapsulated Easy to use interface Easy to use interface

18. What information is suitable to be placed in a cookie

The increase of cookies will undoubtedly increase the overhead of network requests, and each request will bring the cookie intact, so for those "information that must be carried in each request (such as identity information, A/B bucket information, etc.)" , It is suitable to be placed in cookies, and other types of data are recommended to be placed in localStorage.

In addition to the cookie interview questions, I also made a series of front-end interview questions. Friends in need can click on the blue letters below to read:

Guess you like

Origin blog.csdn.net/hugo233/article/details/112637828