Cookies are small text files that websites store on your computer. They contain data about your interaction with the site, such as login information, visited pages, clicked links, and more. This data helps the website remember your preferences, making your browsing experience more personalized and efficient.
When a user visits a website for the first time, the site creates a new cookie for that user. The server sends this cookie to the user's browser, which then stores it locally on the user's machine. On subsequent visits, the browser sends this cookie back to the server, allowing it to recognize the user and recall their preferences.
For example, when you visit an e-commerce site and add items to your shopping cart, that information is stored in a cookie. Even if you leave the site and come back later, your shopping cart will still contain the items you added earlier, thanks to cookies.
You can create a new cookie or update an existing one using the
document.cookie property. Here's an example:
document.cookie = "username=John Doe; expires=Fri, 31 Dec 2021 23:59:59 GMT";
In this code, we're creating a cookie named
username with the value
John Doe. The
expires attribute sets the expiration date for the cookie. After this date, the browser will delete the cookie automatically.
You can retrieve all cookies for the current page as a single string using the
This code will output something like this:
username=John Doe; expires=Fri, 31 Dec 2021 23:59:59 GMT
You can delete a cookie by setting its
expires attribute to a past date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
In this code, we're essentially updating the
username cookie and setting its expiration date to 1st January 1970. This will cause the browser to delete the cookie immediately.
1. What are secure cookies?
Secure cookies are those that can only be transmitted over an encrypted connection (i.e., HTTPS). They help prevent the data in the cookie from being intercepted by malicious entities. You can make a cookie secure by adding the
secure attribute when creating it:
document.cookie = "username=John Doe; secure";
2. How can I make my cookies HttpOnly?
3. What are third-party cookies?
Third-party cookies are created by domains other than the one you're currently visiting. They are often used for tracking and online-advertising purposes.
For more in-depth information, you can check the Mozilla Developer Network documentation.
Note: This blog post was written for codedamn, an interactive learning platform for programmers.
Free money-back guarantee
Unlimited access to all platform courses
100's of practice projects included
ChatGPT Based Instant AI Help (Jarvis)
Structured Full-Stack Web Developer Roadmap To Get A Job
Exclusive community for events, workshops
Sharing is caring
Did you like what Sarthak Jain wrote? Thank them for their work by sharing it on social media.
No comments so far
Leave a question/feedback and someone will get back to you