Web Cookies for Everyone

Written by omergoldberg | Published 2017/09/10
Tech Story Tags: javascript | web-development | coding | web-cookies-for-everyone | web-cookies

TLDRvia the TL;DR App

Web jargon! It’s hard to keep up at times. The worst is when terms that are supposedly simple are thrown around, and you just sit there at the meeting like this.

Doctor Who like whaaaat?

Web cookies is definitely one of those terms. The purpose of this post is to explain web cookies in a simple manner. We will focus on the core concept, so that you can later apply this in any project, regardless of which framework or library you may choose. At the end of this post you should be able to differentiate between an actual cookie and a web cookie pretty confidently ;)

Cookies?!? What do you mean

A web cookie is a small bit of text that is sent to your browser by a server. A cookies purpose is to carry bits of useful information about your interaction with the website that sets them. The browser may store it and send it back with the next request to the same server. This way, the server can distinguish whether two requests came from the same browser.

Cookies are specific to a web browser. Therefore, if you use a different computer, open a different browser or delete your cookies, the website will treat you as if you have arrived for the first time (and a new cookie will be set).

What are cookies used for?

Cookies can be used for a variety of reasons:

  1. Remember your settings on a website. Like whether you read the oldest or newest comments first; the volume on the video player, how long you hovered over a specific post, your shopping carts state, game scores and more.

2. To understand how you and other users are using the site. For example, to tell what the most popular news story of the day is. Or to tell how badly you want an airline ticket. Evilness!

3. Authentication services like logging in to a service or to make sure you’re logged in securely (these cookies may contain information such as your email address and your name — the information you gave when you signed up. The website you signed up to is the only site that can access this information.)

Cookies in Practice

Let’s start seeing things in action by setting our first cookie and examining it in the browser.

It’s important to note that the Chrome browser won’t store cookies set from local web pages. Therefore we’ll set up a simple node server that will allow us to work under the localhost domain. To get this working locally clone the repo from this github repo, and run npm install. Then navigate to project directory and run

Call it maaagic

Simple Express Server

Great! Now that we have our local dev environment setup and we can start playing with cookies.

Let’s work towards something that resembles a real life scenario. Say we want to create a site that upon a users first visit prompts him/her for his name. When the user enters his name, we’d like to save it (via a web cookie), so that on the user’s next visit we can give them a warm welcome :)

Here’s the basic markup we’ll be using for this experiment:

Let’s start off with setting and getting a cookie in it’s most basic form.

Now let’s restart the server so we can see the new changes. Voila!

Our snazzy alert message

Viewing cookies via Chrome Developer tools

So when we show our document’s cookies we get something almost exactly identical to what we set. What’s the subtle difference? See that semi colon between both key-value pairs? Hmm.. we didn’t explicitly set that. So this is an example of how the browser differentiates between different cookies. By adding a semi colon to it!

Methods for fetching, setting and checking for cookies

Alright, alright. So at this point we’ve seen that cookies are built right into the global document object. We can set them by passing a string key-value pair to document. cookie. We can view all of our current web pages cookies by accessing document.cookie. Let’s try and build a more scalable approach to getting and setting cookies by creating some Javascript methods.

Like we saw in our mini example above, cookie are saved as a string and separated by semicolons. Therefore we are going to use some built in Javascript string methods to fetch our cookie.

fetchCookie()

Our first method will check our cookies for a cookie with the username key and returns it if it exists.

getUserData()

This method will check the browser for a cookie with a “username” key. If it exists we will welcome the user. Otherwise we will prompt him/her for their name.

setCookie()

Our setter method will accept 3 params. A key, a value, and an expiration date.

All Together Now

The Final result

Wrapping up

Cookies are a big part of web development and are something we use everyday as consumers. Hopefully knowing how this works on the development side gives a little more insight into the inner workings of some of your favorite websites.

In case you want a big picture view, here is the full code available on our GitHub account.

If you enjoyed this don’t forget to clap! 👏 👏 👏

Feel free to follow me on Instagram, LinkedIn or Github where I regularly post entrepreneurship and tech related content.

This post was created using the amazing summarization tool Mindflow.ai! Sign up now to join the alpha release!

This post was originally published on CodingStartups. We’re building a community of builders with an emphasis on teaching skills that help you get stuff doooone. Subscribe!

Until next time ✌️


Published by HackerNoon on 2017/09/10