Vanilla JavaScript Cookies ๐ช
permalinkIn this tutorial, we'll be looking into working with browser cookies in Vanilla JavaScript. It's not the most widely used functionality, but great to keep track of small things like whether someone clicked a cookie bar.
We can set
, get
, change
and, delete
a cookies.
How to set a cookie permalink
To set a cookie in Vanilla JavaScript
, we use the document.cookie
property.
First, we must understand cookies are set as a key-value pair.
key = value
So, to set an HTTP cookie, you use the following:
document.cookie = 'username=Chris';
We can even set an expiry date:
document.cookie = 'username=Chris; expires=Sun, 01 Jan 2023 12:00:00 UTC';
Get cookies in Vanilla JS permalink
To get and read a specific cookie, we can use the following:
const username = document.cookie;
username = Chris;
second = bla;
This will return the complete cookie object, so we need to split it like so:
const username = getCookie('username');
console.log(username);
// Chris
function getCookie(name) {
// Add the = sign
name = name + '=';
// Get the decoded cookie
const decodedCookie = decodeURIComponent(document.cookie);
// Get all cookies, split on ; sign
const cookies = decodedCookie.split(';');
// Loop over the cookies
for (let i = 0; i < cookies.length; i++) {
// Define the single cookie, and remove whitespace
const cookie = cookies[i].trim();
// If this cookie has the name of what we are searching
if (cookie.indexOf(name) == 0) {
// Return everything after the cookies name
return cookie.substring(name.length, cookie.length);
}
}
}
How to change a cookie permalink
Sometimes we want to update a cookie. To do that, we first get the cookie and then set it again:
document.cookie = 'username=Nicole; expires=Sun, 01 Jan 2023 12:00:00 UTC';
JavaScript Deleting a browser cookie permalink
To delete a specific web cookie, we have to set its date to be passed:
document.cookie = 'username=; expires=Thu, 01 Jan 1970 00:00:00 UTC;';
View the demo code to try getting and setting cookies in JavaScript right on Codepen. permalink
See the Pen JavaScript get and set all cookies by Chris Bongers (@rebelchris) on CodePen.
Thank you for reading, and let's connect! permalink
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter