The Ultimate Beginner's Guide to Browser Cookies

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
What Are Cookies?
Why Do Websites Use Cookies?
The Legal Side: Cookies and Consent
Types of Cookies
- Strictly Necessary
- Functional
- Performance/Analytics
- Advertising/TargetingSession Cookies vs Persistent Cookies
- Differences
- Use CasesCookie Components and Settings
- Name & Value
- Expires/Max-Age
- Path
- Domain
- Secure
- HttpOnly
- SameSiteCookie Size Limit
Setting Cookies: How It Works
- Client-Side (JavaScript)
- Server-Side (HTTP Headers)How to See Cookies in the Browser
When Do Cookies Take Effect?
Important Cookie Scenarios
- Same Name, Different Paths
- Sharing Across SubdomainsWhat If the User Rejects Cookies?
Common Cookie Security Vulnerabilities
Extra Tips for Developers
Alternatives to Cookies (localStorage, sessionStorage**,** etc.)
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
⚖️ The Legal Side: Cookies and Consent
Thanks to privacy laws like the GDPR (Europe), CCPA (California), and others, websites are required to:
Only set essential cookies automatically (like session or security cookies)
Ask for your consent before using “non-essential” cookies (like tracking scripts or ads)
Give you a choice — not just a yes
That’s why you see cookie banners everywhere now.
🍪 Types of Cookies
Type | What It Does | Consent Required? |
Strictly Necessary | Needed for basic site features (like login) | ❌ No |
Functional | Saves preferences (language, theme) | ✅ Yes |
Performance / Analytics | Track usage to improve the site | ✅ Yes |
Advertising / Targeting | Used for ads and personal tracking | ✅ Yes |
🆚 Session Cookies vs Persistent Cookies
Feature | Session Cookies | Persistent Cookies |
Lifespan | Deleted when browser closes | Stay until their expiration date |
How to Set | No Expires /Max-Age | Has Expires or Max-Age set |
Purpose | Temporary storage (e.g., cart, login) | Remember the user over multiple visits |
Stored Where? | Browser memory (RAM) | Disk (hard drive/storage) |
Example | Shopping cart during a session | “Remember me” login, language preference |
🧁 Cookie Components (What’s Inside a Cookie?)
Each cookie stores more than just a name and value. It has:
Attribute | Purpose |
Name=Value | The actual information to store (e.g., theme=dark ) |
Expires/Max-Age | When it should be deleted |
Path | Which part of the site can use this cookie |
Domain | Which sites/subdomains can read it |
Secure | Only works on HTTPS connections |
HttpOnly | Hidden from JavaScript (adds security) |
SameSite | Controls when cookies are sent in cross-site requests (helps stop CSRF) |
🔐 Cookie Size Limit
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:
Right-click on the page and select "Inspect"
Go to the Application tab
Under Storage, click Cookies
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.
⚠️ Important Cookie Scenarios
🔁 Same Cookie Name, Different Paths
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.
🛡️ Common Cookie Security Vulnerabilities
Risk Name | What Happens | How to Prevent |
Session Hijacking | Stolen cookies let attackers log in as you | Use Secure , HttpOnly , and HTTPS |
Cross-Site Scripting (XSS) | Scripts can steal cookies | Use HttpOnly to block JS access; sanitize inputs |
CSRF Attack | Bad site tricks your browser to make actions | Use SameSite=Lax or Strict |
Session Fixation | Attacker sets session ID before login | Regenerate session cookies after login |
Overly wide domains | Sharing cookies across all subdomains can be dangerous | Only 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
andMax-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:
Option | Max Size | Good For |
localStorage | ~5MB | Remembering data across browser tabs |
sessionStorage | Same tab only | Temporary 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.
Subscribe to my newsletter
Read articles from Prateek Bajpai directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
