How to Set, Get and Delete Cookies using Vanilla JavaScript

In this tutorial, we are going to learn how to SET, GET and DELETE Cookies using Vanilla JavaScript. We will create methods for all the operations to make it reusable. It will help you in your JavaScript projects.

Cookie Javascript
Cookie Javascript | Fineshop Design

Getting Started

Follow the following steps to use the codes in your HTML document.

Table of Contents

Basic

Add the following JavaScript codes under a <script> in the head section of your HTML document.

/*!
 * cookie.js by Fineshop Design
 * ----------------------------
 *
 * MIT License
 *
 * Copyright (c) 2021 Fineshop Design
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
window.cookie =
  window.cookie ||
  Object.defineProperties(
    {},
    {
      value: {
        get() {
          return document.cookie;
        },
        set(value) {
          document.cookie = value;
        },
      },
      get: {
        value(key) {
          const regex = new RegExp(
            `(?:^|; )${encodeURIComponent(key).replace(
              /[-\/\\^$*+?.()|[\]{}]/g,
              "\\$&"
            )}=([^;]*)`
          );
          const matches = this.value.match(regex);
          if (matches && typeof matches[1] === "string") {
            return decodeURIComponent(matches[1]);
          }
          return null;
        },
      },
      getAll: {
        value() {
          const cookies = {};
          const cookieArray = this.value.split("; ");
          for (let i = 0; i < cookieArray.length; i++) {
            const cookieParts = cookieArray[i].split("=");
            if (typeof cookieParts[0] === "string") {
              const cookieName = decodeURIComponent(cookieParts[0]);
              const cookieValue = cookieParts[1]
                ? decodeURIComponent(cookieParts[1])
                : "";
              cookies[cookieName] = cookieValue;
            }
          }
          return cookies;
        },
      },
      has: {
        value(key) {
          return this.get(key) !== null;
        },
      },
      set: {
        value(key, value, options) {
          const object = Object.assign({ path: "/" }, options);

          let cookieString = `${encodeURIComponent(key)}=${
            typeof value !== "undefined" ? encodeURIComponent(value) : ""
          }`;

          for (let flagKey in object) {
            let flagValue = object[flagKey];
            switch (flagKey) {
              case "expires":
                if (flagValue instanceof Date) {
                  flagValue = flagValue.toUTCString();
                }
                break;
              case "maxAge":
                flagKey = "max-age";
                break;
              case "sameSite":
              case "samesite":
                flagKey = "samesite";
                if (flagValue === "none") {
                  flagValue = true;
                }
                break;
            }
            cookieString += `; ${flagKey}`;
            const shouldAddValue =
              typeof flagValue === "boolean"
                ? flagValue !== true
                : typeof flagValue !== "undefined";
            if (shouldAddValue) {
              cookieString += `=${flagValue}`;
            }
          }

          this.value = cookieString;
          return cookieString;
        },
      },
      remove: {
        value(key) {
          this.set(key, "", {
            maxAge: -1,
          });
        },
      },
      clear: {
        value() {
          for (const key in this.getAll()) {
            this.remove(key);
          }
        },
      },
      keys: {
        get() {
          return Object.keys(this.getAll());
        },
      },
      size: {
        get() {
          return this.keys.length;
        },
      },
    }
  );

Functions

cookie
.get(key) ⇒ string | null
.getAll() ⇒ Record<string, string>
.has(key) ⇒ boolean
.set(key, value, [config]) ⇒ string
.remove(key) ⇒ void
.clear(key) ⇒ void

cookie.set(key, value, [config]) ⇒ string

To set cookie with desired key and value.

Param Type Default Description
key string Key of the cookie to set
value string Value of the cookie key
[config] object { path: "/" } To add "max-age" (number), secure (boolean), etc

Returns:

string

Example:

const userDetails = {
  name: "Deo Kumar",
  email: "deo@fineshopdesign.com"
};
cookie.set("user", JSON.stringify(userDetails), {
  secure: true,
  maxAge: 3600 // will expire after 1 hour
});

cookie.get(key) ⇒ string

To get cookie with its key.

Param Type Default Description
key string Key of the cookie to get

Returns:

string | null: Returns value of the cookie key if exists otherwise null.

Example:

const cookieValue = cookie.get("user");
const userObj = cookieValue ? JSON.parse(cookieValue) : null;
console.log(userObj);

cookie.getAll() ⇒ Record<string, string>

Returns key-value pairs of existing cookies.

Returns:

Record<string, string>

Example:

cookie.getAll(); // { user: '{"name":"Deo Kumar","email":"deo@fineshopdesign.com"}' }

cookie.remove(key) ⇒ void

To remove cookie with its key.

Param Type Default Description
key string Key of the cookie to remove

Returns:

undefined

Example:

cookie.remove("user");

There are more methods available, you can try it yourself 😁.

Related Posts

Copyright (c):
fineshopdesign.com

About the author

Deø Kumar
Lost in the echoes of another realm.

Post a Comment

To avoid SPAM, all comments will be moderated before being displayed.