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)