DEV Community

Cover image for Cookies Explained — How They Work & Header-Based Auth vs Cookie-Based Auth
Jack Pritom Soren
Jack Pritom Soren

Posted on

Cookies Explained — How They Work & Header-Based Auth vs Cookie-Based Auth

A Backend Engineer’s Deep-Dive

When people say:

“Authentication is confusing”

What they usually mean is:

👉 Cookies, headers, sessions, tokens, browser behavior — all mixed together.

This article clears that confusion from the ground up.


🌐 First: Why Cookies Exist at All

HTTP is stateless.

That means:

  • Server does NOT remember users
  • Every request is independent

But real apps need memory:

  • Logged-in users
  • Shopping carts
  • Preferences
  • Sessions

So browsers introduced cookies.


🍪 What Is a Cookie?

A cookie is a small piece of data stored by the browser and automatically sent to the server with every request to the same domain.

👉 Cookies are not authentication by themselves
👉 Cookies are just a transport mechanism


Cookie Example

Server response:

Set-Cookie: session_id=abc123; HttpOnly; Secure
Enter fullscreen mode Exit fullscreen mode

Browser stores it.

Later request:

Cookie: session_id=abc123
Enter fullscreen mode Exit fullscreen mode

That’s it.

No magic.


Important Cookie Properties (Backend MUST Know)

Flag Meaning
HttpOnly JS cannot access cookie
Secure Sent only over HTTPS
SameSite Controls cross-site sending
Path URL scope
Domain Which domain can read

Cookie ≠ Session ≠ Token

This confusion causes 90% of auth bugs.

  • Cookie → storage + transport
  • Session → server-side state
  • Token → self-contained credential

Cookies can carry:

  • Session IDs
  • JWT tokens
  • Preferences

🔁 How Cookies Work (Full Flow)

Step 1: User Logs In

Server verifies credentials.

Step 2: Server Sends Cookie

Set-Cookie: session_id=abc123
Enter fullscreen mode Exit fullscreen mode

Step 3: Browser Stores Cookie

Invisible to user.

Step 4: Browser Automatically Sends Cookie

Every request to the domain.

👉 Backend doesn’t need to ask for it.


🧠 Why Cookies Are Powerful

Because:

  • Automatically attached by browser
  • Work with redirects
  • Secure flags exist
  • No manual JS handling required

That’s why sessions traditionally use cookies.


🔐 Cookie-Based Authentication

How It Works

  1. Login success
  2. Server creates session
  3. Session ID stored in cookie
  4. Browser sends cookie automatically
  5. Server checks session store
Browser → Cookie → Server → Session Store
Enter fullscreen mode Exit fullscreen mode

Advantages

✅ Automatic sending
✅ Protected by HttpOnly
✅ Strong CSRF defenses possible
✅ Mature browser support


Disadvantages

⚠️ CSRF risk (if misconfigured)
⚠️ Less natural for mobile apps
⚠️ Cross-domain complexity


🔥 Header-Based Authentication

This is common in APIs.

Instead of cookies:

Authorization: Bearer <token>
Enter fullscreen mode Exit fullscreen mode

How Header-Based Auth Works

  1. User logs in
  2. Server returns token (JWT)
  3. Client stores token
  4. Client manually attaches header
  5. Server verifies token
Client → Authorization Header → Server
Enter fullscreen mode Exit fullscreen mode

Advantages

✅ Stateless
✅ Perfect for APIs
✅ Easy for mobile apps
✅ No CSRF (by default)


Disadvantages

⚠️ Token theft risk
⚠️ Must manage expiration
⚠️ Manual handling in frontend


⚔️ Cookie vs Header — Direct Comparison

Feature Cookies Headers
Auto-sent by browser ✅ Yes ❌ No
CSRF risk ⚠️ Yes ❌ No
Works well with SSR ✅ Yes ❌ Harder
Mobile friendly ⚠️ Limited ✅ Excellent
Security flags ✅ Yes ❌ No

🧠 Cookie + Token (Modern Best Practice)

Very common today:

  • JWT stored in HttpOnly cookie
  • Sent automatically
  • No JS access
  • No localStorage risks

This gives:

✔ Token scalability
✔ Cookie security


⚠️ Why CSRF Happens (Simple Explanation)

Because cookies are auto-sent.

Malicious site:

<img src="bank.com/transfer?amount=1000" />
Enter fullscreen mode Exit fullscreen mode

Browser sends cookies → server thinks it’s legit.

Mitigation:

  • SameSite=strict
  • CSRF tokens
  • Double submit cookie

🧠 Why Sessions Are NOT Stored in Database (Usually)

This is a very important backend design question.

Short answer:

👉 You can store sessions in DB — but you usually shouldn’t.

Let’s explain why.


Problem 1: Database Is Too Slow

Sessions are accessed:

  • On every request
  • By every authenticated user

DBs are optimized for:

  • Business data
  • Transactions
  • Queries

Not millions of tiny reads per second.

This creates:

❌ Latency
❌ Lock contention
❌ Performance bottlenecks


Problem 2: Database Connections Are Limited

DBs have limited connections.

Session lookups steal connections from:

  • Orders
  • Payments
  • Writes

Bad tradeoff.


Problem 3: Cleanup Is Expensive

Sessions expire.

In DB you need:

DELETE FROM sessions WHERE expires_at < now();
Enter fullscreen mode Exit fullscreen mode

This causes:

  • Table scans
  • Locks
  • IO pressure

At scale → dangerous.


Problem 4: Horizontal Scaling Pain

If DB goes down:

👉 Auth goes down

Single point of failure.


🧠 Why Redis Is Used Instead

Redis is:

  • In-memory
  • Extremely fast
  • TTL built-in
  • Designed for ephemeral data

Example:

SET session:abc123 userId=42 EX 3600
Enter fullscreen mode Exit fullscreen mode

Redis auto-expires sessions.

No cleanup job needed.


❗ When DB Sessions MAY Be Acceptable

Small apps:

  • Low traffic
  • Monolith
  • MVP
  • Internal tools

Even then — Redis is better if available.


🧭 Final Mental Models (Memorize These)

👉 Cookies are carriers, not auth
👉 Headers are manual carriers
👉 Sessions = server remembers you
👉 Tokens = you prove yourself
👉 Databases store truth, not temporary state


⭐ Backend Interview Gold Tip

If interviewer asks:

“Why not store sessions in DB?”

Answer:

“Sessions are high-frequency, short-lived, non-critical data.
Databases are optimized for durability, not ephemeral state.
Redis matches session access patterns much better.”

That’s a senior-level answer.


Follow me on : Github Linkedin Threads Youtube Channel

Top comments (0)