Javatpoint Logo
Javatpoint Logo

Http Cookies

An Http cookie, also known as a web cookie, is a small piece of data that the server sends to the web browser. The browser may store the cookies and send them back to the server with other requests. The typical use of the cookies is to identify multiple requests from the same resource (browser). It helps the user to keep logged in and trace his data, such as user name and session. It is also useful to remember the stateful information for the stateless HTTP protocol.

If you are a developer, you cannot skip the cookies as it will be helpful for session management and tracking the other user info. A cookie is very important nowadays as any other functionality of the app. Cookies make many things easier for both the user and the developer.

Cookies have been used for a long time and are being developed magnificently. A cookie is just textual information about the web application. When a user visits a website, some information is saved to the local storage of the system so that if They visit again, the app will be able to identify the user and show the relevant results.

When the user visits any site, he requests the application's home page from the server, and when He selects any specific action, he again requests any other page of the application. So if the user visits the 100th time every time, the request will be unique. Since the requests to the server are highly intensive, it is impossible to save data straight to the server; also, it may lead to an overload on the server. Also, the information collected will be redundant if the user does not visit again. So, to remember the user's identity, the server sends cookies along with the response, which is saved to the system's local storage. Next time the same client makes the request, the server will recognize its identity and display the result accordingly.

Cookies are unique to the server, so that the user might have many cookies in their system, but a server identifies its cookie.

In this section, we will discuss the following topics about cookies:

  • Usage of cookies
  • How Cookies Works
  • JavaScript Cookies
  • Cookies Properties
  • Types of Cookies

Usage of Cookies

The following are some common usage of the cookie:

Session Management:

The primary use of the cookie is to manage user logins, shopping cart details, game scores, or anything else the server should remember when the user logs in next time.

Generally, the session management facilitates the user to provide a secure interaction with the server through the application. Since the user continues to interact with the web application, they create a new request every time they visit the website. So, it provides an easy way to track their status and activity during the session.

Tracking

Tracking involves recording the user activity and analyzing their behaviours to personalize the content for them. It records and analyzes their habits and interests and finds the pages that they visit. The tracking details may include the time spent on a page or across the website during a session. There is some sensitive information in the user tracking, so the user should be aware of the vulnerabilities of visiting insecure websites and avoid if possible visiting such websites.

Personalization

Cookies help in personalizing user preferences, themes, and other settings. Most of the time, these settings are synchronized with a central database to personalize the things for the users when the user logs in for the first time. The user personalization keeps the information of the user preferences and settings for reapplying when the user logs in or restarts the application.

Authentication

Cookies are also very important in user authentication. When the user signs in, the server uses the Set-Cookie HTTP header in response to set a cookie with a unique "session identifier".

Next time the same user requests the same domain, the browser sends the cookie over the net using the Cookie HTTP header.

Thus the server can have the information on who made the request.

How Cookies Works

When a user interacts with a website, a new request to the server is sent, and when he performs any action within the application each time, a new request is sent to the server. The server considered every new request sent by a different user.

To recognize the requests by the same user, the developers need to add the cookie with the server's response, which is stored in the system's local memory. So if the same user sends a request to the server, the server identifies the user using cookies.

From the client side communication, the web browser is the medium to send the request from the client to the server.

Once the developers add the cookie, the requests sent by the users are identified, and the server sends the response as per the personalization.

From both the user's and developers' perspectives, cookies are very important. It helps both to have the proper responses.

Let's understand how to create cookies in JavaScript.

JavaScript Cookies

Let's understand how to create cookies in JavaScript:

Create Cookies

When the server receives a request, it can send one or more Set-Cookie headers with the response. It will be stored in the local storage of the system. So, the next time when the browser sends a request to the server, it will also send the cookie along with the request.

We can also specify the expiration date or time period after which the cookie will be expired and should not be sent. We can also have a few additional restrictions to a specific domain and path to limit when the cookie is sent.

JavaScript provides document.cookie property to create, read, update, and delete a cookie.

Below is the syntax to create a cookie:

There are two different ways to create an HTTP cookie. We can create cookies on the client side using the browser console or add them from the server in the file's script section. To add from the client side, we can open the console and add it in the browser by typing the JavaScript code. To add from the server side, we can add set-cookie headers to create one or multiple cookies.

Let's understand how to create cookies from the client and server sides.

Client Side

To open the cookie from the client side, open your browser's console and execute the below code:


Http Cookies

We can also see the cookies saved in the local system using the web browser's dev tool. To test if the cookie is added or not, navigate to the application tab of the dev tool and select the Cookies tab. Consider the below snap of the application tab:

Http Cookies

From the above screenshot, we can specify the cookie is stored in our local system.

Web Server Side

To add the cookie from the server, we need to create the cookie on an action when the user visits the website.

Consider the below example:

From the above example, it will render a button component on our web page. When we click the button, it will create the specified cookie for our system storage.

Similarly, we can add any other event listener to create the cookie. We can also add an onload event to set the cookie.

Let's understand cookie's properties:

Cookie's Properties

The properties of the cookies remain consistent across all types of cookies; the following are some common properties of different types of cookies:

Cookie scope

The scope of a cookie determines what URLs the cookie will be sent to. The cookie scope can be divided into two different attributes:

1) Path

The path is one of the attributes that define the scope of a cookie. It specifies a specific URL path to send the cookie in the HTTP header. To set the cookie to different paths, we can write the below code:

Now, when you visit a website to the specified URL, such as example.com/path1, you will send a cookie header "cookie_first=1".

