What is Cookie

HTTP is stateless,which means all request origins to a server are exactly the same and a server cannot determine if a request comes from a client that already did a request before, or it’s new one.
Cookie are sent by the browser to the server when an HTTP request starts, and they are sent back from the server,which can edit their content.
Cookies are essentially used to store a session id.

Restrictions of cookies

  • Cookies can only store 4KB of data
  • Cookies are private to the domain. A site can only read the cookies it set, not other domains cookies
  • You can have up to 20 limits of cookies per domain (but the exact number depends on the specific browser implementation)
  • Cookies are limited in their total number (but the exact number depends on the specific browser implementation). If this number is exceeded, new cookies replace the older ones.

    Properties of Cookie

  • Name

  • Value
  • Domain:The domain can be used to specify a subdomain for your cookie.

    A site with top domain can only set this top domain as cookie domain, and can not set it’s subdomain as cookie domain. A site with subdomain can set the top domain, or itself as cookie domain, and can not set other subdomain. This means a site called “baidu.com” can only set “.baidu.com“ as cookie domain, “.teiba.baidu.com“ is not permitted; A site called “tieba.baidu.com” can set “.baidu.com“, “.tieba.baidu.com“, “music.baidu.com“ is not permitted. If you want to use this cooke for all site from the same top domain, you should set “.topdomain.com” as cookie domain.

  • Path: The path parameter specifies a document location for the cookie, so it’s assigned to a specific path, and sent to the server only if the path matches the current document location, or a parent

    this cookie is sent on /dashboard, /dashboard/today and other sub-urls of /dashboard/, but not on /posts for example. If you don’t set a path, it defaults to the current document location. This means that to apply a global cookie from an inner page, you need to specify path="/".

  • Expires: Determine how long can this cookie survive

    If you don’t set anything, or a negative number, the cookie will expire when the browser is closed; If you set 0, which means this cookie will be expired right now(because there’s no method to destory a cookie); If you set a positive number, the cookie will expire when the time is over, nomatter the browser is closed or not;

  • Size

  • HttpOnly: One useful parameter is HttpOnly, which makes cookies inaccessible via the document.cookie API, so they are only editable by the server:
  • Secure: Adding the Secure parameter makes sure the cookie can only be transmitted securely over HTTPS, and it will not be sent over unencrypted HTTP connections:
  • SameSite