Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Introduction and use of cookies


May 30, 2021 Article blog


Table of contents


First, an overview

A cookie is a small piece of text information that the server holds in a browser and cannot be larger than 4KB in general. This information is automatically attached to the browser every time it makes a request to the server.

Cookies primarily hold status information, and here are some of the main uses.

  • Conversation management: Save information that needs to be recorded, such as logins, shopping carts, and so on.
  • Personalized information: Save user preferences, such as the font size of the page, background color, and so on.
  • Track users: Record and analyze user behavior.

Cookies are not an ideal client storage mechanism. I t has a small capacity (4KB), lacks a data manipulation interface, and can affect performance. C lient storage should use the Web storage API and IndexedDB. Only information that needs to be made known to the server for each request should be placed in a cookie.

For an introduction to Web storage, read this blog: Use of sessionStorage and localStorage

Each cookie has metadata in the following areas.

  • The name of the cookie
  • The value of the cookie (the real data is written here)
  • Expiration time (beyond this time will expire)
  • Domain name (current domain name by default)
  • Path in effect (default to current URL)

For example, when a user visits a URL www.example.com the server writes a cookie in the browser. The domain name to which this cookie belongs is www.example.com and the effective path is the root path / .

If the active path of a cookie is set to /user the cookie is only valid if access www.example.com/use r and its subpaths. Later, before the browser accesses a path, it finds cookies that are valid for the domain name and path and have not expired and are sent to the server together.

Users can set that the browser does not accept cookies, or they can set that cookies are not sent to the server. The window.navigator.cookieEnabled property returns a Boolean value indicating whether the browser has cookies turned on.

window.navigator.cookieEnabled // true

document.cookie property returns the cookie for the current page.

The limits on the number and size of cookies vary from browser to browser. I n general, a single domain name should not set more than 30 cookies, each cookie size can not exceed 4KB. When the limit is exceeded, cookies are ignored and not set.

Two URLs can share cookies as long as they have the same domain name. N ote that the protocol is not required to be the same here. That is, cookies set http://example.com can be read by https://example.com

2. Cookies and HTTP protocols

Cookies are generated by the HTTP protocol and are primarily intended for use by the HTTP protocol.

1, HTTP response: the generation of cookies

If the server wants to save cookies in a browser, place a Set-Cookie field in the header information of the HTTP response.

Set-Cookie:foo=bar

The above code saves a cookie named foo in the browser with a value of bar.

AN HTTP RESPONSE CAN CONTAIN MULTIPLE Set-Cookie FIELDS, I.E. GENERATE MULTIPLE COOKIES IN THE BROWSER.

HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: yummy_cookie=choco
Set-Cookie: tasty_cookie=strawberry

In addition to the value of the cookie, the Set-cookie field can attach the properties of the cookie. Inside a Set-cookie field, multiple properties can be included at the same time, with no order requirements.

Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>
Set-Cookie: <cookie-name>=<cookie-value>; Max-Age=<non-zero-digit>
Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>
Set-Cookie: <cookie-name>=<cookie-value>; Path=<path-value>
Set-Cookie: <cookie-name>=<cookie-value>; Secure
Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly

 Introduction and use of cookies1

2, HTTP request: the sending of cookies

When the browser sends an HTTP request to the server, each request is brought with a cookie. T hat is, save this information from the browser earlier and send it back to the server. The Cookie field for HTTP header information is used at this time.

// 会向服务器发送名为 foo的 Cookie,值为 bar。
Cookie: foo=bar

// Cookie字段可以包含多个 Cookie,使用分号(;)分隔。
Cookie: name=value; name2=value2; name3=value3

Here's an example.

GET /sample_page.html HTTP/1.1
Host: www.example.org
Cookie: yummy_cookie=choco; tasty_cookie=strawberry

 Introduction and use of cookies2

The properties of cookies

1、Expires,Max-Age

Expires property specifies a specific expiration time, after which the browser no longer retains the cookie. Its value is in UTC format, which can be Date.prototype.toUTCString()

