Step-by-Step Tutorial for Managing Cookies in JavaScript
Cookies are a fundamental part of web development and are widely used to store information about users’ activities and preferences. In JavaScript, cookies are an essential tool for web developers to track user activity, maintain user sessions, and store user data. In this article, we’ll discuss what cookies are, why we use them, and their advantages and disadvantages.
Learn More –
- Top Web Development Programming Technologies to Learn in 2023
- Top 10 Reasons Why You Should Learn C++ Language in 2023
- How To work with Recursive Function in PHP Tutorial
- CakePHP 4 API Development with JWT Authentication Tutorials
- Learn Complete CakePHP 4 Plugin Development Tutorials
Let’s get started.
What are Cookies?
Cookies are small text files stored on a user’s computer by a web browser. They contain information about the user’s activity on the web, such as login credentials, shopping cart items, and user preferences. Cookies are sent back and forth between the client’s browser and the web server with each request and response.
Why We Use Cookies?
Cookies are widely used by web developers for various reasons. Some of the most common reasons for using cookies are:
- Session Management: Cookies are used to manage user sessions. By storing session data in a cookie, the server can identify the user and maintain their session between requests.
- Personalization: Cookies can store user preferences and settings, such as language, layout, and theme. This allows the website to customize the user experience and offer personalized content.
- Tracking: Cookies are used to track user behavior, such as page views, clicks, and purchases. This data is then used to analyze user behavior, improve website performance, and deliver targeted advertising.
Advantages of Cookies
- Efficiency: Cookies are lightweight and can store a small amount of data, making them an efficient way to store information about the user.
- Usability: Cookies can store information that makes it easier for users to navigate and use a website. For example, by storing login credentials, users can quickly access their account without having to re-enter their username and password.
- Customization: Cookies can store user preferences, enabling websites to offer personalized content and experiences.
Disadvantages of Cookies
- Security: Cookies can be used by hackers to steal sensitive information, such as login credentials and personal data. If cookies are not encrypted, they can be intercepted and read by third parties.
- Privacy: Cookies can store personal information about users, which can be used for tracking and profiling. This has raised concerns about user privacy and has led to increased regulations, such as GDPR.
- Reliability: Cookies can be deleted or blocked by users, making them unreliable for storing critical information such as session data.
Complete Program To Handle Cookies in Javascript
Here’s an example program that sets, reads, and removes cookies using JavaScript:
Save a Cookie value
Set a cookie with a given name, value, and expiration time in days
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
Read a Cookie value
Read a cookie with a given name
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
Remove a Cookie value
Remove a cookie with a given name
function deleteCookie(name) {
document.cookie = name + '=; Max-Age=-99999999;';
}
Procedure to Call (Usage)
// Example usage
setCookie("myCookie", "Hello, world!", 7); //...
Let’s combine all code together.
<script> // Set a cookie with a given name, value, and expiration time in days function setCookie(name, value, days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/"; } // Read a cookie with a given name function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; } // Remove a cookie with a given name function deleteCookie(name) { document.cookie = name + '=; Max-Age=-99999999;'; } // Example usage setCookie("myCookie", "Hello, world!", 7); // Set a cookie named "myCookie" with value "Hello, world!" and expiration time of 7 days console.log(getCookie("myCookie")); // Read the value of "myCookie" from the cookie and log it to the console deleteCookie("myCookie"); // Remove the "myCookie" cookie </script>
In this program, we define three functions:
setCookie
: This function takes three arguments: the name of the cookie, the value of the cookie, and the number of days until the cookie expires. It sets a cookie with the given name and value, and an optional expiration time in days.getCookie
: This function takes one argument: the name of the cookie to read. It searches thedocument.cookie
string for a cookie with the given name, and returns its value if found.deleteCookie
: This function takes one argument: the name of the cookie to remove. It sets the cookie’s value to an empty string and sets its expiration time to a date in the past, effectively removing the cookie.
In conclusion, cookies are an essential tool for web developers that enable them to store information about users’ activities and preferences. While cookies offer many advantages, such as efficiency, usability, and customization, they also have some disadvantages, such as security, privacy, and reliability. To use cookies effectively, web developers must balance the benefits and risks, and ensure that they are used in compliance with applicable laws and regulations.
We hope this article helped you to learn about Step-by-Step Tutorial for Managing Cookies in JavaScript in a very detailed way.
Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.