Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to test if a JavaScript cookie has expired?
To test if a JavaScript cookie has expired, you need to check if the cookie exists or returns null. When a cookie expires, the browser automatically removes it, so attempting to access it will return null or undefined.
Using document.cookie (Vanilla JavaScript)
The most straightforward approach is to create a helper function that checks if a cookie exists:
function getCookie(name) {
const cookies = document.cookie.split(';');
for (let cookie of cookies) {
const [cookieName, cookieValue] = cookie.trim().split('=');
if (cookieName === name) {
return decodeURIComponent(cookieValue);
}
}
return null;
}
function isCookieExpired(cookieName) {
return getCookie(cookieName) === null;
}
// Test the cookie
if (!isCookieExpired('myCookie')) {
console.log('Cookie exists and is valid');
} else {
console.log('Cookie has expired or does not exist');
}
Using jQuery Cookie Plugin
If you're using the jQuery Cookie plugin, you can check cookie expiration more simply:
if ($.cookie('myCookie') !== null && $.cookie('myCookie') !== undefined) {
// Cookie exists and is valid
console.log('Cookie is active');
} else {
// Cookie has expired or doesn't exist
console.log('Cookie expired');
}
One-Line Conditional Check
You can also use a ternary operator for a concise check:
// Using vanilla JavaScript
const cookieStatus = getCookie('myCookie') ? 'Cookie active' : 'Cookie expired';
// Using jQuery Cookie plugin
const checkCookie = $.cookie('myCookie') ? 'Cookie exists' : 'Cookie expired';
console.log(checkCookie);
Complete Example with Cookie Creation
// Set a cookie that expires in 1 minute for testing
document.cookie = "testCookie=hello; max-age=60; path=/";
function getCookie(name) {
const cookies = document.cookie.split(';');
for (let cookie of cookies) {
const [cookieName, cookieValue] = cookie.trim().split('=');
if (cookieName === name) {
return decodeURIComponent(cookieValue);
}
}
return null;
}
// Check immediately
console.log('Cookie value:', getCookie('testCookie'));
console.log('Is expired?', getCookie('testCookie') === null);
Cookie value: hello Is expired? false
Key Points
- Expired cookies are automatically removed by the browser
- Checking for null/undefined indicates expiration
- Always handle both null and undefined cases for cross-browser compatibility
- The jQuery Cookie plugin simplifies cookie operations but requires the library
Conclusion
Testing cookie expiration involves checking if the cookie returns null or undefined. Use vanilla JavaScript's document.cookie for lightweight solutions, or jQuery Cookie plugin for simpler syntax when already using jQuery.
Advertisements
