In the current digital age, you have probably used e-commerce websites and email clients like Gmail, Outlook, and so on on any browser. Remember how after adding one item to your cart, you add another without being asked to enter your email address or password for that account? Then, maybe you leave the website and return to add another item to your shopping cart. Yet again, you are not required to log in again this time. Sound like magic to you?
So, the credentials don't need to be entered every time. Have you ever questioned why this happens? How does the e-commerce website know you are the same person trying to log in without having to enter your credentials again? Also, have you ever thought about how you can sign into a website once and remain signed in, even if you close the tab or the browser? The answer to all these questions is cookies, which you will learn more about in this topic with some examples.
Why cookies?
A cookie is a piece of data, in other words, a small string of data sent by a server to the browser. But what's the need to send a string of data by the server? Before answering this, let's dig into history.
HTTP is a stateless protocol, which means it doesn't require the HTTP server to retain or store the information about each user for multiple requests. Now consider the above example of signing into a website to shop for certain items. As soon as you add items to your cart you are asked to fill in your credentials. You enter the information, the browser sends it to the server, after which then the server sends back the rendered data. But if the website is stateless and once you try to add another item from a different page, the web server would not remember that you've already signed in. You will be asked to fill in the credentials again and then you'd be able to add items to your cart. That would be rather hectic, so there was a pressing need to develop stateful sessions on the web. So, cookies came into play.
What are cookies?
A cookie is a small string of data that is stored in the browser and sent by the web server. These cookies are stored in name=value pairs and delimited by ;. Whenever a request is made to the server, it sends a small string of data, that is, a cookie to the user's browser, and the browser can accept a cookie that gets stored locally in the user's computer. When the user arrives at another page of the same website the browser sends the same cookie to the server for retrieval. Once retrieved, the server already knows what was stored earlier on the website.
Cookies are the most efficient way of tracking or remembering the user's preferences, purchases, and other information which may be required for a better experience on the websites. As discussed above, cookies are stored in the form of plain text, and there are some properties, or attributes of the cookie, which are explained below. But first, let's see how you can access cookies from the browser.
In your console inside the browser, you can type document.cookie to access the cookies. You can open the console straightaway while on any of the websites or platforms and see which cookies are present. The example below displays what a cookie would look like:
"pixelRatio=1.25; _ga=GA1.2.1733290612.1663742642; _ym_uid=1614948498645601200; _ym_d=1663742643;
_gid=GA1.2.136817066.1670087116; my%20name=John%20Smith; _ym_isad=2; _ym_visorc=b" You can also access the cookies from the developer tools, as you can see below:
The image above shows the cookies from the JetBrains home page. Note that the values may differ based on the user's preferences. You can also check what cookies are present on your side from the developer tools. Right-click on the home page -> Inspect -> Application -> Select cookies from the left-most menus.
Details of cookies
You can also write to document.cookie: you can create your own cookie, but it should be a name=value pair. Remember that only the cookies listed in a document.cookie are updated during a write operation; other cookies are left alone or unedited. See the example below:
> document.cookie
'-fiijwen_=990fej0_ijlwllgwbwoe; 1P_JAR=2022-12-05-12 DV=U_6LHprzlRNXcKt5a0Qc82JSXWvYTRgaJbqIpnojPI5GAAAAA;
SIDCC=AIKkIs190-gx5liI9HspfhVRRMBlN9jfkKxsa-ctdsNH2pXtUiY9rYo3kS2xT3AZ7kgYvX08bx9F'
> document.cookie = "newCookie=helloIamNewCookie-Hehe"
'newCookie=helloIamNewCookie-Hehe'
> document.cookie
'-fiijwen_=990fej0_ijlwllgwbwoe; 1P_JAR=2022-12-05-12 DV=U_6LHprzlRNXcKt5a0Qc82JSXWvYTRgaJbqIpnojPI5GAAAAA;
SIDCC=AIKkIs190-gx5liI9HspfhVRRMBlN9jfkKxsa-ctdsNH2pXtUiY9rYo3kS2xT3AZ7kgYvX08bx9F;
newCookie=helloIamNewCookie-Hehe'
That means that the document.cookie= operation does not overwrite all the existing cookies. It only assigns the mentioned cookie newCookie with a value. The name and value in a cookie can have any characters. But, to keep valid formatting, they should be escaped with a built-in encodeURIComponent function. Let's see the example below:
let cookieName = "This a cookiename";
// Special characters like 'spaces', '$', '%' etc. are encoded as %20, %25, %24, respectively.
let cookieValue = "This isthe %value$ of a cookieName"
// encodes the cookie
document.cookie = encodeURIComponent(cookieName) + '=' + encodeURIComponent(cookieValue);
document.cookie // This%20a%20cookiename=This%20isthe%20%25value%24%20of%20a%20cookieName'Options in cookies
path:
path=/mypath. The prefix of the URL must be absolute. It enables the cookie to be accessed by pages that are under that route. By default, it follows the current route. If a cookie is set withpath=/newpath, it's visible on pages/newpathand/newpath/someotherpath, but not at/thatpathor/newerpath.domain:
domain=example-site.com. Normally, a cookie can only be accessed at the domain that created it. For example, somepage.com will never receive a cookie placed at thatpage.com since there is no mechanism to allow a cookie to be accessible from another second-level domain. Also, remember that, by default, cookies are not shared with subdomains either. For example, newpage.somepage.com doesn't contain the cookies set at somepage.com. However, if you'd like to allow subdomains to get a cookie set at the primary domain, you can use the domain and set the domain option to the root domain, such asdomain=somepage.com, in this example. In this way, all the subdomains will be able to access the cookie.expires: a cookie disappears when the browser is closed (called session cookies) and when it doesn't have an option like
expires. If you want the cookie to survive even if the browser is closed, you can set theexpiresoption. The value of theexpiresoption is the time when the browser will delete the cookie automatically.max-age: this option is the same as the
expiresoption. The value of this option is specified in seconds from the current moment. The cookie is deleted instantly if the value ofmax-ageis 0 or any negative value.secure: by default, if you set a cookie at http://somepage.com it also appears at https://somepage.com vice versa. If the
secureoption is set, a cookie set byhttps://somepage.comdoesn't appear when the same site is accessed by http://somepage.com.samesite: this option is set to protect the cookies from XSRF (cross-site request forgery) attacks.
The following example represents how you can use all these options while setting a cookie:
// cookie (name=value pair)
document.cookie = "cookieName=valueOfCookie";
// cookie accessible under '/adminpage' or '/adminpage/mypage'
document.cookie = "cookieName=valueOfCookie; path=/adminpage";
// expires at the given date and time
document.cookie = "cookieName=valueOfCookie; expires=Wed, 25 Mar 2060 06:20:15 GMT";
// expires at +2 hr(7200s) from the current moment
document.cookie = "cookieName=valueOfCookie; max-age=7200"
// cookie is accessible at this-site.com or on any subdomains
document.cookie = "cookieName=valueOfCookie; domain=this-site.com";
// cookie is transferred only over HTTPS.
document.cookie = "cookieName=valueOfCookie; secure" Use cases of cookies
Cookies are mostly used for the process of authentication on various websites or web applications. Let's see how they play a vital role in authentication. Suppose a user visits a page that requires authentication. To interact with the whole website, the user signs in, and the server uses the Set-Cookie HTTP header to set a cookie with a unique identifier called a session identifier. Next time the user tries to sign in, the request transfers to the same domain, the Cookie HTTP header is used to send the cookie from the browser over the net. So, this time the server knows who made the request, and the user doesn't have to enter the credentials again.
Cookies are also used for session management: you may control what data the server should keep in memory with the help of cookies. Take user login credentials, shopping carts and so on as examples.
Cookies are also used to store and maintain user preferences, additional settings specific to a user, some themes set by a user, and so on. Also, cookies are a great way to record and analyze the user's activity for advertising purposes. Various web applications use cookies for better experiences in viewing ads on various platforms.
Conclusion
In this topic, you learned what are cookies and how they are used for authentication, adding cart items, and other purposes. These cookies are sent by the server to the browser, which is in the form of name=value pair. You can see what cookies are stored by a specific website using document.cookie. We've also discussed various use cases of cookies, such as session management, and they are also used to store and maintain user preferences, some themes set by a user, and a lot more.