If the property is not set, or if it is set to null, the cookie is valid only in the current session, and once the browser window is closed and the current session ends, the cookie is deleted. In addition, the browser determines whether a cookie has expired based on local time, and since the local time is inaccurate, there is no guarantee that the cookie will expire at the time specified by the server.

Max-Age property specifies the number of seconds that cookies exist from now on, such as 60 x 60 x 24 x 365 (i.e. one year). After this time, the browser will no longer retain this cookie.

If both Expires and Max-Age are specified, the values of Max-Age take precedence.

If Set-Cookie field does not specify Expires or Max-Age attribute, the cookie is the Session cookie, i.e. it exists only in this conversation and will no longer be retained by the browser once the user closes the browser.

Use Node to create a server to simulate the demo:

const http = require('http')
const fs = require('fs')

http.createServer(function (request, response) {
  console.log('request come', request.url)
  
  const html = fs.readFileSync('test.html', 'utf8')
  response.writeHead(200, {
    'Content-Type': 'text/html',
    'Set-Cookie': ['id=123;max-age=2', 'abc=456;HttpOnly']
  })
  response.end(html)

}).listen(8888)

console.log('http://127.0.0.1:8888')

 Introduction and use of cookies3

 Introduction and use of cookies4

2、Domain,Path

Domain property specifies which domain names to include this cookie when a browser makes an HTTP request.

  • If the property is not specified, the browser sets it to the current domain name by default, and the child domain name will not come with the cookie. For example, example.com does not set the domain property of a cookie, the sub.example.com will not be included with the cookie.
  • If a domain property is specified, the subdomain will also come with the cookie. If the domain name specified by the server does not belong to the current domain name, the browser rejects the cookie.
  • Bottom line: The Domain identity specifies which hosts can accept cookies. I f not specified, the default is the current host (which does not contain child domain names). If Domain is specified, the child domain name is generally included.

Path property specifies which paths to include this cookie when a browser makes an HTTP request. A s soon as the browser discovers that the Path property is the first part of the HTTP request path, the cookie is included in the header information. F or example, if the PATH property is / , the request /docs path will also contain the cookie. Of course, the premise is that the domain names must be consistent.

3、Secure,HttpOnly

Secure property specifies that the browser can send the cookie to the server only under the encryption protocol HTTPS. O n the other hand, if the current protocol is HTTP, the browser automatically ignores the Secure property from the server. T he property is just a switch and does not need to specify a value. If the communication is httpS protocol, the switch opens automatically.

HttpOnly property specifies that the cookie is not available through JavaScript scripts, primarily document.cookie property, XMLHttpRequest object, and the Request API T his prevents the cookie from being read by the script and will only be brought with it if the browser makes an HTTP request. For security reasons.

Document.cookies

document.cookie property is used to read and write cookies on the current page. When read, it returns all cookies on the current page, provided that the cookie does not have HTTPOnly properties.

document.cookie // "foo=bar;baz=bar"

The above code reads out two cookies at once from document.cookie which are separated by semicolons. Y ou must restore manually to remove the value of each cookie. This is where cookie access data is inconvenient, it does not have perfect access to the data api let us use, we must manually extract their own data.

document.cookie property is writeable and can be used to add cookies to the current website. A t the time of writing, the value of the cookie must be written in the form of key=value N ote that there can be no spaces on either side of the equal sign. document.cookie can only be written one cookie at a time, and writes are not overwritten, but added.

document.cookie = 'fontSize=14';

// 最终只会有 test1=456 被写进去
document.cookie = 'test1=456;hahah=123'

Differences in the reading and writing behavior of document.cookie (all cookies can be read at once, but only one cookie can be written) are related to the cookie communication format of the HTTP protocol.

  • When a browser sends cookies to the server, the cookie field sends all cookies using one line;
  • When the server sets a cookie to a browser, the Set-Cookie field is a line setting a cookie.

The only way to delete an existing cookie is to set its expires property to a past date.

document.cookie = 'fontSize=;expires=Thu, 01-Jan-1970 00:00:01 GMT';

V. Reference materials

HTTP cookies are detailed