Cookies are something a front-end engineer deals with every day, so almost all front-end interviews ask about cookies. This article has organized front-end cookie knowledge into 18 questions covering all interview situations.
Past lives: Cookie and Session systems
As we know, HTTP is a stateless protocol, stateless means that the server considers each request sent by the client as a new request, and there is no connection between the last session and the next session. However, in many cases, we need to know the relationship between the next Session and the last Session (for example, we need to remember the login status after logging in), so cookies and Session systems are introduced.
Cookie: When the client requests the server, if the server needs to record the user state, it issues a Cookie to the client browser through Response Headers, and the client browser saves the Cookie. When the browser requests the server again, the browser submits the requested URL along with the Cookie to the server. The server checks the Cookie to get the user’s state.
Session: When the server receives the request, it looks up the state of the cookie brought by the client with the request from the numerous Session information stored on the server. If the session information does not exist on the server, add a session information.
Generally, cookies store the unique Id (sessionId) of session information after calculation.
Cookie’s 18 questions
1. Where are cookies stored?
Cookies are generally stored in the computer hard disk by the browser in the form of TXT for the browser to read and write operations.
2. How do cookies work?
- request
When the browser initiates a Request, the browser automatically checks for a cookie and adds the cookie to the Cookie field of the Request Headers (the cookie field is a string of semicolon-delimited name=value strings).
- response
When the server needs a cookie, it adds the set-cookie field to the Response Headers of the HTTP request. After receiving the cookie, the browser automatically parses and recognizes it and seeds the cookie.
3. What is the difference between cookie and session?
- Different storage locations: Cookie data is stored in the client’s browser, while session data is stored on the server.
- Different storage sizes: Generally, a single cookie cannot store more than 4K of data, and a single domain can store a maximum of 30 cookies (different browsers vary). Sessions are unlimited in size and number.
4. What are session-level cookies?
Session-level cookies exist only for the current session and disappear when the session terminates. When a cookie is not set Expires, the cookie will only exist for the duration of the web session and will disappear when the browser exits.
A browser that represents Expires/ max-age is Session.
5. Who can manipulate cookies?
Cookies can be read/written by both the server and JS.
6. Detailed explanation of cookie attributes
-
Name: cookies
-
Value: the cookie Value.
-
Domain: indicates the Domain name of the cookie. If the cookie is set to. Example.com, the cookies of. Example.com can be used for both subdomain names a.example.com and b.example.com. The opposite is not possible.
-
Path: indicates the URL Path that cookie reading is allowed. The value is usually set to /.
-
Expires: indicates the cookie expiration time. If this parameter is not specified, the Session is the Session period, and the cookie is invalid when the page exits.
-
HttpOnly: When set to true, only HTTP can be read. Js can only read cookies that are not HttpOnly set.
-
Secure: Indicates the cookie marked Secure. Only HTTPS requests can be carried.
-
SameSite: Restricts whether third-party urls can carry cookies. There are three values: Strict/Lax(default)/None. (Chrome51 new properties, chrome80+ mandatory)
- Strict: Only cookies requested by the same site are allowed to be sent
- Lax: Allow some third-party requests to carry cookies, that is, get requests that navigate to the target url. Including hyperlink, preload and get form three forms to send cookies
- None: Send any cookies, set to None (Secure is required, that is, the site must use HTTPS)
-
Priority: Priority. Chrome’s proposal (not supported by Firefox) defines three priorities: Low, Medium, and High. When the number of cookies exceeds, the cookies with the lower Priority are cleared first.
7. What is the difference between cookie operation on JS and server side?
Cookie has an attribute of HttpOnly. When HttpOnly is set, it indicates that the cookie can only be read by HTTP request, not JS. The specific performance is: Document.
8. How does JS operate cookies
The js API for reading/writing cookies is document.cookie.
- Read the cookie
Document. The 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;
Copy the code
The cookie after reading is a string, containing the names and values of all cookies (separated by semicolons), which need to be resolved by ourselves.
- Write a 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'Copy the code
You can only write one cookie at a time. You need to write multiple cookies multiple times.
1. Expires Defaults to the session level. 2. Path Is the path of the current URL by default. 3. Domain Is the current domain name by default. 4. Samesite defaults to Lax. 5. Secure defaults to false (that is, HTTP).Copy the code
- Delete the cookie
You only need to set an existing cookie name expiration time to the past time.
document.cookie = 'uid=dkfywqkrhkwehf23; expires=' + new Date(0) + '; path=/; secure; 'Copy the code
- Modify the cookie
Just reassign, the old value overwrites the new value.
Note: You need to keep the path and domain values unchanged, otherwise a new cookie will be added.
Q: What if you want to set multiple cookies? A: Document. cookie Only one cookie can be set at A time.
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 a set-cookie writes a cookie when writing cookies. When a cookie is read, all cookie information is put into the cookie field.
Take express as an example:
- Write a cookie
res.setHeader('Set-Cookie', ['uid=123;maxAge: 900000; httpOnly: true']); // res.cookie("uid",'123',{maxAge: 900000, httpOnly: true});Copy the code
- Read the cookie
console.log(req.getHeader('Cookie')); // Get all the cookies // or console.log(req.cookie.name);Copy the code
10. Limits on Cookie size and number
Different browsers have different limits on the size and number of cookies. Generally, a maximum of 30 cookies can be set for a single domain name, and the size of each Cookie cannot exceed 4kb. If the size exceeds the threshold, cookies are ignored and will not be set.
11. Check whether the Cookie function is enabled on the browser
window.navigator.cookieEnabled // true
Copy the code
12. What is the cookie sharing policy
Domain and path together determine which urls cookies can be accessed.
Cookies can be read only when the host of a URL is the same as the domain or the subdomain of the domain, and the path of the URL partially matches the path of the domain.
If cookies look like the figure above, then the relationship between a URL and readable cookies is:
url | uid1 | uid2 | uid3 |
---|---|---|---|
edu.360.cn/caikuai/ | Square root | Square root | Square root |
edu.360.cn/ | Square root | Square root | x |
360. Cn/article / 123… | Square root | x | x |
Cookies in cross-domain requests (CORS)
First, the SameSite for cookies needs to be set to None. Secondly, for interfaces with access-Control-allow-credentials set to true (indicating that cookies are allowed), we need to set the withCredentials attribute to true when sending Ajax requests.
14. Cookie encoding
document.cookie = 'uid=123; expires=Mon Jan 04 2022 17:42:40 GMT; path=/caikuai; domain=edu.360.cn; secure; samesite=lax'Copy the code
As can be seen from the assignment of document.cookie, there are equal signs, colons, semicolons, Spaces, commas, slashes and other special characters. Therefore, when these symbols exist in the key and value of cookie, it is necessary to encode them. Tend to use encodeURIComponent/decodeURIComponent.
Q: Why not use Escape and encodeURI for encoding? A: Because encodeURIComponent can encode more characters, such as “/”, than these two apis.
Cookie and Web security
1. How does cookie deal with XSS vulnerability *
The principle of XSS vulnerability is that the data submitted by users, such as form data or URL parameters, are displayed on the page without processing, resulting in the content submitted by users being executed as HTML parsing on the page.
General scheme: special characters such as “<” and “>” are escaped.
Cookie solution: For users to use script to collect cookie information, we can set important cookie information to HttpOnly to avoid cookies being collected by JS.
2. How does cookie respond to CSRF attacks
CSRF is called cross-site request forgery in Chinese. The principle is that A user logs in to website A and then visits website B for some reasons (such as redirection, etc.), and website B directly sends A request from website A to perform some dangerous operations. As website A is logged in, CSRF attack (the core is the use of cookie information can be carried across sites)!
Common solution: use verification code or token.
Cookie solution: Since the core of CSRF attack is to make use of cookie information that can be carried across sites, we can set the SameSite of the core cookie to Strict or Lax to avoid this.
16. Do different browsers share cookies?
Different browsers do not communicate with each other; they are independent cookies. As a result, we log in to a site on one browser and have to log in again when we switch to another browser.
17. Cookies and localStorage/sessionStorage differences
features | Cookie | localStorage | sessionStorage |
---|---|---|---|
The operator | Server and JS | js | js |
The lifetime of the data | You can set the expiration time | It is stored permanently unless it is removed | This parameter is valid only in the current session and is cleared after you close the page or browser |
Data storage size | About 4 k | Generally for 5 m | Generally for 5 m |
Communicates with the server | It’s going to be carried in the HTTP header every time | Does not communicate with the server | Does not communicate with the server |
Ease of use | The native Cookie interface is unfriendly and requires encapsulation | Interface is easy to use | Interface is easy to use |
18. What information is appropriate to put in cookies
The increase of cookies will undoubtedly increase the overhead of network requests, and each request will be complete with cookies, so for those “each request must carry information (such as identity information, A/B bucket information, etc.)”, it is suitable to put in cookies, other types of data is recommended to put in localStorage.