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 functions to reduce our codes and make it easy to do these operations. It will help you in your JavaScript projects.

Cookie Javascript

Getting Started

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

Table of Contents


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

 * cookie by Fineshop Design
 * License: MIT
const cookie=Object.defineProperties({},{get:{value(a){if("string"==typeof a){const b=this.cookie.match(new RegExp(`(?:^|; )${a.replace(/([.$?*|{}()[\]\\/+^])/g,"$1")}=([^;]*)`));if(b&&"string"==typeof b[1])return decodeURIComponent(b[1])}return null}},getAll:{value(){const a={},b=this.cookie.split("; ");for(let c=0;c<b.length;c+=1){const[d,e]=b[c].split("=");d&&(a[d]=decodeURIComponent(e||""))}return a}},has:{value(a){return null!==this.get(a)}},set:{value(a,b,c){const d={path:"/",...c};let e=`${encodeURIComponent(a)}=${void 0===b?"":encodeURIComponent(b)}`;return Object.keys(d).forEach(a=>{const b=a,c=d[b];let f,g;"expires"===b?(f=b,g=c instanceof Date?c.toUTCString():c):"maxAge"===b?(f="max-age",g=c):"sameSite"===b?(f="samesite",g="none"===c||c):(f=b,g=c),e+=`; ${f}`;const h=("boolean"!=typeof g||!0!==g)&&void 0!==c;h&&(e+=`=${g}`)}),this.cookie=e,e}},delete:{value(a){this.set(a,"",{maxAge:-1})}},clear:{value(){Object.keys(this.getAll()).forEach(a=>this.delete(a))}},size:{get(){return Object.keys(this.getAll()).length}},cookie:{get(){try{return document.cookie}catch(a){return""}},set(a){try{document.cookie=a}catch(a){}}}});


.get(key) ⇒ string | null
.getAll() ⇒ Record<string, string>
.has(key) ⇒ boolean
.set(key, value, [config]) ⇒ string
.delete(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




  const userDetails = {
    name: "Deo Kumar",
    email: ""
  // Cookie will expire after 1 hour
  cookie.set("user", JSON.stringify(userDetails), { secure: true, "max-age": 3600 });

cookie.get(key) ⇒ string

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.

null: if cookie key doesn't exists.


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

Cookie.delete(key) ⇒ void

To delete cookie with its key.

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




Related Topics

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

About the Author

~ Hello World!

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.