DEV Community

Cover image for Introduction to HTTP Cookies
Linda
Linda

Posted on

Introduction to HTTP Cookies

I heard the british use biscuits instead of cookies...weird.

Okay, let's focus.

What are Cookies

Cookies, more properly called HTTP cookies, are small bits of data stored as text files on a browser. Cookies associate bits of data to a specific user.

Cookies are mainly used for three purposes:

Session management

Logins, shopping carts, game scores, or anything else the server should remember.

Personalization

User preferences, themes, and other settings.

For example, a user's preferences such as language and preferred theme could be saved for future sessions.

Tracking

Recording and analyzing user behavior.

When a user visits a shopping website and searches for an item, the item gets saved in their browser history. Cookies can read browsing history so similar are shown to the user next time they visit.

Types of Cookies

Session cookies

Session cookies, also known as 'temporary cookies', help websites recognise users and the information provided when they navigate through a website. Session cookies only retain information about a user's activities for as long as they are on the website. Once the web browser is closed, the cookies are deleted.

Permanent cookies

Permanent cookies are also known as 'persistent cookies'. They remain in operation even after the web browser has closed. For example they can remember login details and passwords so web users don't need to re-enter them every time they use a site.

Third-party cookies

Third-party cookies are installed by third-parties with the aim of collecting certain information from web users to carry out research into, for example, behaviour, demographics or spending habits. They are commonly used by advertisers who want to ensure that products and services are marketed towards the right target audience.

Flash cookies

Flash cookies are also known as 'super cookies'. They are independent from the web browser. They are designed to be permanently stored on a user's computer. These types of cookies remain on a user's device even after all cookies have been deleted from their web browser.

Zombie cookies

Zombie cookies are a type of flash cookie that are automatically re-created after a user has deleted them. This means they are difficult to detect or manage. They are often used in online games to prevent users from cheating, but have also been used to install malicious software onto a user's device.

Secure Cookies

Only HTTPS websites can set secure cookies, i.e., cookies with encrypted data. Mostly, the checkout or payment pages of e-commerce websites have secure cookies to facilitate safer transactions. Similarly, online banking websites are required to use secure cookies for security reasons.

Creating Cookies with Vanilla JavaScript

NOTE: For the code below to work, your browser has to have local cookies support turned on.

JavaScript can create, read, and delete cookies with the document.cookie property.

With JavaScript, a cookie can be created like this:

document.cookie = "name=Linda Ojo";
Enter fullscreen mode Exit fullscreen mode

You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed:

document.cookie = "name=Linda Ojo; expires=Wed, 1 Oct 2022 12:00:00 UTC";
Enter fullscreen mode Exit fullscreen mode

With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.

document.cookie = "name=Linda Ojo; expires=Wed, 1 Oct 2022 12:00:00 UTC; path=/";
Enter fullscreen mode Exit fullscreen mode

Handling Cookies using just vanilla JavaScript can get tedious real quick that's why I prefer using the JavaScript Cookie Package

Handling Cookies with JavaScript Cookie Package

JavaScript Cookie is a simple lightweight JavaScript API for handling cookies. It works on all browsers, accepts any character, heavily tested and requires no dependency. Awesome!

Installation

Run the command below in your root folder to install js-cookies.

npm install js-cookie --save
Enter fullscreen mode Exit fullscreen mode

