The Ultimate Beginner's Guide to Browser Cookies

Prateek BajpaiPrateek Bajpai
7 min read

You’ve probably seen privacy-related pop-up messages lots of times:
“The website uses cookies to improve your experience.”

You’ve probably seen this message many times. Most people just click “Accept” or “Reject” without thinking about it.
But have you ever wondered:

  • What are cookies?

  • Why do all websites ask about them?

  • Are cookies there to help you, or to watch what you do?

Don’t worry—cookies aren’t as scary as they sound!
In this easy guide, we’ll simply explain:

  • What cookies are

  • Why websites use them

  • What it means for you

  • And how to stay safe online

Ready to quickly understand cookies? Let’s get started 👇

🗂️ Table of Content

  1. What Are Cookies?

  2. Why Do Websites Use Cookies?

  3. The Legal Side: Cookies and Consent

  4. Types of Cookies
      - Strictly Necessary
      - Functional
      - Performance/Analytics
      - Advertising/Targeting

  5. Session Cookies vs Persistent Cookies
      - Differences
      - Use Cases

  6. Cookie Components and Settings
      - Name & Value
      - Expires/Max-Age
      - Path
      - Domain
      - Secure
      - HttpOnly
      - SameSite

  7. Cookie Size Limit

  8. Setting Cookies: How It Works

    - Client-Side (JavaScript)
      - Server-Side (HTTP Headers)

  9. How to See Cookies in the Browser

  10. When Do Cookies Take Effect?

  11. Important Cookie Scenarios
      - Same Name, Different Paths
      - Sharing Across Subdomains

  12. What If the User Rejects Cookies?

  13. Common Cookie Security Vulnerabilities

  14. Extra Tips for Developers

  15. Alternatives to Cookies (localStorage, sessionStorage**,** etc.)

  16. Final Thoughts: Making Cookies Work for You


📌 What Are Cookies?

Cookies are tiny text files stored in your browser by websites.
They store key-value pairs like this:

textlanguage=English
theme=dark
sessionID=abc123

Each time you visit or revisit a page on that site, your browser quietly sends those cookies along with the request — helping the website remember you.


🔧 Why Do Websites Use Cookies?

Websites use cookies because without them, every time you move to a new page, the website would forget who you are. This means you would have to log in again and again or lose the things you were doing.

With cookies:

  • Keep you logged in

  • 🛒 Remember your shopping cart

  • 🎨 Save your theme or language

  • 📊 Track visits for analytics

  • 📢 Show you personalized ads (with your consent)

But here’s the catch: while cookies make your browsing easier and better, they can also be used to track what you do online. That’s why there are privacy laws that require websites to ask for your permission before using certain cookies


Thanks to privacy laws like the GDPR (Europe), CCPA (California), and others, websites are required to:

  1. Only set essential cookies automatically (like session or security cookies)

  2. Ask for your consent before using “non-essential” cookies (like tracking scripts or ads)

  3. Give you a choice — not just a yes

That’s why you see cookie banners everywhere now.


🍪 Types of Cookies

TypeWhat It DoesConsent Required?
Strictly NecessaryNeeded for basic site features (like login)❌ No
FunctionalSaves preferences (language, theme)✅ Yes
Performance / AnalyticsTrack usage to improve the site✅ Yes
Advertising / TargetingUsed for ads and personal tracking✅ Yes

🆚 Session Cookies vs Persistent Cookies

FeatureSession CookiesPersistent Cookies
LifespanDeleted when browser closesStay until their expiration date
How to SetNo Expires/Max-AgeHas Expires or Max-Age set
PurposeTemporary storage (e.g., cart, login)Remember the user over multiple visits
Stored Where?Browser memory (RAM)Disk (hard drive/storage)
ExampleShopping cart during a session“Remember me” login, language preference

Each cookie stores more than just a name and value. It has:

AttributePurpose
Name=ValueThe actual information to store (e.g., theme=dark)
Expires/Max-AgeWhen it should be deleted
PathWhich part of the site can use this cookie
DomainWhich sites/subdomains can read it
SecureOnly works on HTTPS connections
HttpOnlyHidden from JavaScript (adds security)
SameSiteControls when cookies are sent in cross-site requests (helps stop CSRF)
  • A single cookie must be 4KB or smaller (name + value + all attributes)

  • Browsers usually allow 20–50 cookies per domain

  • Going over the limit? Extra cookies may be dropped or old ones deleted

