DEV Community

Cover image for HttpOnly Cookies 🍪
Kalama Ayubu
Kalama Ayubu

Posted on

HttpOnly Cookies 🍪

If you have looked at the banner above carefully, you probably already understand what HttpOnly cookies are 👌 — and this should be the end of this post 😂😂.
But let's break it down anyway...

What are HttpOnly Cookies?

HttpOnly cookies are cookies that cannot be accessed or modified by client-side javaScript(javaScript in the browser). They’re server-side only, which means only your backend can set, read or delete these cookies.

Why do HttpOnly Cookies Matter?

Security🔏
Cookies often hold sensitive data like:

  • Authentication tokens
  • Session IDs
  • Refresh tokens
  • User data

If this info is accessible via frontend JavaScript, opens the door to client-side threats like:

  • XSS (Cross-Site Scripting)
  • Malicious browser extensions
  • Session hijacking
  • Rogue scripts in your frontend

Using the HttpOnly flag prevents frontend access, reducing attack surfaces.

How to Set an HttpOnly Cookie

Let’s say you’re setting a cookie in a Next.js API route (or any backend framework):

cookieStore.set('your-cookie-name', cookieValue, {
  path: "/", // Available throughout the app
  httpOnly: true, // Keeps it hidden from client-side JS
  secure: process.env.NODE_ENV === "production",
  sameSite: 'lax',
  maxAge: 60 * 60 * 3, // Expires in 3 hours
});
Enter fullscreen mode Exit fullscreen mode

Boom! You now have a cookie that’s:

  • scoped correctly
  • secure over HTTPS
  • immune to frontend peeking
  • and automatically expires

Now, try to access it from the frontend using document.cookie or js-cookie. library
Let me give you a hint: It won’t work. At all. 😏

Just to Be Clear...
I intentionally focused only on the HttpOnly way of doing things — not on how to work with cookies from scratch.

Why?
Because going too deep would make the post unnecessarily large and potentially boooring...
And I hate seeing myself bored 😩..

Wrapping up

So here’s your takeaway:
If your cookies store sensitive data, make them HttpOnly.
Keep them server-side, and sleep better at night 🛏️.

Thy cookies shall be safe.
happy coding 🚀

Want to share your thoughts or ask a question?
Drop a comment below — I’d love to keep the conversation going!

Top comments (0)