Week 14: demo

Cookies



Cookies are another method of being able to store variables within the browser. These are incredibly commonly used, and likely the oldest method to store local variables on the users computer. There's also a lot of international laws established about how cookies should or shouldn't be used and the options that web publishers should be providing to their users to opt-in or out of using cookies.

Cookies are very simple to create, as they are not object oriented, but more like setting a single string of neatly formatted key/value pairs.

document.cookie = "username=aaronsie";

The unique thing about cookies is that the developer can establish an expiration date when setting one:

document.cookie = "username=aaronsie; expires=Mon, 1 May 2023 12:00:00 UTC";

We can set additional cookies by simply assigning them to document.cookie again. The previous cookies won't be overwritten.

document.cookie = "bgcolor=red; expires=Mon, 1 May 2023 12:00:00 UTC";

When we attempt to read from document.cookie it will only return the key/value pairs of cookies that were set and not their experiation information or path.

var c = document.cookie;
console.log(c);
// the output will be "username=aaronsie;bgcolor=red"

Of course we would then need to create a function to separate these key/value pairs and form a tidy object that we can access. Or, we can simply modernize our approach and look towards the js-cookie JavaScript library, which will allow us to set and retrieve cookies pretty much exactly like how we work with localStorage and sessionStorage.

Resources