How to Set, Get And Delete Cookies in Vanilla JavaScript

Learn how to set, get, and delete cookies using Vanilla JavaScript. Step-by-step tutorial with reusable methods and examples for your projects.

Hello! Welcome to EmadulAi.

In this tutorial, we will learn how to Set, Get, and Delete cookies using Vanilla JavaScript. We will create reusable methods for each operation, so you can easily implement them in your JavaScript projects. This will help you manage cookies efficiently while keeping your code clean and organized.

Getting Started

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

Basic

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

/*!
 * cookie.js by EmadulAi
 * ----------------------------
 *
 * MIT License
 *
 * Copyright (c) 2021 EmadulAi
 *
 * 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: "/" } Optional settings:
• max-age (number) – Expiration in seconds
• secure (boolean) – Only sent over HTTPS
• path (string) – Cookie scope (default "/")

Returns:

string

Example:

const userDetails = {
  name: "Emadul Tarafdar",
  email: "[email protected]"
};

// Set cookie for 1 hour
cookie.set("user", JSON.stringify(userDetails), {
  secure: true,
  "max-age": 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(); 
// Output: { user: '{"name":"Emadul Tarafdra","email":"[email protected]"}' }

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");
// Removes the cookie with key "user"

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

Conclusion! That’s all about adding the How to Set, Get And Delete Cookies in Vanilla JavaScript in your Blogger posts. We hope you found this guide helpful and easy to follow. Please feel free to share this article with others. If you face any issues or have any questions regarding any step, don’t hesitate to ask in the comment section. Thank you for reading!

About the author

Emadul Tarafdar
Hello guys! My name is Emadul Tarafdar. If you enjoy my content, feel free to follow me on my social media links. Thanks so much for your support!

Post a Comment

Join the conversation