Understanding Cookies in Web Development
Introduction
In this blog, we'll delve deeper into the types of cookies, their properties, and the importance of cookies in web development, especially in the context of authentication and security.
Types of Cookies 🍪
Persistent Cookies: Stays even after the window is closed. Our auth cookies should be persistent; otherwise, the user must keep logging in every time they visit the website.
Session Cookies: Stays as long as the window is live. Once the window is closed, it is deleted.
Secure Cookies: Sent only over secure, encrypted connections (HTTPS). It also helps tackle man-in-the-middle attacks.
Properties of Cookies ℹ️
httpOnly:
This property restricts the access of the cookies on the client side. No one on the client side can access these cookies, be it the developer or some other hackers who could retrieve the confidential data from various injections on the client side.
It allows the cookies only to be sent (that is the default behavior of the cookies).
Domains:
We can define the domains only from which, when API calls/requests are made, the cookies should be sent to the server and not otherwise. It restricts unknown/random websites from making requests to our server.
We can opt to allow cookies to be sent from all domains as:
But it will make it vulnerable to CSRF attacks!!
SameSite:
This property gives more granular control over how and when cookies are sent based on the context of the requests.
Ensure cookies are not sent over cross-origin requests.
This option basically defines if we can send cookies when the request is made to the source site or not.
It has three options available:
Strict: Cookies will only be sent to the origin site when the request is made from the same site.
Lax:
This option is present by default; it allows cookies to be sent from top-level navigation (redirect links) and the defined sites and domains.
This option helps avoid CSRF attacks and keeps the user experience in check, as when the user lands on the website from top-level navigation/redirect links, the cookies are sent and the user gets the authenticated pages.
None: This option allows cookies to be sent from all requests from all sites and domains.
Conclusion
Cookies play a vital role in web development, especially when it comes to authentication and security. Understanding the different types of cookies and their properties can help in making informed decisions about their use in your web applications.
Subscribe to my newsletter
Read articles from Manish Kumar Gupta directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Manish Kumar Gupta
Manish Kumar Gupta
{ "about" : "Just an engineer ⚙️", "stack" : "T3 Stack || MERN || AWS || Docker" }