Unveiling the Secrets of Cookies: A Fun and Informative Guide

Fares waheed - Jul 30 - - Dev Community

What you will learn?✨

  • What is a Cookie?
  • How do Cookies work?
  • Some Cookie Network Terminologies
  • Cookies Tags

Welcome to the cookie wonderland! No, we're not talking about the delicious kind you dip in milk—we're diving into the tiny bits of data magic that make your online experience smooth and personalized. Ever wondered how websites remember your preferences or keep you logged in? Let's unwrap the mystery of cookies!
Cookies word

What is a Cookie? 🧐

Cookies are small data pieces stored on your device by a web browser while you're browsing a website. It's worth noting that cookies are specifically a browser term.

Key Characteristics of Cookies

  1. Key-Value Pairs Storage 🗂️
    • Think of cookies like little sticky notes that store information in the form of key-value pairs.
    • Example: userID=12345.
  2. Limited in Size 📏
    • Cookies have a maximum size of 4KB, including both the name and the value.
  3. Browser Responsibility 🌐
    • Browsers save and send cookies automatically with every request, adhering to certain tags.
  4. Multiple Usage Options 🎛️
    1. Session Management: Cookies keep you logged in as you navigate through pages.
    2. Personalization: Cookies remember your preferences and settings.
    3. Tracking: Cookies monitor your behavior and collect data for analytics and targeted advertising.

Pop Quiz! 📝

How many cookies can a browser save?

  • Browsers usually have a total limit of 3000 cookies.
  • Maximum cookies per domain varies between browsers:
    • Google Chrome, Microsoft Edge, and Opera: Maximum cookies per domain is 180.
    • Mozilla Firefox and Safari: Maximum cookies per domain is 150.

Why Do We Love Cookies? ❤️

Imagine visiting your favorite online store and having to log in every time you open a new page. Annoying, right? Cookies save the day by keeping you logged in, remembering your shopping cart, and even suggesting items based on your previous visits. They're the unsung heroes of a seamless web experience.

A Bit of Cookie History 📜

Cookies have been around since October 1994, first implemented in Netscape Navigator 0.9beta.

Fun Fact 💡

The term "cookie" was derived from "magic cookies," which are packets of data sent and received without change. This concept existed long before web browsers popularized it! Check the Early Use to find more.

Types of Cookies 🍪

Alright, cookie fans! Let's dive into the different types of cookies. These delicious data tidbits come in various forms based on their lifespan and who sets them.

How Long Do They Last? ⏳

  1. Session Cookies:
    • Temporary: These cookies are like your favorite TV show reruns—they disappear once you turn off the browser.
    • Storage: They are stored in the browser's memory (RAM).
    • By Default: Session cookies are, well, for the session. They vanish once the browser is closed.
    • Example: Imagine a sticky note you use during a meeting and then toss away when it's over.
  2. Persistent Cookies:
    • Long-lasting: These cookies stick around for a specified period, like a calendar reminder you set for next year.
    • Storage: They are stored on the user's hard drive.
    • Example: Think of a note you stick to your fridge to remind you of a vacation a year from now.

Who Sets These Cookies? 🧑‍🍳👨‍🍳

  1. First-party Cookies:
    • Set by the website you're visiting: These cookies are like the store loyalty cards—they're issued by the store (website) you're currently shopping at.
    • Example: When you log into your favorite online shop, it's a first-party cookie that remembers your preferences.
  2. Third-party Cookies:
    • Set by other domains: These cookies are like the flyers you get in the mail from other stores—they come from different places (domains) and are often used for advertising.
    • Example: While browsing your favorite news site, you might see ads that remember your shopping habits, thanks to third-party cookies.
    • Check this link if you want more insights into What are 3️⃣rd-party Cookies.

3rd party cookie

Cookie Trivia! 🍪

Which type of cookie do you think is responsible for keeping you logged in as you navigate through different pages of a website? Is it a session cookie or a persistent cookie?

……. Just wait for the next blog🫣


How do Cookies Work? 🔧

Ready to find out how cookies work behind the scenes? Let's break it down step by step. By the end of this, you'll know exactly how these tiny pieces of data make your web experience smoother and more personalized.

cookie way

Setting a Cookie 🏗️

Imagine you visit a website to buy a new pair of shoes👢 and the server needs to know who will pick up this pair. Here's what happens:

  1. Server Sends a Cookie: When you visit the site, the server responds with an HTTP response that includes a Set-Cookie header.

    Set-Cookie: user_id=abc123; expires=Wed, 09 Jun 2024 10:18:14 GMT; path=/; domain=.example.com
    

    In Rails, you might see:

    response.set_cookie(:cookie_name, tags_hash)
    

    expires, path, domain—oh, what the hell are those? Don't worry, we've got your back! We'll explain these soon, so stay tuned! 🚀

  2. Cookie Headers: This header contains all the information needed to set the cookie on your browser.

