What Are Cookies & How to Work With Them Using JavaScript

Jack Misteli

🧁 🧁 🧁 not quite… 🍪🍪🍪 Better! The cookie 🍪 is one of the web’s favorite emoji and it’s also one of web’s most important technology.

Let’s take a look at what it’s all about, shall we?

The Basics of Browser Cookies

Browser cookies were introduced to the web in order to keep persistent information about the user. The first use case was to check if a user had already visited Netscape’s website.

Cookies are strings that have a name field, a value field and additional optional attributes. The values are strings and you can store whatever you think is best for your application. Google Analytics’ _ga is probably one of || the most common cookie out there, it usually looks like this:

  • Name: _ga
  • Value: GA1.3.210706468.1583989741
  • Domain: .example.com
  • Path: /
  • Expires / Max-Age: 2022-03-12T05:12:53.000Z

Cookies can store up to 4096 bytes of data (this includes name, value, domain, expiry date and whatever else you can fit in there). You can add a limited number of cookies per domain which changes depending on your browser.

How Are Cookies Created

There are two main ways to create cookies:

  • With HTTP you can send Set-Cookie in your HTTP response header. Depending on the technologies you are using for your web server; you can use different tools and libraries to manage cookie headers. These tools should create HTTP responses which will roughly look like this:
HTTP/2.0 200 OK
Content-type: text/html
Set-Cookie: alligator_name=barry
Set-Cookie: tasty_cookie=strawberry
... More http Content

You can add information to your cookies like an expiration date, and security features such as the Secure directive and the HttpOnly flag.

Set-Cookie: cookie_name=cookie_value; Expires=Wed, 17 Sep 2021 07:00:00 GMT; Secure; HttpOnly

The HttpOnly flag means that the cookies cannot be read or modified by the browser. And Secure means that the cookie can only be transferred over HTTPS. These are really important to protect your application.

  • With Javascript it’s a bit trickier to manage Cookies. We have one interface, document.cookie, which stores our cookies and can be reassigned. For example on a site that has Google Analytics installed, and in the developer console, we can do:
console.log(document.cookie)
// logs something like "_ga=GA1.3.210706468.1583989741; _gid=GA1.3.1734708005.1583989741"

// This equal sign does not work as you expect
document.cookie = "alligator=alligator_cookie_content;"
console.log(document.cookie)
// logs "_ga=GA1.3.210706468.1583989741; _gid=GA1.3.1734708005.1583989741; alligator=alligator_cookie_content"
// Notice that the previous piece of code appends the new cookie we created

// A rough implementation of a cookie interface could look like this:
const createCookie = (name, value) => document.cookie = name + '=' + value + ';'
// For a real update we would first check if the cookie exists
const updateCookie = (name, value) => document.cookie = name + '=' + value + ';'
const deleteCookie = (name) => document.cookie = name + '=; Max-Age=-1;';  

Types of Cookies

Session cookies

Session cookies often refer to a type of cookie that exist until the browser is closed. To setup a session cookie you just need to NOT specify any expiration date.

For example, you can store your user’s name in the cookie. Whoever has access to the cookie will have access to the user’s name. Since it is in the cookie we don’t need to add it to our requests.

Session cookies is a confusing expression. Session cookies also refer to cookies which you use to manage sessions. Cookies that are deleted when the browser is closed are not the only cookies you can use for session management.

Persistent cookies are not deleted by the browser when the user closes it. These cookies have an expiration date that you can set in your server. You can set a cookie to expire in a day or ten years.

We can differentiate cookies that are on the same domain from cookies which come from third-party providers. The example we gave earlier with Google Analytics is an example of a third-party cookie. Third-party cookies can be used to track user activities. To set a third-party cookie, you have to set ';domain=thirdpartydomain.com'.

Cookies are usually temporary, so you might want to set a precise expiry date. You have two strategies:

  • Use Expires and set a fixed expiration date. The date uses the HTTP date formate: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT. So for example if we want our cookie to expire September 17 2020 we can do:
const jacksBirthday = new Date(2020, 8, 17);
document.cookie = 'jacksage=27; expires =' + jacksBirthday.toUTCString() + ';';
  • Using ‘Max-Age’ is not supported by every browser. But it’s the soundest solution. It forces the cookie to expire a certain amount of time (in seconds) after the client receives it:
// Expires after one day
const oneDayToSeconds = 24 * 60 * 60;
document.cookie =  'daily_cookie=session_identifierXYZ; max-age = ' + oneDayToSeconds + ';';

🍪 That's about it! I hope you now have a better idea of how to use cookies on the client side with JavaScript. If you have any question ask us on Twitter. Next time, we will see how to manage sessions with cookies and Express.js.

  Tweet It

🕵 Search Results

🔎 Searching...