The site is under maintenance, posts are being updated. Report!

How to Set, Get and Delete Cookies using Vanilla JavaScript

Please wait 0 seconds...
Scroll Down and click on Go to Link for destination
Congrats! Link is Generated

In this tutorial, we are going to learn how to SET, GET and DELETE Cookies using Vanilla JavaScript. We will create functions to reduce our codes and make it easy to do these operations. It will help you in your JavaScript projects.

Table of Contents

Getting Started

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


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

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 }) }


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

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




  const userDetails = {
    name: "Deo Kumar",
    email: ""
  Cookie.set("user", JSON.stringify(userDetails), { secure: true, "max-age": 3600 });

Cookie.get(key) ⇒ Cookie key value

To get cookie with its key.

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


string: value of the cookie key if exists.

undefined: if cookie key doesn't exists.


  const cookieValue = Cookie.get("user");
  const userObj = cookieValue != undefined ? JSON.parse(cookieValue) : null;

Cookie.rem(key) ⇒ void

To remove cookie with its key.

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




Related Topics

About the Author

Hey there! My name is Deo Kumar aka Dev, a professional Web Designer, Graphic Designer, UI / UX Designer as well as Content Creator from Bihar, India. I love to Code and create interesting things while playing with it.

Buy me a Coffee


Post a Comment

To avoid SPAM, all comments will be moderated before being displayed.
Don't share any personal or sensitive information.
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.