Cookies are a convenient mechanism for saving state (e.g. user login, user preferences, settings, etc.) across multiple pageviews across multiple sessions. Cookies can be manipulated both on server-side and client-side. For a full breakdown on the topic, check out this excellent primer on cookies on MDN.
document.cookie
document.cookie
- Visit your favourite site (e.g. reddit.com)
- Open up your browser’s developer console (in Chrome use the shortcut ⌘ + option + J)
- Type in document.cookie and press the return key
- You will now see all the cookies associated with this domain
This is how you interpret the output of document.cookie :
- You are looking at all cookies associated with the domain concatenated into a single string.
- Each cookie is separated by the “;” character.
- Each cookie is a key-value pair separated by the “=” character. The key is on the left of the = character, and the value is on the right.
document.cookie
gives us our fundamental building block for managing cookies client-side. So how do we manipulate cookies? Read on!
A JavaScript library for managing cookies
I’ve put my code into a simple JavaScript library so I can reuse it in the future. Feel free to take a copy for your own purposes.
- The code is available here on GitHub.
- You can also see the code in action on this simple JavaScript and cookies demo.
Setting cookies
- Cookie name
- Cookie value
- Expiry date
- Path or scope – in the below code the path is set to “/“ so that the cookie is accessible across all pages on the site. You could modify this to only apply to a specific directory or set of directories.
So to set a cookie, we invoke the below code.
cookieHandler.setCookie = function (cookieName, cookieValue, nDays) { var d = new Date(); d.setTime(d.getTime() + (nDays*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";path=/"; } //Example: set a cookie that expires one year from now cookieHandler.setCookie('my_cookie', '12345', 365);
- The cookie is new – the new cookie details will be appended to document.cookies
- The cookie already exists – the cookie string will be replaced in document.cookies
Updating cookie values
Updating cookie values simply involves calling cookieHandler.setCookie()
with the original cookie name and a new value. The existing cookie will have its value replaced with the new value.
//Example: update value of 'my_cookie' to 67890 cookieHandler.setCookie('my_cookie', '67890', 365);
Reading cookie values
- Read the string representation of document.cookie. Remember, this returns a representation of all cookies.
- Split the string into its individual cookie components.
- Iterate through the individual cookies. For each cookie string:
- Split the cookie into its key-value pair.
- If the key matches the name of the cookie you are looking for, then return the value.
- If no cookies matches your search, return an empty string.
Thus to get the value of a cookie, we run the code below.
cookieHandler.getCookieValue = function (cookieName) { var name = cookieName + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i <ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ''; } //Example: get value of the 'my_cookie' cookie cookieHandler.getCookieValue('my_cookie');
Deleting cookies
The easiest way to delete a cookie is to set its value to an empty string and its expiry time to a time in the past. For added measure I set the expiry date to two years in the past.
cookieHandler.deleteCookie = function (cookieName) { cookieHandler.setCookie(cookieName,'',-730); } //Example: delete the 'my_cookie' cookie cookieHandler.deleteCookieI('my_cookie');