Tutorial

What Are Cookies & How to Work With Them Using JavaScript

Published on March 19, 2020
author

Jack Misteli

What Are Cookies & How to Work With Them Using JavaScript

🧁 🧁 🧁 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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Jack Misteli

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

I feel that framing expires and max-age as an option of one or the other is incorrect, the best option is to use both. Modern browsers only use expires if max-age is absent, so expires is a good fallback for older browsers.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.