Cookie Attributes

  • Expire: define when the cookie will be removed. Value can be a Number which will be interpreted as days from time of creation or a Date instance.

  • Path: a String indicating the path where the cookie is visible.

  • Domain: a String indicating a valid domain where the cookie should be visible. The cookie will also be visible to all subdomains.

  • Secure: Either true or false, indicating if the cookie transmission requires a secure protocol (https).
  • Create a cookie

    We can create a cookie that valid across the entire website by providing the name and the value as shown below.

    import Cookies from 'js-cookie';
    
    Cookies.set('name', 'value');
    
    Enter fullscreen mode Exit fullscreen mode

    We can specify how long it takes for a cookie to expire by passing an object that contains the number of days before expiration as the third argument in the Cookie.set method. The cookie that's created below expires after 7 days. By default, a cookie is removed when the user closes the browser.

    import Cookies from 'js-cookie';
    
    Cookies.set('name', 'value', { expires: 7 });
    
    Enter fullscreen mode Exit fullscreen mode

    Next,We can create an secure expiring cookie that's only valid to the path of the current page. The path is add to the previous Object which contains the expiration date.

    Cookies.set('name', 'value', { expires: 7, path: '', secure: true });
    
    Enter fullscreen mode Exit fullscreen mode

    Read cookie

    The point of creating cookies is so we can use them later. We can access already existing cookies using the Cookie.get method. Let's create and read a real cookie called 'theme'.

    import Cookies from 'js-cookie';
    
    Cookies.set('theme', 'dark');
    Cookies.get('theme') // => 'dark'
    
    Enter fullscreen mode Exit fullscreen mode

    You can also update a cookie by overriding it's value

    Cookies.set('theme', 'light');
    
    Enter fullscreen mode Exit fullscreen mode

    Now the theme cookie has a value of 'light'.

    We can get all cookies present at once by calling Cookies.get method without passing in any arguments as shown below.

    
    Cookies.get(); // => { theme: 'light' }
    
    
    Enter fullscreen mode Exit fullscreen mode

    Delete cookie

    You can delete cookies that are globally accessible running the Cookie.remove method with just the first argument which is value

    Cookies.remove('theme');
    
    Enter fullscreen mode Exit fullscreen mode

    Note:cwhen deleting a cookie and you're not relying on the default attributes, you must pass the exact same path and domain attributes that were used to set the cookie.
    let's set and delete a cookie valid to the path of the current page as an example.

    Cookies.set('direction', 'north', { path: '' });
    Cookies.remove('direction'); // fail!
    Cookies.remove('direction', { path: '' }); // removed!
    
    Enter fullscreen mode Exit fullscreen mode

    That's all folks. Read more of my articles

    Top comments (18)

    Collapse
     
    davwheat profile image
    David Wheatley

    As a Brit, I can confirm that we use cookies and biscuits to mean different things :)

    Collapse
     
    lindaojo profile image
    Linda

    Omg yes! 😂

    Collapse
     
    yoursunny profile image
    Junxiao Shi

    I guess this one is for the British:
    npmjs.com/package/biscuit.js

    Collapse
     
    lindaojo profile image
    Linda

    Exactly! I love that this exists 😂😂

    Collapse
     
    kowellternerr profile image
    Timmy Terner

    You will experience a real explosion of flavor with this amazing Bonne Maman La Madeleine biscuit. It brings the tenderness of the dough and the perfect combination of flavor factors that will take you into a world of delight. Try this biscuit and you'll immediately understand why I recommend it to anyone looking for a truly cool and delicious treat. With no chemical additives, it provides a rich and natural experience that will surprise you after the first bite.

    Collapse
     
    ademirqj profile image
    Ademir Quirino

    Excelent article, I will share.

    Collapse
     
    sergio1 profile image
    Sergio Answer

    בהיעדר בן זוג אינטימי שיוכל לתמוך בך בשעת הצורך או ללוות אותך לאירוע חברתי, אני ממליץ לך ליצור קשר עם נערות ליווי, זוהי סוכנות הליווי האמינה והמוכחת ביותר בחיפה בעזרת קוהוטורו. תאסוף בחורה מתאימה לך. אם אתה עדיין לא יודע איך לבחור בחורה, אל תדאג כי הסרסור יכול לעזור לך

    Collapse
     
    lindaojo profile image
    Linda

    Thank you!

    Collapse
     
    ktoni73 profile image
    kToni73

    Cheers, been meaning to read upon this :)

    Collapse
     
    dhintz89 profile image
    Daniel Hintz

    This is great! I've been meaning to get more familiar with cookies and this was a really good introduction. Thanks for posting!

    Collapse
     
    lindaojo profile image
    Linda

    Thanks! Glad you liked it.

    Collapse
     
    oyeleyemustapha profile image
    Mustapha oyeleye

    Greate Article.

    Collapse
     
    lindaojo profile image
    Linda

    Thank you

    Collapse
     
    stuartcmd profile image
    Stuart

    Linda, thank you for an excellent explanation.

    Collapse
     
    lindaojo profile image
    Linda

    Thank Stuart!

    Collapse
     
    lindaojo profile image
    Linda

    Thank you!

    Collapse
     
    axhat profile image
    Axhat

    Are these cookies internet's own cache? :-)

    Collapse
     
    mohammadjr7 profile image
    MohamamadJavad

    Good info; thanks!