Moment For Technology

The cookie and session

Posted on Aug. 12, 2023, 5:43 p.m. by Brent Carroll
Category: The back-end Tag: The back-end


1.1 What is a Cookie

A cookie is a small text file that is stored on your hard drive by a Web server when you browse a website. It records your user name, password, web pages you visit, how long you stay and so on. When you visit the site again, the Web server will first look to see if it has any cookies from the last time. If so, it reads the cookie, identifies the user, and sends out the appropriate web content, such as a welcome slogan on the page, or allowing you to log in without entering an ID or password, etc.

When a client sends an HTTP request, the browser checks to see if there is a cookie. If so, the cookie field is automatically added to the request header. Note that every HTTP request, if there is a cookie, the browser automatically sends the cookie to the server. So what data to put in the cookie is very important, because a lot of data does not need to be sent to the server every request, after all, will increase the network overhead, waste bandwidth. So setting "information to be carried on every request (typically authentication information)" is particularly good for cookies, and other types of data are not.

To put it simply:

  • Cookies are small text files (plain text) that exist entirely on the client side. Cookies save login credentials, with it, you only need to send the cookie on the next request, do not have to re-enter the user name, password and so on to re-login.

  • Is designed to transfer information between the server and the client;

Here I draw a simple picture to make it easy to understand:

On the first request:

First request

At the next request:

Next request

The browser submits the cookie to the server along with the request header. The cookie carries the session ID information. The server identifies users based on cookies: Since cookies contain session ID information, the corresponding session can be found through cookies and the state of users can be determined by judging the session.

1.2 Cookie attributes

In the browser console, you can view cookies by typing: document.cookie. A cookie is a string of key-value pairs with "; "between each pair. That is, separated by a semicolon and a space.


Note that this method can only get cookies of non-Httponly type

Each cookie has certain attributes, such as when it expires, which domain to send to, which path, and so on. These properties are set using cookie options: Expires, Domain, path, Secure, and HttpOnly. These properties can be set or not set when setting any cookie, and the default values for these properties are used. When these properties are set, they are separated by a semicolon and a space. The following is a code example:

"key=name; expires=Sat, 08 Sep 2018 02:26:00 GMT;; path=/; secure; HttpOnly"
Copy the code

Cookie properties can be viewed in the console: Application option, select Storage on the left, and the last one is cookie. Click to view.

- Expires、Max Age:

The Expires option sets when a cookie is valid. Expires is actually the expiration Date of a cookie. Expires must be a time in GMT format (which can be obtained by new Date().togmtString () or new Date().toutcString ()).

New Date().togmtString () or new Date().toutcString ()Copy the code

For example, Expires =Sat, 08 Sep 2018 02:26:00 GMT indicates that the cookie will expire after 2:26 on September 8, 2018. The browser clears for invalid cookies. If this option is not set, such a cookie is called a session cookie. It lives in memory, and when the session ends, the browser closes, the cookie disappears.


Expires is an option in HTTP /1.0. In HTTP /1.1, Expires has been replaced by the Max age option, both of which limit how long cookies can be valid. The Expires value is a point in time (cookie expiration = Expires), while the Max age value is a time period in seconds (cookie expiration = creation time + Max age). In addition, the default value of Max age is -1(that is, the validity period is session); There are three possible values for Max age: negative, 0, and positive. Negative: Valid session; 0: delete cookies. Positive: Valid at creation time + Max age

- Domain and Path

A Domain is a Domain name, and a Path is a Path. Together, the Domain and Path form a URL. Together, the Domain and Path restrict which urls a cookie can be accessed by. That is, the requested URL is Domain or subdomain, and the Path of the URL is Path or subpath, then the cookie can be accessed. For example:

The Domain of a cookie is "" and the Path is "/". If the requested URL can be js/ HTML /img/ CSS resource request, The domain name is "" or its subdomain is "" or "", and the URL path is "/" or its subpath is "/home" or "/home/login". The cookie is accessible to all.


When a cross-domain XHR request occurs, the cookie is not automatically added to the request header by default, even if the requested URL's Domain name and Path meet the cookie's Domain and Path.

- Size

The size of the Cookie

- Secure

The Secure option is used to set cookies to be sent only in Secure requests. Cookies containing the Secure option can only be sent to the server when the request is HTTPS or other security protocol.

By default, cookies do not carry the Secure option (that is, empty). So by default, a cookie is sent to the server for either HTTPS or HTTP requests. Note, however, that the Secure option only allows you to transfer to the server under Secure conditions, but that does not mean you cannot see the cookie.


If you want to use JS to set Secure cookies on a web page, you must ensure that the web page is HTTPS. Secure cookies cannot be set on HTTP web pages.

- httpOnly

This option is used to set whether the cookie can be accessed through js. By default, cookies do not have the httpOnly option, so by default, the client can access the cookie (including reading, modifying, deleting, etc.) through JS code. When the cookie has the httpOnly option, the client cannot access (including reading, modifying, deleting, etc.) the cookie through JS code.

It is not possible to set an httpOnly type cookie on the client via JS code. This type of cookie can only be set on the server.

You can see in the browser's console which cookies are of type httpOnly, as shown in the figure below:


Document. cookies cannot be obtained from the console and cannot be modified as long as they are of type HttpOnly.

The reason why clients are restricted to access cookies is mainly for security purposes. Because if any cookie can be obtained by the client through document.cookie, then if the webpage of a legitimate user is attacked by XSS, and there is a malicious script inserted into the webpage, this script, The document. Cookie reads the cookie related to user authentication, so you can simply forward the cookie as is.

1.3 Cookie setting, reading and deleting methods

Cookies can be set either by the server or by the client.

1.3.1 Setting cookies on the Server

As described in 1.1 above, when a client makes a request to the server for the first time, there is a set-cookie field in the corresponding request header to identify the user.

The following picture is a screenshot of the response header of a page logged in Tencent Cloud. You can see that there are two set-cookie fields in the response header, and each one corresponds to a cookie. Note that each cookie is placed in a set-cookie field, and multiple cookies cannot be placed in a set-cookie field. For each cookie, set the following attributes: Expires, path, and httpOnly. The specific meaning of these attributes can be seen in combination with the cookie attributes in 1.2:

response headers

The server sets the range of cookies:

The server can set all cookie options: Expires, Domain, path, Secure, HttpOnly

1.3.2 Setting cookies on the Client

Cookie unlike Web Storage setItem, getItem, removeItem, clear and other methods, need their own encapsulation. Simply type in the browser's console:

document.cookie="name=lynnshen; age=18"
Copy the code

"Name =lynnshen"; "name=lynnshen"; "name=lynnshen";

The easiest way to set multiple cookies is to repeat document.cookie = "key=name" :

document.cookie = "name=lynnshen";
document.cookie = "age=18";
Copy the code

Look at the console again:


If the name, domain, and path fields are the same, the cookie is overwritten.

Here is my own simple encapsulation of setting, reading, and deleting cookies:

Setting cookies:

function setCookie(name,value,iDay){ var oDate = new Date(); oDate.setDate(oDate.getDate() + iDay); document.cookie = name + "=" + value + "; expires=" + oDate; }Copy the code

This method simply assumes that there is only one "=" in the cookie, that is, key=value. If there is more demand, it can be improved on this basis:

Function getCookie(name){// For example, cookie is "username= ABC; password=123" var arr = document.cookie.split('; '); / / to use ";" Cookie for(var I = 0; i  arr.length ; i++){ var arr2 = arr[i].split("="); if(arr2[0] == name){ return arr2[1]; } } return ""; // Return null if no one is found;}Copy the code

Delete the cookies:

Function removeCookie(name){setCookie(name, "1", -1)}Copy the code

1.4 Disadvantages of cookies

Disadvantages of cookies:

(1) The number of cookies under each particular domain name is limited:

  • IE6 or IE6-(versions below IE6) : A maximum of 20 cookies

  • IE7 or IE7+(IE7 or later) : up to 50 cookies

  • FF: Up to 50 cookies

  • Opera: Maximum 30 cookies

  • Chrome and Safari have no hard and fast limits

  • When the limit of a single domain name is exceeded and the cookie is set again, the browser will clear the previously set cookie. IE and Opera will clean the least recently used cookies, FF will clean the cookies randomly;

(2) The storage is too small, only 4KB;

(3) Each HTTP request will be sent to the server, affecting the efficiency of resource acquisition;

(4) Need to own encapsulation to obtain, set, delete cookie method;

1.5 Differences between Cookies and Sessions

A cookie is stored on the client's browser, and a session is stored on the server. Session objects are used to store attributes and configuration information required by a specific user session. When a user requests a Web page from an application, the server automatically creates a session object if the user does not already have a session. When a session expires or is abandoned, the server terminates the session. Cookies and sessions need to work together, as described in Section 1.1.

When the cookie expires and the session expires, you need to log in again.

2. Browser local storage:

2.1 localStorage and sessionStorage

In higher versions of browsers, JS provides two types of storage: sessionStorage and globalStorage. In H5, localStorage replaces globalStorage.

SessionStorage is used to store the data of a session locally. The data can be accessed only from the pages in the same session and is destroyed when the session ends. So sessionStorage is only session level storage, not a persistent local storage.

LocalStorage is persistent localStorage. Data will never expire unless it is deleted by js or the browser cache is cleared.

Browsers supported: Internet Explorer 7 and later versions do not support Web storage. Other browsers support web storage. However, in IE5, IE6, IE7 there is a userData, which is also used for local storage. This persistent data is stored in the cache and will remain there until the cache is cleared.

2.2 Differences between Web Storage and Cookies

(1) The role of Web Storages and cookies is different, Web storage is used for local mass storage data (the storage capacity of web storage is large to 5MB); And cookie is used for information transfer between client and server;

(2) Web storage has setItem, getItem, removeItem, clear and other methods, cookie needs our own to encapsulate setCookie, getCookie, removeCookie, see section 1.3;

3. Summary

In this article, the longitudinal depth of the cookie related knowledge, including the role of the cookie, the use of each attribute, cookie Settings, shortcomings and so on. Horizontally, the cookie is compared with the session and localStorage. If you have any questions, please make corrections.

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.