JavaScript

How do I Check if a Cookie Exists?

Cookies maintain a small amount of data (about 4KB) on the user’s computer by a web browser and are used to store information about a user, including login or sign-in credentials and other forms of data. It can be utilized to optimize a user’s experience on a website. Majorly browsers store three kinds of cookies. “Session cookies” that are deleted when the browser is closed, “First-party cookies” that are created by websites, and the “Third-party cookies” created by the third party on your website.

This article will demonstrate the method to check whether a cookie exists using JavaScript.

How to Check/Verify if a Cookie Exists in JavaScript?

To check if the cookie exists in the browser or not, use the “checkCookie()” function. In the defined function, check whether the cookie is null using the “document.cookie” attribute. If it is null, it means the cookie does not exist; else cookie exists in the browser.

Example

Create two buttons in an HTML file that will use to set and check the cookie on the browser on the button click:

<input type="button" class="button" value="SetCookie" onclick="setCookie()">

<input type="button" class="button" value="CheckCookie" onclick="checkCookie()">

Set the cookie using the “document.cookie” attribute with the “prompt()” method to get the input from the user:

function setCookie() {

var cookie = prompt("Please enter your name");

document.cookie = cookie;

alert("Cookie is created");

}

Now, define a function called “checkCookie()”. Check the condition such that if the value of “document.cookie” is not equal to the null (“”), the cookie exists. Otherwise, it doesn’t exist. Then, call the “setCookie()” to set the cookie on the browser:

functioncheckCookie() {
if (document.cookie != "") {
  alert("Cookie exist ");
  alert("Cookie is " + document.cookie);
 }
else {
  alert("Cookie not exist");
  setCookie();
 }
}

Output

The output indicates that firstly no cookie exists in the browser. Then, we clicked on the “setCookie” function to set the cookie and fetched its value.

Conclusion

To check if the cookie exists in the browser, use the “checkCookie()” function with the “document.cookie” attribute. In the function checkCookie(), first, check whether the cookie is null. If null, it means the cookie does not exist; else cookie exists in the browser. This article demonstrated the method to check whether a cookie exists or not.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.