Set and Get cookies using JavaScript

How to Set and Get Cookies using JavaScript?

Using the JavaScript document.cookie property, you can create, read, and delete cookies.

Creating cookies in Javascript is very easy, Just assign an information to the document.cookie property and the information should be in key value pairs like – key=value.

In the following example, name=Akash Sharma is a data or information in the form of key value pair where name is key and value is Akash Sharma.

document.cookie = "name=Akash Sharma";
View Cookies on Browser Dev Tools

There are two ways to set the expiry of a cookieexpires and max-age

  • First, set the cookie information – "name=Akash Sharma;" Here you can see that we have added a semicolon (;) at the end of the information.
  • After that define the expiry with the help of the expires key or max-age key like – "name=Akash Sharma; expires=expiry" or "name=Akash Sharma; max-age=expiry"
//expiry time in minutes
let expiry = 1; //after 1 minute
let now = new Date();
now.setMinutes(now.getMinutes() + expiry);
expiry = now.toUTCString();

// This cookie will self-destruct after a minute.
document.cookie = `name=Akash Sharma; expires=${expiry}`;
//expiry time in Seconds
let expiry = 30; // in seconds

// This cookie will self-destruct after 30 seconds.
document.cookie = `name=Akash Sharma; max-age=${expiry}`;

The Domain and Path attributes define the scope of a cookie, which means where the cookie can be accessed.

For example, if you set domain=devbabu.com, the cookie can only be accessed from this domain and its subdomains like – blog.devbabu.com.

But, if you set it to a subdomain domain=blog.devbabu.com, the cookie can only be accessed from the subdomain.

document.cookie = "name=Akash Sharma; domain=devbabu.com";

// OR with expiry
let expiry = 30; // in seconds
document.cookie = `name=Akash Sharma; max-age=${expiry}; domain=devbabu.com`;

Path defines the scope of the URL path –

For example, if you set path=/posts, then the cookie can be accessed from /posts and its child path like – /posts/hello, /posts/hello/21, etc. But you can’t access from this/blog, /page/about, etc.

If you do not provide a path, the default path will be the current location.

let expiry = 30; // in seconds
document.cookie = `name=Akash Sharma; max-age=${expiry}; domain=devbabu.com; path=/blog`;

Cookie Secure attribute –

When you define the secure attribute, the cookie will only be transmitted over secure protocols such as https (except on localhost).

document.cookie = "name=Akash Sharma; secure";

The document.cookie property is used to set cookies and also to get cookies

document.cookie = "name=Akash Sharma;";
document.cookie = "age=24;";
document.cookie = "[email protected];";

The document.cookie property also gives you all the cookies

console.log(document.cookie);
show cookies on browser console

Here is the JavaScript code that gives you a specific cookie by key of the cookie.

function getCookie(key) {
    const data = document.cookie.split(";");
    for (const i in data) {
        const item = data[i].split("=");
        if (item[0].trim() === key) {
            return item[1] || false;
        }
    }
    return false;
}

const name = getCookie("name");
const email = getCookie("email");

console.log(name);
console.log(email);
Get specific cookie by name or key

To delete a cookie, Just specify the cookie name without value and set the expires parameter to a previous date or max-age=0.

document.cookie = "name=; max-age=0";
//OR
document.cookie = "name=; expires=Tue, 21 Jul 1998 00:00:00 UTC";