May 22, 2016
Here we are: my first installment for the #BlogBuddies blog with my buddy Loren! My goal for this series, (as outlined here), is to share what I'm learning on a weekly basis with others--be it lessons in teamwork, new workflow techniques, or fun little hacks--and to have a record of my progress. This week, I worked with cookies for the first time.
So what's the big deal?
How do they work?
That's all the current page's cookies! (Yes, I'm using Google Analytics. ¯\_(ツ)_/¯) It's just as easy to set a cookie, too:
document.cookie = "maxscookie=12345"
A cookie is a key-value pair, so you could use them to store a myriad of things, like a user's id number, temporary values that don't need to interact with the server, or fun easter eggs for observant individuals. Now, if you check your browser's content storage settings, you'll see the following:
Hey, I didn't set all those values! That's right, all those are default values and many of them are configurable: 1
pathrefers to the associated path (or URL) where the cookie is active. The default is
/, which means the cookie will apply to all pages under the given domain.
domainis the domain where the cookie will be active. In this case, it's maximumtiu.com, as it defaults to the host of the current page. If you specify a domain, all its subdomains will be included.
expirestakes a UTC date-time string for the desired cookie expiration time. A quick way to calculate the expiration string for a week from now would be:
miliseconds = (1000 * 60 * 60 * 24 * 7) d = new Date() d.setTime(d.getTime() + miliseconds) d.toUTCString()
Which would return:
"Sun, 05 Jun 2016 16:49:09 GMT"
And now, here are some options that aren't listed in the above image, but are available for configuration:
secureallows you to specify that cookie only be active over secure https connections.
max-ageis a value in seconds that refers to the maximum lifetime your cookie should have.
Okay, that's all pretty cool.
Right? And if I wanted to set my cookie to expire in one week and be applicable across all maximumtiu.com subdomains (like iam.maximumtiu.com), it'd look like this:
document.cookie = "maxscookie=12345;domain=.maximumtiu.com;expires=Sun, 05 Jun 2016 16:49:09 GMT"
So now the browser shows us:
Yep! That's exactly what I asked for!
So it turns out that cookies aren't nearly as difficult to use as I thought; they're actually pretty straightforward. I look forward to using them more in my projects and hope you do too!
1. “Document.cookie” , https://developer.mozilla.org/en-US/docs/Web/API/document/cookie