If you visit a website to another URL, such as example.com/path2, you will send a cookie header "cookie_second=2".

Other requested paths will not send any cookie header except the specified URLs.

2) Domain

The second attribute of a cookie is the domain. Domains act as a bucket in which cookies are placed. The cookie assigns itself a unique domain name which helps the admin to keep the cookies specific and organized for each http request for the web pages. Below is an example of a domain-specific cookie:

Domain=javatpoint.com will set cookies to be available for the domain Javatpoint.com and its subdomains, such as training.javatpoint.com.

Expires and Max-age

The "Expires" and "Max-Age" properties of a cookie determine the lifetime of a cookie or its expiration date. They fall under the persistent cookies category. Except for the name "permanent cookie", the "Expires" attribute can delete a cookie for a specified date. Moreover, the "Max-Age" attribute will delete a cookie after a specified time.

Comparatively, the session cookies are deleted when the current session ends. Some browsers have the ability to specify when the current session will end, which can be any amount of time, including unlimited.

SameSite

The SameSite attribute allows us to set the cookie when clicking a link within a page. We have discussed how we can set the http cookies for a specific URL, but what if you want to set the cookie on click of a link within that direct URL? Using the SameSite, we can send the cookies by clicking on a link from a new page which is redirected. We can specify the SameSite to send the cookies with cross-site requests or whenever the user clicks on a link on a web page.

Let's understand how the SameSite property allows cross-site cookies with the following example. The below flow will explain how the cookies are sent and received when navigating from one page to another.

The user hits a URL (Example, Javatpoint.com)

He will receive a first-party cookie

On Javatpoint.com, the user will click on the link that sends a fetch request to another site, e.g. www.tutorialandexample.com.

Tutorialandexample.com will set a cookie with Domain=tutorialandexample.com

Now, javatpoint.com will hold a third-party cookie from tutorialandexample.com

The SameSite attribute specifies whether third-party cookies are sent with the following three values:

Strict

The SameSite attribute with the strict value will only be sent through a first-party cookie context. It will not consider third-party cookies.

Lax

The "Lax" value of a SameSite attribute will only be sent when the user clicks a link having third-party navigation. If the SameSite attribute is not directly set to the third-party link, lax is the default value.

None

If the SameSite attribute has a value of "None", the cookies will be sent in all contexts.

We have discussed the cookies and their properties; let's understand the types of cookies:

Types of Cookies

There are the following types of cookies which are identified by their usage and behaviours:

First-Party cookies

The first-party cookies are the cookies which are being sent to the system straight from the server of the site that you are visiting. These cookies are stored directly on your computer by the visited website. Most websites send cookies to the client to collect helpful information and analytics to improve the user experience.

The best example of a first-party cookie is authentication. When the user logs in to an application, the server sends the cookies to the client and stores them in their local system to identify the user. Next time, when you log in to the application, you do not need to submit the login information again.

Without first-party cookies, the website will not be able to identify the user and won't automatically log you in or remember your preferences from past sessions.

Third-Party cookies

The third-party cookies are created by the third-party domains to which you are redirected. It is not created by the same domain in which you have logged in. These cookies are generally created for tracking purposes and can be stored even after the browser is closed.

One great example of a third-party cookie is ad tracking from websites. You might have noticed that you have browsed a few products from various eCommerce sites, and you will start seeing the ads related to those products. Because while browsing the products, you might have been exposed to third-party cookies from a domain outside of that specific website. Later on, when you close the browser or that specific website, a third-party cookie can be used to track your browsing details, like what products you have seen and bought or not. After that, you will have to start receiving the emails regarding those products and see the ad from the different ad agencies.

Session cookies

The session cookies are also temporary cookies, which will expire when the user closes the browser tab. Usually, session cookies are used when the user enters their login credentials and logs in to the application. When the session cookies are used, the users have to provide their credentials every time when they try to log in to the application.

One best example of the session cookie is the shopping cart handling on an eCommerce site. Session cookies help in organizing the shopping cart of a user. If the site does not use the session cookies, it will be harder to remember what products they have chosen.

Secure cookies

The cookies provide a Secure attribute to prevent unauthorized access from the observing cookies sent to a user within an HTTP response. When the cookies are used with a Secure attribute, all the HTTP requests will only include the cookie if it is transmitted over a secure medium.

Initially, Microsoft Internet Explorer implemented the HttpOnly cookies in 2002. The cookies flagged with HttpOnly can be included in a Set-Cookie HTTP header. The HttpOnly attribute reduces the risk of users accidently clicking on a malicious link that may exploit cross-site scripting loopholes.

Generally, attackers try to add some malicious scripts to a trusted website and try to access cookies and other sensitive information from the local system storage.

Zombie cookies

We can guess the zombie cookies by their name. Just like Zombies, these types of cookies can be alive after killing. These cookies can come to life when cleared or the browser is closed.

Zombies cookies can store themselves in another place rather than the browser's dedicated storage. Generally, the Zombie cookie can create a replica of the original cookie, store it elsewhere, and attach it to the user's cookie storage again.

Previously, few companies used the zombie cookie to track user activity and access personal information. Few states have banned the zombie cookie and consider it an illegal invasion of privacy use of the zombie cookie.

Summary:

The Http cookies are very useful for both developers and users. They have been around the web for a long time and provide opportunities to understand people's interests and improve their user experience. In this section, we have discussed many important points about the HTTP cookies, such as their properties and types.

We have discussed several things, but many things are left to discuss and use the cookies properly and securely.

To learn more, visit the examples of cookies in JavaScript.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA