JavaScript - get / set / remove cookies (custom solution)
In this short article we would like to show how to get, set and remove cookies in JavaScript in web browser usiong custom light cookies manager implementation.
By default cookies usage with built-in web browser API is not intuitive. In practice we are able to wite own one cookies manager what is presented in this article.
The example presented in the article was created to store cookies in safe way - escaping dangerous characters with encodeURIComponent()
function, that can be changed to some other if it is needed.
The below manager provides API to:
- check if cookies are enabled
- get string, boolean, number and date value cookies
- set string, boolean, number and date value cookies,
- remove cookie,
- calculate expiration time from: seconds, minutes, hours and days.

Usage example:
xxxxxxxxxx
var expiration = Cookies.calculateExpirationDays(30); // cookies will expire after 30 days
Cookies.setStringCookie('user', 'john', expiration);
Cookies.setBooleanCookie('admin', true , expiration);
Cookies.setNumberCookie('age', 25, expiration);
Cookies.setDateCookie('created', new Date(), expiration);
var user = Cookies.getStringCookie('user');
var admin = Cookies.getBooleanCookie('admin');
var age = Cookies.getNumberCookie('age');
var created = Cookies.getDateCookie('created');
Full API:
|
|
|
|
|
|
|
Where:
expiration
,domain
andpath
are optional,calculatExpiration...
functions return time when cookie will expire.
xxxxxxxxxx
window.Cookies = new function() {
var self = this;
var cachedCookies = { };
var browserCookie = document.cookie;
if (browserCookie.length > 0) {
var parts = browserCookie.split('; ');
for (var i = 0; i < parts.length; ++i) {
var entry = parts[i];
var index = entry.indexOf('=');
var name = decodeURIComponent(entry.substr(0, index));
if (name in cachedCookies) {
continue;
}
var value = decodeURIComponent(entry.substr(index + 1));
setCachedCookie(name, value);
}
}
function setCachedCookie(name, value) {
cachedCookies[name] = value;
}
function removeCachedCookie(name) {
delete cachedCookies[name];
}
function setBrowserCookie(name, value, expiration, domain, path) {
var cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
if (expiration) {
cookie += ';expires=' + expiration.toUTCString();
}
if (domain) {
cookie += ';domain=' + encodeURI(domain);
}
if (path) {
cookie += ';path=' + encodeURI(path);
}
document.cookie = cookie;
}
function removeBrowserCookie(name) {
var expiration = this.calculateDays(-100);
document.cookie = encodeURIComponent(name) + ';expires=' + expiration.toUTCString();
}
// Cookies API
self.checkCookiesEnabled = function() {
return navigator.cookieEnabled;
};
self.removeCookieValue = function(name) {
removeCachedCookie(name);
removeBrowserCookie(name);
};
self.getStringCookie = function(name) {
return cachedCookies[name] || null;
};
self.setStringCookie = function(name, value, expiration, domain, path) {
setCachedCookie(name, value);
setBrowserCookie(name, value, expiration, domain, path);
};
self.getBooleanCookie = function(name) {
var string = self.getStringCookie(name);
if (string == null) {
return null;
}
return string == 'true' || string == '1';
};
self.setBooleanCookie = function(name, value, expiration, domain, path) {
var string = value.toString();
self.setStringCookie(name, string, expiration, domain, path);
};
self.getNumberCookie = function(name) {
var string = this.getStringCookie(name);
if (string == null) {
return null;
}
return parseFloat(string);
};
self.setNumberCookie = function(name, value, expiration, domain, path) {
var string = value.toString();
self.setStringCookie(name, string, expiration, domain, path);
};
self.getDateCookie = function(name) {
var number = self.getNumberCookie(name);
if (number == null) {
return null;
}
return new Date(number);
};
self.setDateCookie = function(name, value, expiration, domain, path) {
var number = value.getTime();
self.setNumberCookie(name, number, expiration, domain, path);
};
// Cookies Utils
self.calculateExpirationSeconds = function(value) {
var now = Date.now();
return new Date(now + 1000 * value);
};
self.calculateExpirationMinutes = function(value) {
var now = Date.now();
return new Date(now + 60000 * value); // 60 * 1000 = 60000
};
self.calculateExpirationHours = function(value) {
var now = Date.now();
return new Date(now + 3600000 * value); // 60 * 60 * 1000 = 3600000
};
self.calculateExpirationDays = function(value) {
var now = Date.now();
return new Date(now + 86400000 * value); // 24 * 60 * 60 * 1000 = 86400000
};
};
// Usage example:
console.log('Cookies are ' + (Cookies.checkCookiesEnabled() ? 'enabled' : 'disabled'));
if (Cookies.checkCookiesEnabled()) {
var expiration = Cookies.calculateExpirationSeconds(5); // cookies stored only 5s
// Cookies.calculateExpirationMinutes(minutes); // in minutes
// Cookies.calculateExpirationHours(hours); // in hours
// Cookies.calculateExpirationDays(days); // in days
Cookies.setStringCookie('user', 'john', expiration);
Cookies.setBooleanCookie('admin', true , expiration);
Cookies.setNumberCookie('age', 25, expiration);
Cookies.setDateCookie('created', new Date(), expiration);
var user = Cookies.getStringCookie('user');
var admin = Cookies.getBooleanCookie('admin');
var age = Cookies.getNumberCookie('age');
var created = Cookies.getDateCookie('created');
if (created) {
created = created.toISOString();
}
console.log('user: ' + user + '\n' +
'admin: ' + admin + '\n' +
'age: ' + age + '\n' +
'created: ' + created );
};