shaikhu-blog-v1627328294/shaikhu/rsz_1add_a_subheading_cujuhr.png

What is http cookie and how it works?

Published on 2021-07-26, by Javed Shaikh

Subscribe for new article
*No spam. unsubscribe at anytime

Introduction

A cookie or HTTP cookie is a small set of strings specially in name value pairs that are stored in the user’s web browser. This string is set by a server and is mostly used to identify the clients.

Why cookie?

The HTTP protocol is stateless which means that the server does not remember about any response it sent to the user’s browser. It executes each request independently without knowing past requests that were already been executed. This is not at all good if a user is accessing a secure page like making a financial transaction. Due to stateless scheme, server cannot identify if the request is coming from a valid customer or not. To solve such issues, cookie concept was introduced which is fairly easy to understand and implement.

How HTTP Cookie can solve above problem?

Lets see how cookie can solve the above problem. When a user signs in to a server, the server creates a unique ID and set it as a name value pair string with an expiry date or timestamp and sends it to the user’s browser. When the same user makes a transaction or access another secure page on the same server, it sends the http cookie along with the request. Upon receiving another request from the user, the server extracts and validates the cookie ID, expiry date in the cookie string and allows or declines the request.

Cookie attributes

As mentioned earlier, a cookie is a name value pair string set by the server. Along with the name value pair, a cookie has optional attributes like expiry date,domain, path and few others. Lets check one by one.

  • <name>=<value> : name-value pair data
  • expires=<GMT date string>: date after which cookie will no longer be active or validate
  • Max-Age=<seconds>: same as expires. Invalid after number of seconds set by this attributes
  • Domain=<domain>: it tells the host or server name to which browser will send the requests
  • Path=<path>: it tells the directory for which cookie will be validate
  • Secure: it tells cookie will be valid only on https secure protocol
  • samesite=<value>: It is used to protect from cross site request forgery attacks or CSRF attacks

How to set cookie(<name>=<value>) ?

All cookies can be seen in the browser using document.cookie property.It will return all the cookies set by the server separated by semicolon.

Let’s go to developer tools of a browser and select console tab and enter document.cookie, it will return all the cookies set by the server.
In the below screenshot we are checking cookies from the web page of https://developer.mozilla.org/ . Please note how cookie is set.

post image shaikhu/cookie_pinyuf

Since a cookie is a name value pair data, we can set cookie as shown below using JavaScript

javascript
1document.cookie ="user_id=abc0123456789";

This will set or update cookie for user_id.

expires=<GMT date string>

Each cookie has an expiry date after which the cookie will no longer be active. If a cookie does not have expiry date, that cookie will be invalidated or trashed once browser is closed. This type of cookie is called session cookie.

To set an expiry date, expires=<date> attribute can be used which takes HTTP date. Date must be in the GMT format. We can use toUTCString() to convert date to GMT format.

Example:

python
1expires=Mon, 26 Jul 2021 19:19:07 GMT

The expiry date should exactly follow above format.

Below example will set cookie expiry date to 1 hour from now.

javascript
1const expiry_date = new Date(Date.now()+60*60*1000).toUTCString(); 2document.cookie = "user_id=abc0123456789;" + “expires= + expiry_date; 3

post image shaikhu/cookie2_fscdck

Max-Age=<seconds>

This is another optional attribute similar to <expires>, but it takes time in number of seconds as value after which the cookie will expire.

We can set same above cookie with Max-Age attribute instead of expire attribute . The below cookie will be trashed after 60*60 seconds.

javascript
1document.cookie ="user_id=abc0123456789; max-age=3600"

Domain=<domain>

The Domain attribute is used by the browser to identify the host or server where it should sent the cookie to. The default domain is the host of the current web page. Also if I set the domain as shaikhu.com, then other subdomain can also read the cookie.

However if I set the domain to blog.shaikhu.com, then only blog subdomain can have access to that cookie,it wont' be available to other subdomains. Also we cannot set the domain attribute to another domain or host other than your own server/host.

Below example sets shaikhu.com as domain, that means this http cookie will be available to all the subdomains as well.

javascript
1document.cookie = "user_id=abc0123456789; domain=shaikhu.com;"

path=<path>

The path attribute is used to set the directory where the cookie should be valid and read.All other directories cannot read that cookie. By default, path is set to / to read cookie on all pages and directories of that domain.

Below example sets cookie only for /myaccount , so it cannot be read on another directory.

javascript
1document.cookie = "user_id=abc0123456789; path=/myaccount;"

Secure

If this attribute is set, the cookie will only be sent over the https protocol. Below example shows how to set secure attribute for a cookie

javascript
1document.cookie = "user_id=abc0123456789; Secure;"

samesite=<value>

This attribute is used to protect from cross site request forgery attacks.

samesite=strict

If a cookie is set with samesite=strict, then the browser will send that cookie only for the requests to the server that created this cookie. It is never going to send the cookie if the request is made from different URL.

samesite=lax

This is the default value for samesite attribute in case the samesite attribute is missing or absent. This is basically used to allow cookie to the origin server upon following a link from external website or emails.

Thanks for reading. Let me know your thoughts on twitter or using contact page.

References

Visit these pages for more information on cookies.

My other recent posts

About the Author

I am a Backend System Engineer at a credit card company, specializing in C/C++ and assembler on IBM's TPF OS. I have a passion for web development and enjoy working with Node.js and Python in my free time.

Connect with author

Related articles ...

How to use localStorage and sessionStorage in JavaScript?

World Wide Web Consortium or W3C introduced two storage object mechanisms to store data in the browser which are localStorage and sessionStorage objects

2021-07-28

How to check if a string contains a substring or not in JavaScript?

There are two methods in JavaScript to find if a string contains another string or not. The includes() method returns true or false after a search and indexOf() method returns index of a string or -1 if it does not find a match

2021-08-08

How to check if a string is null, blank, empty or undefined using JavaScript?

Instead of using any library function, in this post we are going to learn how to check if a string is null, blank, empty or undefined with just one line instruction

2021-08-10