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
});
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)