DEV Community

Om Prakash Tiwari
Om Prakash Tiwari

Posted on

Why I switched Back to Cookie

At some point, most developers go through this phase where cookies feel ancient.
Like table layouts or jQuery—“we’ve moved on from that, right?”

I thought the same.
I moved away from cookies… and then slowly, painfully, came back.

Here’s why.


Cookies: Great Until They Weren’t

In the beginning, cookies were easy.
They just worked.

But then reality hit:

document.cookie
Enter fullscreen mode Exit fullscreen mode

Anyone with JavaScript access could read them.
One XSS bug and boom—your auth token is gone.

That was enough for me to say:
“Nope. Cookies are unsafe.”

So I left.


Session Storage: Felt Safer, Wasn’t

Next, I tried sessionStorage.

The logic was simple:

  • Tab closes → data gone
  • Less persistence → less risk

But guess what?

  • JavaScript can still read it
  • XSS still wins
  • Accidentally close the tab → user logged out

Security-wise, it wasn’t better.
UX-wise, it was worse.


Local Storage: Convenient but Dangerous

Then came localStorage.

Persistent. Simple. Popular.

Also:

  • Fully readable by JavaScript
  • A gold mine for XSS attacks
  • Tokens just sitting there, waiting to be stolen

At this point I realized something uncomfortable:

Every solution I tried had the same weakness.


The Real Problem Was JavaScript Access

It finally clicked.

The issue wasn’t:

  • cookies
  • session storage
  • local storage

The issue was this:

If JavaScript can read your token, attackers can too.

So instead of finding new storage, I went back to the old one—
but used it correctly.


Cookies, Take Two (HttpOnly This Time)

This time, I used cookies with rules:

  • HttpOnly
  • Secure
  • SameSite
  • HTTPS only

Now:

  • JavaScript can’t touch the token
  • XSS can’t steal it
  • Browser sends it automatically
  • Backend stays clean and predictable

Suddenly… cookies made sense again.


The Irony

After all the modern solutions, I ended up with:

  • Better security
  • Cleaner auth flow
  • Less frontend complexity

Using something that existed all along.

Turns out cookies weren’t bad.
We were just using them wrong.


Final Thought

Security isn’t about what’s trendy.
It’s about what attackers can’t access.

And right now?
A properly configured HttpOnly cookie is one of the hardest places to steal from.

So yeah—I switched back to cookies.

Top comments (0)