Think of it like the server giving your browser a little note saying, "Remember this info for later!"

Storing a Cookie 🗄️

Once the cookie is set, the browser takes over:

  1. Browser Stores the Cookie: The browser keeps this cookie safe, storing it either in memory (for session cookies) or on the hard drive (for persistent cookies).
  2. Sending the Cookie Back: On your next visit to the same site, the browser sends the cookie back to the server with an HTTP request using the Cookie header.
Cookie: user_id=abc123
Enter fullscreen mode Exit fullscreen mode

Using a Cookie 🛠️

Finally, the cookie's moment to shine🌟:

Server's Role: The server reads the cookie values to perform actions such as authenticating the user, remembering preferences, or tracking sessions.

Example: When you return to a website, the server sees your user_id cookie and says, "Oh, it's you! Welcome back!"

How does the server read the cookie? As we mentioned earlier, it's just a Cookie header. The server reads this header directly, but most of the time, each framework has some kind of middleware to handle cookies, making life easier. So, instead of manually parsing the Cookie header, you get a neat and tidy way to access cookie values.

I will find it in Rails as follows:

user_id = cookies[:user_id]
Enter fullscreen mode Exit fullscreen mode

Now you know the lifecycle of a cookie—from being set by the server to being stored and sent back by the browser, and finally, being used by the server to enhance your browsing experience. Next time you enjoy a personalized web session, you’ll know the magic behind it! 🪄✨

Network Terminologies 🌐

Understanding some key network terms can help you navigate the internet better and grasp how cookies work. Let's make this fun and easy!

Domain

💡 Pop Quiz:
Given the URL: https://staging.example.com:443/login, identify the following:

  • Port
  • Domain
  • Subdomain
  • Scheme
  • Registrable domain
  • Top-level domain

Okay, let's explain them first, and the answers will be provided shortly!

  • Domain: The URL without the port, endpoint, and scheme. It's a human-readable address used to access websites, like an IP address's cool nickname.
    • Examples: staging.example.com, google.co.uk
  • Subdomain: A part of a larger domain.
    • Example: staging in staging.example.com
  • TLD (Top-Level Domain): The last part of a domain name.
    • Example: .com, .uk
  • Registrable Domain: The base or root domain that is bought from Domain Name Registrars (e.g., GoDaddy, Namecheap).
    • Example: example.com
    • Fun Fact: Oxford (ox.ac.uk) and Cambridge (cam.ac.uk) are different registrable domains. So it's not just about the dots! 🌟

How Does the Browser Know? 🤔

When you're typing a web address into your browser, it needs to figure out where to send your request. How does it know where example.com lives on the internet? Let's break it down!

  • Domain Name Registries: These are like the phone books of the internet. They maintain the database of all domain names registered within their TLD (Top-Level Domain). Every time you register a new domain, it's added to this giant directory.

Imagine It Like This:

  • You: "I want to visit example.com."
  • Browser: "Okay, let me check my directory."
  • Domain Name Registries: "Here's the IP address for example.com."

These registries make sure that each domain name is unique and can be correctly translated into an IP address that computers use to locate each other on the internet. Think of them as the middlemen that keep everything running smoothly behind the scenes!

Why Is This Important for Cookies?

When you set a cookie for a domain, it needs to be linked to the correct domain so that the right websites can access it. The browser uses the domain name system to ensure that the cookie is associated with the proper domain.

For example, if you set a cookie for example.com, the browser will check with the domain name registry to ensure that this domain is correctly identified and that the cookie can be accessed by example.com and its subdomains like sub.example.com.

Sounds like a plan! Stay tuned for the cookie domain magic—it's going to be a cookie-licious ride! 🍪🚀

Site

A site is a combination of a protocol (schema) and a registrable domain. It's like the main hub of your web address.

Hands-on Exercise:

URL 1 URL 2 Same Site Reason
https://www.example.com/foo https://foo.bar.example.com/bar Yes Same protocol and registrable domain
https://www.cam.ac.uk/ https://www.cambridgestudents.cam.ac.uk/ Yes Same protocol and registrable domain
https://example.com/foo http://example.com/bar No Different protocols
https://www.ox.ac.uk/ https://www.cam.ac.uk/ No Different registrable domains
https://example.com/ https://example.net/ No Different registrable domains

Origin

Where does it come from?

Components of an Origin:

  1. Scheme (Protocol): http, https, ftp, etc.
  2. Host (Domain): example.com, subdomain.example.com
  3. Port: 80, 443, etc.

