techStackGuru

JavaScript Cookies


A JavaScript cookie is a small piece of data that a website stores on the users browser. The cookies track and store the users interactions, preferences, and session state. Developers can personalize user experiences and store temporary data with JavaScript, which includes setting, retrieving, and deleting cookies.

Read all Cookies

const getAllCookies = document.cookie; 

Read Specific Cookie

var cookieValue = document.cookie.replace(/(?:(?:^|.*;s*)myCookies*=s*([^;]*).*$)|^.*$/, "$1");
console.log(cookieValue); 

Using the regex pattern, the value of the cookie "myCookie" is extracted from the string. In the console, the value is then logged.

Write a new cookie

document.cookie = newCookieValue; 

Several options exist in cookies, many of which are important. After key=value, the options are listed, separated by ;

document.cookie = "user=Vishal; path=/; expires=Wed, 21 Jan 2025 02:10:06 GMT" 

Using the Cookie class

A cookie can be set, retrieved, or removed using the Cookie class

// Setting a cookie
Cookie.set('username', 'admin');

// Fetching a cookie
console.log(Cookie.get('username')); // admin

// Removing a cookie by a name
Cookie.remove('username'); 

secure

To enhance cookie security, the "secure" attribute can be set in cookies. By enabling the secure attribute, cookies will only be transmitted over a secure (HTTPS) connection. By encrypting cookie data, malicious third parties are prevented from intercepting or tampering with it during transmission.

Security threats can be prevented by using the secure attribute on websites that store sensitive information, such as session IDs and user authentication tokens.

document.cookie = "myCookie=example; expires=" + new Date(Date.now() + 604800000).toUTCString() + "; secure"; 

encodeURIComponent()

Whenever a cookie value is set using JavaScript, special characters such as spaces, commas, or equal signs may appear. In order to avoid parsing issues, its critical to encode the cookie value using encodeURIComponent().

Consider the case where you would like to set the cookie "myCookie" with the value "Hello, World!".

var cookieValue = "Hello, World!";
var encodedValue = encodeURIComponent(cookieValue);
document.cookie = "myCookie=" + encodedValue; 

This ensures that cookies are properly encoded and can be stored safely by replacing special characters such as the comma (",") with their encoded counterparts ("%2C").

decodeURIComponent()

To decode the cookie value and obtain the original content, use decodeURIComponent():

var decodedValue = decodeURIComponent(document.cookie.replace(/(?:(?:^|.*;s*)myCookies*=s*([^;]*).*$)|^.*$/, "$1")); 

By combining encodeURIComponent() and decodeURIComponent(), errors in cookie parsing and data integrity are avoided.

Namespace conflicts

Several JavaScript libraries or scripts may attempt to set or access the same cookie with the same name. These conflicts are known as namespace conflicts. If the cookies are overwritten or accessed incorrectly, this may cause unexpected behavior or data corruption.

Using descriptive and unique cookie names is a good way to mitigate JavaScript namespace conflicts. Adding a namespace or identifier to the cookie names can help prevent clashes with other scripts or libraries.

To minimize the chances of conflicts, prefix your cookies with "MyApp_" if your application is named MyApp.

Example

document.cookie = "MyApp_myCookie=value; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/"; 

Domain Specific

JavaScript allows you to specify a domain for which cookies are valid when setting them. Cookies are "domain-specific" in this sense. It is possible to set a specific domain for the cookie, thereby controlling what domains it will be sent to with subsequent requests.

Example

document.cookie = "myCookie=value; domain=example.com; path=/"; 

Deleting a Cookie

Example

document.cookie = "myCookie=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; 

A cookie can be deleted by setting its expiration date to a past date. Setting the expiration date of the "myCookie" cookie to January 1, 1970 deletes the cookie.

JavaScript function example for setting, retrieving, and deleting cookies.

Setting a Cookie:

function setCookie(name, value, days) {
    var expires = "";
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}
  
setCookie("myCookie", "example", 7); 

Retrieving a Cookie:

function getCookie(name) {
    var cookieName = name + "=";
    var cookieArray = document.cookie.split(";");
    for (var i = 0; i < cookieArray.length; i++) {
      var cookie = cookieArray[i];
      while (cookie.charAt(0) === " ") {
        cookie = cookie.substring(1);
      }
      if (cookie.indexOf(cookieName) === 0) {
        return cookie.substring(cookieName.length, cookie.length);
      }
    }
    return null;
  }
  
var myCookieValue = getCookie("myCookie");
console.log(myCookieValue); // Output: "example" 

Deleting a Cookie:

function deleteCookie(name) {
    document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
  }
  
deleteCookie("myCookie");