👉 Cookies larger than 4KB won’t be saved at all
👉 Browsers do NOT split large cookies automatically — you must split data manually if needed


🧪 Setting Cookies: How It Works

📍 Client-Side (JavaScript)

document.cookie = "theme=dark; path=/; expires=Fri, 01 Jan 2038 12:00:00 UTC; Secure; SameSite=Lax";

➡️ This cookie is instantly available to JavaScript on the same page.
It will be sent to the server on the next request (after refresh or navigation).

💻 Server-Side (HTTP Headers)

Set-Cookie: sessionId=abc123; HttpOnly; Path=/; SameSite=Strict

➡️ The browser saves this cookie and sends it with future requests to the same path/domain.


🔎 How to See Cookies in the Browser

Let’s look under the hood!

On Google Chrome or Microsoft Edge:

  1. Right-click on the page and select "Inspect"

  2. Go to the Application tab

  3. Under Storage, click Cookies

  4. Select the current website — you’ll now see names, values, domains, and more!


🔄 When Do Cookies Take Effect?

  • ✅ JavaScript (Client-Side) cookies are available immediately after being set

  • 🔃 But if the server needs to read the cookie, it will only see it on the next request — typically after a page reload

Some features, based on cookies, work instantly, while others take effect after a refresh or navigation.


Cookies with the same name but different Path= behavior behave separately.
Example:

  • theme=dark; Path=/shop

  • theme=light; Path=/

The browser stores both, but only sends the one matching the current page path.

🌍 Sharing Cookies Across Subdomains

Want to share a cookie across example.com, shop.example.com, and blog.example.com?

Set the domain like this:

document.cookie = "userId=123; domain=.example.com; path=/";

Now all subdomains can access it (unless restricted by SameSite settings).


🙅♂️ What If the User Rejects Cookies?

Great question! Websites must not set non-essential cookies unless the user says “yes.”

✅ Good Practices:

  • Don’t set analytics/ads cookies by default

  • Only start loading third-party scripts after consent

  • Remove cookies if a user says “No” or revokes consent

✨ JavaScript Example:

if (localStorage.getItem("trackingConsent") === "yes") {
 // Set Analytics or Other Cookie Here
  const script = document.createElement("script");
  script.src = "https://example.com/analytics.js";
  document.head.appendChild(script);
}

You can also use Consent Management Platforms (CMPs) like CookieYes or OneTrust, or Syrenis to automate this.


Risk NameWhat HappensHow to Prevent
Session HijackingStolen cookies let attackers log in as youUse Secure, HttpOnly, and HTTPS
Cross-Site Scripting (XSS)Scripts can steal cookiesUse HttpOnly to block JS access; sanitize inputs
CSRF AttackBad site tricks your browser to make actionsUse SameSite=Lax or Strict
Session FixationAttacker sets session ID before loginRegenerate session cookies after login
Overly wide domainsSharing cookies across all subdomains can be dangerousOnly share with subdomains if truly needed

✅ Extra Developer Tips

  • Use Secure + HttpOnly for sensitive cookies like logins

  • Keep cookies under 4KB

  • Don't store private data like passwords in cookies

  • Follow SameSite rules to prevent unwanted cross-site sharing

  • Clean up old/unused cookies regularly

  • Only keep cookies for as long as they’re needed (Expires and Max-Age matter!)

  • localStorage and sessionStorage can be better choices for big client-side data


🧠 Bonus: Alternatives to Cookies

For local data storage, you can use:

OptionMax SizeGood For
localStorage~5MBRemembering data across browser tabs
sessionStorageSame tab onlyTemporary form inputs, single tab

These don’t get sent to the server like cookies do.


🎯 Final Words: Make Cookies Work — Don’t Let Them Work Against You

Cookies are small but mighty.
They make our websites smoother, smarter, and more helpful…
But if used carelessly, they can expose users to security risks and privacy loss.

If you're a developer, respect cookie laws, stay minimal, and use secure flags.
If you're a user, know your rights, inspect your cookies, and feel free to say no.

1
Subscribe to my newsletter

Read articles from Prateek Bajpai directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Prateek Bajpai
Prateek Bajpai