Hands-on Exercise:

URL 1 URL 2 Same Origin Reason
https://foo.bar.example.com/bar https://bar.example.com/bar No Different domain
https://example.com/:443 https://example.com/services Yes Same protocol, domain, and port

SOP (Same-Origin Policy)

SOP allows web pages to make requests to the same origin without any restrictions. Think of it as the no-restrictions zone for your web pages.

Cross-Site

The opposite of same-site. It's like traveling to a different part of the web world.

Cross-Origin

The opposite of origin. It's like sending a postcard from one city to another.

Cross-Origin Requests:

  • By default, browsers block cross-origin requests to prevent security risks.
  • If a script on https://example.com tries to make an AJAX request to https://api.example.com, the browser will block this request unless the server at https://api.example.com explicitly allows it using Cross-Origin Resource Sharing (CORS).

CORS (Cross-Origin Resource Sharing)

CORS is a mechanism that allows servers to specify who can access their resources and which HTTP methods and headers are allowed. This configuration happens server-side.

  • Main Reason: Protect your server resources.
  • Relation to Cookies: To send cookies with each request, the server needs to indicate that it allows credentials to be sent. This is done using the header Access-Control-Allow-Credentials: true.
  • For more insights on how CORS works, check out this link.

Cookies and Network Terminologies

Cross-Origin and Cookies: For cookies to be sent with cross-origin requests, the server must set the Access-Control-Allow-Credentials: true header.

Pop Quiz Answer 📝

For the URL https://staging.example.com:443/login:

  • Port: 443
  • Domain: example.com
  • Subdomain: staging
  • Scheme: https
  • Registrable domain: example.com
  • Top-level domain: .com

Understanding these terms helps in grasping how web technologies work and how different parts of a URL interact. Whether you're setting cookies, managing cross-origin requests, or just curious about how your browser communicates with servers, these basics are essential! 🌐


Cookies Tags 🍪🔖

Domain

Think of this as the VIP guest list. 🍾 A cookie with a domain tag only mingles with the specified domain. So, no need for Facebook cookies to crash the AWS party. 🎉

Example: https://staging.example.com:443

Path

This tag tells the cookie which part of the website it should visit. Imagine it as a map directing the cookie to the right directory, like sending it straight to the admin_portal/v1/sessions/refresh_access_token for a special mission. 🗺️

Security Tags: Keeping Cookies Safe

HttpOnly

This tag is like a secret service for your cookie, ensuring no JavaScript can peek at it. 🕵️‍♂️ It helps prevent Cross-Site Scripting (XSS) attacks, where sneaky scripts try to inject malicious code into your site. 🚫🕵️

Secure

This tag says, "Only on HTTPS, please!" 🚀 It ensures cookies are only sent over secure, encrypted connections. 🛡️

SameSite

Think of SameSite as a cookie’s travel restriction. 🌍 Here’s how it works:

  • Strict: The cookie is a homebody—only works on its own site. 🌐
  • Lax: It’s a bit more flexible but still cautious. It joins cross-site requests only under certain conditions:
    1. The request method must be safe (like GET, not POST). 🚦
    2. The request must be a top-level navigation, meaning the URL changes (like clicking a link to a new site). 🌐
  • None: The cookie is a world traveler, allowing all cross-site requests but requires secure connections (secure: true). ✈️🔒

Wrapping It Up 🎁

You've journeyed through the sweet world of cookies, and now you're a cookie connoisseur! Here’s a quick summary of what we've learned:

  • What is a Cookie?

    Tiny data packets stored by your browser to make your web experience smoother and more personalized.

  • How do Cookies Work?

    They’re set by the server, stored by the browser, and sent back with requests to help with things like logging in and remembering settings.

  • Some Cookie Network Terminologies:

    • Domain: The URL’s home base where cookies belong.
    • Path: The specific directory the cookie targets.
    • Origin: A combination of protocol, domain, and port to define where requests are coming from.
    • Same-Origin Policy: Keeps cross-origin requests in check for security.
    • CORS: Allows servers to specify who can access their resources and under what conditions.
  • Cookie Tags:

    • Basic Tags: Domain and Path for targeting cookies effectively.
    • Security Tags: HttpOnly, Secure, and SameSite to keep cookies safe and controlled.

Final Note 🌟

Thanks for sticking with us through this delightful cookie journey! 🎉🍪 Whether you're setting cookies like a pro or simply curious about the sweet technology behind the scenes, you've got the knowledge to handle your cookies with confidence.

Big thanks for reading, and may your cookies be secure and your web adventures ever more delicious! 🍪✨

.
Terabox Video Player