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)