If you enjoy our website, feel free to connect with us on Google News or become a part of our Telegram Group for more updates and engaging discussions.

How to Set, Get and Delete Cookies using Vanilla JavaScript

Simplify cookie handling in JavaScript with functions for easy setting, getting, and deleting, enhancing your code for web projects.
How to Set, Get and Delete Cookies using Vanilla JavaScript

In this guide, we'll delve into the fundamental aspects of handling cookies using plain JavaScript. We'll cover the essential operations of setting, getting, and deleting cookies, streamlining our code with dedicated functions for a more efficient approach. This tutorial aims to simplify these cookie-related tasks, providing a valuable resource for your JavaScript projects. Let's dive in and enhance your proficiency in managing cookies within your web development endeavors.

Getting Started

To incorporate the provided code into your HTML document, follow these sequential steps for seamless integration.

Tabel of Content

Basic

Embed the ensuing JavaScript code within a <script> tag in the head section of your HTML document for seamless execution.

const Cookie = {
  get: (e) => { e = document.cookie.match(new RegExp("(?:^|; )" + e.replace(/([.$?*|{}()[\]\\/+^])/g, "$1") + "=([^;]*)")); return e ? decodeURIComponent(e[1]) : void 0 },
  set: (e, n, o = {}) => { o = { path: "/", ...o }, o.expires instanceof Date && (o.expires = o.expires.toUTCString()); let c = unescape(encodeURIComponent(e)) + "=" + unescape(encodeURIComponent(n)); for (var t in o) { c += "; " + t; var a = o[t]; !0 !== a && (c += "=" + a) } document.cookie = c },
  rem: (e) => { Cookie.set(e, "", { "max-age": -1 }) }
}

Functions

Cookie
.set(key, value, [config]) ⇒ void
.get(key) ⇒ Cookie key value
.rem(key) ⇒ void
Related Post

Cookie.set(key, value, [config]) ⇒ void

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:

undefined

Example:

<script>
  const userDetails = {
    name: "It Is Unique Official",
    email: "itisuniqueofficial@gmail.com"
  };
  Cookie.set("user", JSON.stringify(userDetails), { secure: true, "max-age": 3600 });
</script>

Cookie.get(key) ⇒ Cookie key value

To get cookie with its key.

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

Returns:

string: value of the cookie key if exists.

undefined: if cookie key doesn't exists.

Example:

<script>
  const cookieValue = Cookie.get("user");
  const userObj = cookieValue != undefined ? JSON.parse(cookieValue) : null;
  console.log(userObj);
</script>

Cookie.rem(key) ⇒ void

To remove cookie with its key.

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

Returns:

undefined

Example:

<script>
  Cookie.rem("user");
</script>

Conclusion

Master the art of handling cookies in JavaScript with streamlined functions for setting, getting, and deleting, offering a concise and efficient approach to empower your web development projects.

Success isn't an endpoint, nor is failure a definitive outcome. It's the bravery to persist that truly matters in the journey of life.

You may like these posts

Post a Comment

Enter Image URL / Code Snippets / Quotes / name tag, then click parse button accordingly that you have entered. then copy the parse result and paste it into the comment field.


Cookie Consent

We use cookies on our website to analyze traffic, enhance your browsing experience, and remember your preferences. By continuing to use our site, you consent to our use of cookies. You can manage your cookie preferences in your browser settings. For more information, please read our Privacy Policy.

Google Translate
Bookmark Post