How to check if a Cookie exists using JavaScript

avatar
Borislav Hadzhiev

Last updated: May 3, 2023
5 min

banner

# How to check if a Cookie exists using JavaScript

To check if a cookie exists using JavaScript:

  1. Use the document.cookie property to get the value of the cookie associated with the document.
  2. Parse the value and check if the specified cookie exists.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">bobbyhadz.com</div> <h2>Set a cookie</h2> <!-- Code for setting a cookie --> <input id="cookie-name" /> <input id="cookie-value" /> <button id="set-cookie-btn">Set cookie</button> <br /> <br /> <br /> <h2>Check if a cookie exists</h2> <!-- Code for checking if a cookie exists --> <input id="check-cookie-exists" /> <button id="check-cookie-btn"> Check if the Cookie exists </button> <script src="index.js"></script> </body> </html>

The HTML contains 3 input fields.

The first 2 input fields are used to set a cookie by specifying the cookie's name and value.

The third input field is used to check if a given cookie exists.

Here is the related index.js file.

index.js
/** * Code for setting a cookie */ function setCookie(name, value, days = 7) { let expires = ''; if (days) { const date = new Date(); date.setDate(date.getDate() + days); expires = '; expires=' + date.toUTCString(); } document.cookie = name + '=' + (encodeURIComponent(value) || '') + expires + '; path=/'; } const setCookieBtn = document.getElementById('set-cookie-btn'); const cookieNameInput = document.getElementById('cookie-name'); const cookieValueInput = document.getElementById('cookie-value'); setCookieBtn.addEventListener('click', () => { setCookie(cookieNameInput.value, cookieValueInput.value); cookieNameInput.value = ''; cookieValueInput.value = ''; }); /** * ------------------------------------------------- */ /** * Code for checking if a cookie exists */ const checkCookieBtn = document.getElementById( 'check-cookie-btn', ); const cookieExistsInput = document.getElementById( 'check-cookie-exists', ); checkCookieBtn.addEventListener('click', () => { const cookieValue = getCookie(cookieExistsInput.value); if (cookieValue) { console.log('✅ The cookie exists: ', cookieValue); } else { console.log('⛔️ The cookie does not exist'); } }); function getCookie(name) { const nameEquals = name + '='; const cookieArray = document.cookie.split(';'); for (cookie of cookieArray) { while (cookie.charAt(0) == ' ') { cookie = cookie.slice(1, cookie.length); } if (cookie.indexOf(nameEquals) == 0) return decodeURIComponent( cookie.slice(nameEquals.length, cookie.length), ); } return null; }

check if cookie exists

If you get confused about the value of the currently set cookie, console.log() the document.cookie property.

index.js
console.log(document.cookie); const allCookies = document.cookie; console.log(allCookies);

The document.cookie property lets you read and write cookies associated with the document.

The JavaScript code sample is a bit long but most of the code is used to make the demo work.

The setCookie function takes 3 parameters:

NameDescription
nameThe name of the cookie
valueThe value of the cookie
daysThe duration in days for which the cookie should be set

The function sets the cookie on the document object.

The default value for the days parameter is 7.

If you only call the function with a name and a value, then the cookie is set to expire in 7 days.

index.js
function setCookie(name, value, days = 7) { let expires = ''; if (days) { const date = new Date(); date.setDate(date.getDate() + days); expires = '; expires=' + date.toUTCString(); } document.cookie = name + '=' + (encodeURIComponent(value) || '') + expires + '; path=/'; }

We also used the encodeURIComponent function to encode the cookie value.

This helps us ensure the cookie value is stored properly even if it contains special characters such as semicolons ;.

The next part of the code sets a click event listener on the button element.

index.js
const setCookieBtn = document.getElementById('set-cookie-btn'); const cookieNameInput = document.getElementById('cookie-name'); const cookieValueInput = document.getElementById('cookie-value'); setCookieBtn.addEventListener('click', () => { setCookie(cookieNameInput.value, cookieValueInput.value); cookieNameInput.value = ''; cookieValueInput.value = ''; });

Every time the button is clicked, we call the setCookie function with the name and value from the input fields.

The last step is to clear the values of the input fields by setting them to empty strings.

The next key part of the code is defining the getCookie() function.

index.js
function getCookie(name) { const nameEquals = name + '='; const cookieArray = document.cookie.split(';'); for (cookie of cookieArray) { while (cookie.charAt(0) == ' ') { cookie = cookie.slice(1, cookie.length); } if (cookie.indexOf(nameEquals) == 0) return decodeURIComponent( cookie.slice(nameEquals.length, cookie.length), ); } return null; }

The getCookie function takes a name of a cookie and returns the corresponding value or null if the cookie doesn't exist.

We also used the decodeURIComponent method to decode the cookie value that we previously encoded using encodeURIComponent.

The last part of the code sample adds a click event listener to the second button.

index.js
const checkCookieBtn = document.getElementById( 'check-cookie-btn', ); const cookieExistsInput = document.getElementById( 'check-cookie-exists', ); checkCookieBtn.addEventListener('click', () => { const cookieValue = getCookie(cookieExistsInput.value); if (cookieValue) { console.log('✅ The cookie exists: ', cookieValue); } else { console.log('⛔️ The cookie does not exist'); } });

