JavaScript

Attributes of Cookies in JavaScript | Explained

Nowadays, it is essential to maintain the session information across multiple pages for most websites. Usually, when a web server responds by sending a web page to your browser, the connection gets terminated, and all of the data stored on the server is lost. This situation makes it difficult to store the information related to the user session, and you can not refer to the server for accessing it.

In such a scenario, Cookies are used to store useful information that can be fetched later to get to know about the user. Cookies comprise tiny bits of data kept in a web browser and used to track user activity. They also permit the website to provide specific features according to a particular user. As a result, cookies are considered a core component of a website’s functionality.

This write-up will explain the Attributes of Cookies in JavaScript with the help of suitable examples. So, let’s start!

Attributes of Cookies in JavaScript

JavaScript supports the following four cookie attributes:

  • expires
  • max-age
  • path
  • domain

The below-given sections will demonstrate the methods to use these attributes for enhancing the functionality of cookies in JavaScript.

Note: Cookies expire after a certain amount of time; however, the cookie’s expiration settings can be handled through its offered “expires” attribute in JavaScript.

Expires Attribute of Cookies in JavaScript

Cookies are automatically removed when the browser is closed. It prohibits the visitors from reusing the cookie’s values when they later visit the website. However, this behavior can be controlled by setting the “expiration date” for the cookie.

Cookies in JavaScript offer an “expires” attribute that permits you to add an “expirationDate” in Universal Time Coordinated (UTC) to the “name=value” cookie pair.

Syntax of Expires Attribute of Cookies in JavaScript

document.cookie = "name=value;expires=expirationDate UTC"

Here, the “expires” attribute is utilized to maintain the cookie’s state according to the “expirationDate” and “UTC” time.

Example: Expires Attribute of Cookies in JavaScript

First of all, in our “index.html” file, we will add two buttons: “setCookie” and “getCookie”. The “setCookie” button invokes the “setCookie()” function to set the specified cookie, whereas, the “getCookie” button calls the “getCookie()” function to fetch the already set cookies:

<input type="button" class="button" value="setCookie" onclick="setCookie()">

<input type="button" class="button" value="getCookie" onclick="getCookie()">

In our “project.js” file, we will define the “setCookie()” and “getCookie()” functions that are associated with the “onclick” events of the “setCookie” and “getCookie” buttons. The “setCookie()” function will create a cookie having “username” as cookie “name” and “Sharqa” as its “value”, and the “expires” attribute’s value as “Sun, 10 Aug 2030 12:00:00 UTC”:

function setCookie() {

document.cookie = "username=Sharqa;expires=Sun, 10 Aug 2030 12:00:00 UTC";

}

Then, after checking the length of the created cookie in the “if” statement, the “getCookie()” function will fetch the cookie “name” and “value” and display it in an alert box. In the other case, if the cookie gets expired or deleted, the alert box will state that “Cookie not available”:

functiongetCookie() {
    if (document.cookie.length != 0) {
        vararray = document.cookie.split("=");
        alert("Name=" + array[0] + " " + "Value=" + array[1]);
    }
    else {
        alert("Cookie not available");
    }
}

Now, we will save both files and then utilize the VS Code “Live Server” extension to run the application in the browser:

The opened web page comprises two buttons: “setCookie” and “getCookie”, where clicking on the “setCookie” will create a new cookie with specified “name”, “value”, and “expires” attribute value:

To view the “name-value” cookie pair in an alert box, click on the “getCookie” button:

The following alert box shows the cookie name as “username” and its value as “Sharqa”:

You can also use the “Developer Console” to check the details related to the added cookie. To do so, right-click on the browser, and from its context menu, select the “Inspect” option:

Next, click on the “Application” option from the top-bar of the Developer console and look for “Cookies” in the “Storage” menu, present at the left side of the window:

It can be seen in the above-given image that we have successfully created a cookie and set its expiration date with the help of the “expires” attribute.

Max-age Attribute of Cookies in JavaScript

A cookie’s lifetime is set according to the current session duration of the browser, which means that the cookie will expire as soon as the user closes the browser. You can use the “max-age” attribute to define its lifetime, which will be independent of the browser session duration.

Syntax of Max-age Attribute of Cookies in JavaScript

document.cookie = "name=value;max-age=" time

Here, the “max-age” attribute is utilized to specify the “time” within which the created cookie will stay in the system before its deletion. This attribute accepts a time value in “seconds”.

Example: Max-age Attribute of Cookies in JavaScript

Now, we will create a cookie having “username” as its “name”, “Alex” as “value”. Also, the “max-age” attribute of the cookie will set its lifetime to “30” days:

document.cookie = "username=Alex;max-age=" + 30*24*60*60 + ";"

After saving the added code, open up the “index.html” file in the browser and click on the “setCookie” button for creating a new cookie and setting its lifetime:

The following alert box will be now displayed on the browser:

To verify the lifetime of the created cookie, explore the “Expires / Max-Age” column in the following window:

In the above-given image, the “Expires / Max-Age” column contains the specified “max-age” attribute value according to the “Unix timestamp epoch”.

Path Attribute of Cookies in JavaScript

In JavaScript, a cookie is accessible for all web pages present in the same directory or sub-directories. However, you can use the “path” attribute to control the scope of the cookies across the web pages.

Syntax of Path Attribute of Cookies in JavaScript

document.cookie = "name=value; expires=expirationDate; path=/PATH";

Here, the “path” attribute is utilized to specify the “PATH” for which the created cookie is “accessible”.

Example: Path Attribute of Cookies in JavaScript

We will create a cookie by the name “username,” which comprises a value “Alex”, and set its expiration date and time as “Wed, 10 Jan 2030 23:00:00 UTC”. Then, we will set its “path” attribute to “/,” which signifies that the created cookies will be available throughout a website:

document.cookie = "username=Alex; expires=Wed, 10 Jan 2030 23:00:00 UTC; path=/";

Save the provided code in your “index.html” file and open it in the browser:

Now, click on the “setCookie” button, and then move to the Developer console window for the reconfirmation of the added path:

As you can see in the “Path” column, the path attribute of the “username” cookie is set to “/”:

The “path” and the “domain” attribute of cookies are primarily used together while creating a cookie in JavaScript. Now, we will discuss the “domain” attribute in the next section.

Domain Attribute of Cookies in JavaScript

The “domain” attribute of the JavaScript cookies is used to add the domain for which the cookie is considered “valid”. For instance, the “domain” attribute’s value is “linuxhint.com”, then the set cookie will be valid for the specified domain and its sub-domains.

Syntax of Domain Attribute of Cookies in JavaScript

document.cookie = "name=value; path=/PATH; domain=DomainName";

In the above-given syntax, the “domainName” value specifies the domain to which the cookies belong.

Example: Domain Attribute of Cookies in JavaScript

For instance, we will create a cookie on “blog.linuxhint.com” and set the value of the “path” attribute to “/” and domain attribute’s value to “linuxhint.com”, then the cookie will be accessible for the webpages of the “linuxhint.com” website:

document.cookie = "name=value; path=/PATH; domain=DomainName";

Instead of “linuxhint.com”, if we provide the sub-domain “blog.linuxhint.com”, then the “username” cookie will be valid only for the added subdomain. Therefore, the ideal approach is to specify the corresponding domain instead of the sub-domain value.

For the demonstration purpose, we will set “127.0.0.1” as a domain for a cookie:

document.cookie = "name=sharqa; path=/; domain=127.0.0.1";

The below-given output signifies that we have successfully set “127.0.0.1” as a valid domain for the created “key-value” cookie pair:

We have compiled the essential information related to attributes of Cookies in JavaScript.

Conclusion

expires”, “max-age”, “path”, and the “domain” are the attributes of cookies in JavaScript. The expires and max-age attributes are utilized for setting the expiration date and the lifetime of cookies. In contrast, the combination of domain and path attributes assist in specifying the valid domain and scope where the cookies are available. This write-up explained the attributes of Cookies in JavaScript with the help of suitable examples.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.