JavaScript Set Get And Remove Cookies

Set cookie and get cookie with JavaScript. Here's a function that set get and remove cookie

JavaScript Set Cookies Function Code

This JavaScript function is used to set a cookie. Add the function parameter cookie name, value, and expiration days. You can also set cookie attributes path, domain, sameSite, etc...

JavaScript
const setCookie = (name, value, days, attributes) => {
    let attr = [];
    // Encode the value to escape semicolons, commas, and white-space
    let name_value = name + "=" + encodeURIComponent(value);
    attr.push(name_value);
    if (typeof days === "number") {
        let expires = "expires=" + new Date(Date.now() + 864E5 * days).toUTCString();
        attr.push(expires);
    }
    if (typeof attributes == 'object') {
        attributes.path = attributes.path == undefined ? "/" : attributes.path;
    }else{
        attributes = {
            path : "/"
        };
    }
    for (let attribute_name in attributes) {
        if (attribute_name != "expires" || attribute_name != "max-age") {
            let attr_name = attribute_name+"="+attributes[attribute_name];
            attr.push(attr_name);
        }
    }
    return document.cookie = attr.join("; ");
};

Usage Set Cookie

By default the lifetime of a cookie is the current browser session, meaning it is lost when the user exits the browser.

By default cookie path / that can be used site-wide

JavaScript Set cookie that can be used site-wide

setCookie("name", "value");
// 'name=value; path=/'
// This cookie only expires when the user exits the browser

Create a cookie that expires 30 days from now

setCookie("name", "value", 30);
// 'name=value; expires=Tue, 22 Dec 2022 17:14:11 GMT; path=/'

Create an expiring cookie and set the cookie path to the current page

setCookie("name", "value", 30, {path:""});
// 'name=value; expires=Thu, 22 Dec 2022 17:14:33 GMT; path='

Set more cookie attributes. path, domain, SameSite and Secure

setCookie("name", "value", 30, {path:"/", domain:".domain.com",SameSite:"none"});
// 'name=value; expires=Thu, 22 Dec 2022 17:14:49 GMT; path=/; domain=.domain.com'

JavaScript Get Cookies Function Code

This JavaScript code is used to get the cookie name. Add the function parameter cookie name, if the cookie exists, you will get the decoded cookie value. or a null value. If you don't pass a cookie name as a function parameter, you get all visible cookies as an object. or empty {} object.

JavaScript
const getCookie = key => {
    let cookies = document.cookie.split('; ');
    let cookies_list_obj = {};
    for (let i = 0; i < cookies.length; i++) {
        let name_value = cookies[i].split('=');
        let name = name_value[0];
        let value = decodeURIComponent(name_value[1]);
        cookies_list_obj[name] = value;
        if (key === name) {
           break;
       }
    }
    if (key !== undefined) {
        return cookies_list_obj[key] ? cookies_list_obj[key] : null;
    }else{
        return cookies_list_obj;
    }
};

Usage Get Cookie

Read cookie

getCookie('name'); // => 'value'
getCookie('nothing'); // => null

Read all visible cookies

getCookie(); // => { name: 'value' }

Check if the cookie name exists or not

if (getCookie('name') != null) {
    // cookie name exists
    // do something
} else {
    // no cookie
    // do something
}

Get all visible cookies and convert them to objects.

var cookies_obj = getCookie(); 
// => { name: 'value', 'second-name': 'second-value' }
if(cookies_obj['your-cookie-name']){
  // do something
}else{
  // no cookie
}

If there are no visible cookies, an empty object is returned.

var cookies_list = getCookie(); 
// => {}

JavaScript Remove Cookie Function Code

This JavaScript code is used to remove cookie. Add the function parameter cookie name and cookie attributes

JavaScript
const removeCookie = (name, attributes) => {   
    let attr = [];
    let name_value = name + "=";
    attr.push(name_value);
    if (typeof attributes == 'object') {
        attributes.path = attributes.path == undefined ? "/" : attributes.path;
    }else{
        attributes = {
            path : "/"
        };
    }
    attributes.Expires = "Thu, 01 Jan 1970 00:00:01 GMT";
    for (let attribute_name in attributes) {
        if (attribute_name != "max-age") {
            let attr_name = attribute_name+"="+attributes[attribute_name];
            attr.push(attr_name);
        }
    }
    return document.cookie = attr.join("; ");
};

Usage Remove Cookie

Delete cookie

removeCookie("name");

Delete the cookie using the path of the current page

When deleting a cookie you must set the same path and domain attributes that were used to set the cookie.

setCookie("name", "value", { path: "" });
removeCookie("name"); // fail!
removeCookie("name", {path: ""}); // removed!

A Single JavaScript Function Code For Set, Get, And Remove Cookies

This JavaScript code is used to set get and remove cookies.

JavaScript
(function(global, factory) {
    global.jscookie = factory();
})(this, function() {
  // script generated by https://www.html-code-generator.com/javascript/set-get-cookies
  return {
      set: (name, value, days, attributes) => {
          let attr = [];
          let name_value = name + "=" + encodeURIComponent(value);
          attr.push(name_value);
          if (typeof days === "number") {
              let expires = "expires=" + new Date(Date.now() + 864E5 * days).toUTCString();
              attr.push(expires);
          }
          if (typeof attributes == 'object') {
              attributes.path = attributes.path == undefined ? "/" : attributes.path;
          } else {
              attributes = {
                  path: "/"
              };
          }
          for (let attribute_name in attributes) {
              if (attribute_name != "expires" || attribute_name != "max-age") {
                  let attr_name = attribute_name + "=" + attributes[attribute_name];
                  attr.push(attr_name);
              }
          }
          return document.cookie = attr.join("; ");
      },

      get: key => {
          let cookies = document.cookie.split('; ');
          let cookies_list_obj = {};
          for (let i = 0; i < cookies.length; i++) {
              let name_value = cookies[i].split('=');
              let name = name_value[0];
              let value = decodeURIComponent(name_value[1]);
              cookies_list_obj[name] = value;
              if (key === name) {
                  break;
              }
          }
          if (key !== undefined) {
              return cookies_list_obj[key] ? cookies_list_obj[key] : null;
          } else {
              return Object.keys(cookies_list_obj).length === 0 ? null : cookies_list_obj;
          }
      },

      remove: (name, attributes) => {
          let attr = [];
          let name_value = name + "=";
          attr.push(name_value);
          if (typeof attributes == 'object') {
              attributes.path = attributes.path == undefined ? "/" : attributes.path;
          } else {
              attributes = {
                  path: "/"
              };
          }
          attributes.Expires = "Thu, 01 Jan 1970 00:00:01 GMT";
          for (let attribute_name in attributes) {
              if (attribute_name != "max-age") {
                  let attr_name = attribute_name + "=" + attributes[attribute_name];
                  attr.push(attr_name);
              }
          }
          return document.cookie = attr.join("; ");
      }
  };
});

Usage Get Set Remove Cookie

As mentioned above, the cookies function parameter should be used here as well. Here only the name of the function changes.

javaScript set cookie

jscookie.set("name","value",30);

javaScript get cookie

jscookie.get("name");

javaScript remove cookie

jscookie.remove("name");