Inside the event handler function:

  1. We pass the value of the input field to the getCookie() method.
  2. If the function didn't return null, then the cookie exists.
  3. Otherwise, the cookie doesn't exist.

check if cookie exists

In some cases, you might not need to get the value of the cookie.

If you only need to check if the cookie exists, use the following function.

index.js
const checkCookieBtn = document.getElementById( 'check-cookie-btn', ); const cookieExistsInput = document.getElementById( 'check-cookie-exists', ); checkCookieBtn.addEventListener('click', () => { if (cookieExists(cookieExistsInput.value)) { console.log('✅ The cookie exists.'); } else { console.log('⛔️ The cookie does not exist'); } }); /** * Only checking if the cookie exists */ function cookieExists(name) { return document.cookie .split(';') .some(item => item.trim().startsWith(`${name}=`)); }

The cookieExists function takes a name of a cookie and returns true if the cookie exists and false otherwise.

The function uses the String.split method to split the cookie string on each semicolon.

The Array.some method is used to iterate over the array of substrings.

On each iteration, we trim the leading and trailing whitespace.

The last step is to use the String.startswith method to check if each substring starts with the given name followed by an equal sign.

only checking if cookie exists

# Adding a Remove cookie functionality

In some cases, you might also have to add a "remove cookie functionality" to test whether your function that checks if a cookie exists works.

Here is the updated HTML for the code sample.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">bobbyhadz.com</div> <h2>Set a cookie</h2> <!-- Code for setting a cookie --> <input id="cookie-name" /> <input id="cookie-value" /> <button id="set-cookie-btn">Set cookie</button> <br /> <br /> <br /> <h2>Check if a cookie exists</h2> <!-- Code for checking if a cookie exists --> <input id="check-cookie-exists" /> <button id="check-cookie-btn"> Check if the Cookie exists </button> <h2>Remove cookie</h2> <input id="cookie-to-remove" /> <button id="remove-cookie-btn">Remove cookie</button> <br /> <br /> <br /> <script src="index.js"></script> </body> </html>

The last input field takes the name of a cookie you want to remove.

Here is the related JavaScript code.

index.js
/** * Code for setting a cookie */ function setCookie(name, value, days = 7) { let expires = ''; if (days) { const date = new Date(); date.setDate(date.getDate() + days); expires = '; expires=' + date.toUTCString(); } document.cookie = name + '=' + (encodeURIComponent(value) || '') + expires + '; path=/'; } const setCookieBtn = document.getElementById('set-cookie-btn'); const cookieNameInput = document.getElementById('cookie-name'); const cookieValueInput = document.getElementById('cookie-value'); setCookieBtn.addEventListener('click', () => { setCookie(cookieNameInput.value, cookieValueInput.value); cookieNameInput.value = ''; cookieValueInput.value = ''; }); /** * ------------------------------------------------- */ /** * Code for checking if a cookie exists */ const checkCookieBtn = document.getElementById( 'check-cookie-btn', ); const cookieExistsInput = document.getElementById( 'check-cookie-exists', ); checkCookieBtn.addEventListener('click', () => { if (cookieExists(cookieExistsInput.value)) { console.log('✅ The cookie exists.'); } else { console.log('⛔️ The cookie does not exist'); } }); function getCookie(name) { const nameEquals = name + '='; const cookieArray = document.cookie.split(';'); for (cookie of cookieArray) { while (cookie.charAt(0) == ' ') { cookie = cookie.slice(1, cookie.length); } if (cookie.indexOf(nameEquals) == 0) return decodeURIComponent( cookie.slice(nameEquals.length, cookie.length), ); } return null; } function cookieExists(name) { return document.cookie .split(';') .some(item => item.trim().startsWith(`${name}=`)); } /** * Code used to remove a specific cookie */ function removeCookie(name) { document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'; } const removeCookieBtn = document.getElementById( 'remove-cookie-btn', ); const removeCookieInput = document.getElementById( 'cookie-to-remove', ); removeCookieBtn.addEventListener('click', () => { removeCookie(removeCookieInput.value); console.log(`Cookie ${removeCookieInput.value} removed`); removeCookieInput.value = ''; });

cookie does not exist after removing it

The removeCookie function takes the name of the cookie you want to remove as a parameter and removes the cookie.

index.js
function removeCookie(name) { document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'; }

The function simply sets the expiration date of the cookie in the past.

THe last part of the code sample is to add a click event listener to the last button element.

index.js
const removeCookieBtn = document.getElementById( 'remove-cookie-btn', ); const removeCookieInput = document.getElementById( 'cookie-to-remove', ); removeCookieBtn.addEventListener('click', () => { removeCookie(removeCookieInput.value); console.log(`Cookie ${removeCookieInput.value} removed`); removeCookieInput.value = ''; });

The event handler function:

  1. Takes the name of the cookie to be removed from the input field.
  2. Calls the removeCookie function with the name of the cookie to be removed.

If you check if the cookie exists after removing it, false is returned.

I've also written an article on how to check if a key exists in localStorage.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.