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
Cookie Javascript | Mas Rizky 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 by Mas Rizky 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){}}}});

Functions

cookie
.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

Returns:

string

Example:

<script>
  const userDetails = {
    name: "Rizky Kharisma",
    email: "email@masrizky.sch.id"
  };
  // Cookie will expire after 1 hour
  cookie.set("user", JSON.stringify(userDetails), { secure: true, "max-age": 3600 });
</script>

cookie.get(key) ⇒ string

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.

null: if cookie key doesn't exists.

Example:

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

cookie.delete(key) ⇒ void

To delete cookie with its key.

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

Returns:

undefined

Example:

<script>
  cookie.delete("user");
</script>

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

Related Posts

Copyright (c):
Masrizky.sch.id

Post a Comment

Popular Emoji: 😊😁😅🤣🤩🥰😘😜😔😥😪😭😱🤭😇🤲🙏👈👉👆👇👌👍❤🤦‍♂️❌✅⭐
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.