Last updated: Mar 7, 2024
Reading time·6 min
To check if a cookie exists using JavaScript:
document.cookie
property to get the value of the cookie associated
with the document.Here is the HTML for the example.
<!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.
/** * 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; }
If you get confused about the value of the currently set cookie, console.log()
the document.cookie
property.
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:
Name | Description |
---|---|
name | The name of the cookie |
value | The value of the cookie |
days | The 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.
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.
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.
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 the 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.
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:
getCookie()
method.null
, then the 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.
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 the 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.
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.
<!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.
/** * 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 = ''; });
The removeCookie
function takes the name of the cookie you want to remove as a
parameter and removes the cookie.
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.
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:
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.
You can learn more about the related topics by checking out the following tutorials: