Cookies: document.cookie

In the world of web development, managing data effectively is crucial. One of the fundamental ways to handle data on the client side is through the use of cookies. Cookies are small pieces of data stored on the user's browser. They play a vital role in enhancing user experience and functionality by remembering stateful information for the web page. In this guide, we will delve into how to manage cookies using JavaScript, providing you with practical code examples to integrate into your projects.

Creating Cookies with JavaScript

To create a cookie, you simply need to assign a string to document.cookie. This string must contain a key-value pair representing the cookie's name and value. Optionally, you can set attributes such as expiration, path, domain, and security for the cookie.

Here is how you can create a basic cookie:

document.cookie = "username=JohnDoe; path=/"; alert(document.cookie);

This line of code creates a cookie named username with the value JohnDoe, sets it to expire on June 8, 2024, and makes it accessible to the entire website.

Setting Expiry Dates

To ensure that a cookie is stored for a specific period, you must set an expiration date in UTC time format using the expires attribute. Alternatively, you can use the max-age attribute to specify the lifetime of the cookie in seconds.

Always specify an expiration date for your cookies to ensure they only persist for the intended duration.
document.cookie = "userSettings=darkMode; max-age=86400; path=/"; alert(document.cookie);

This cookie, userSettings, will expire after 24 hours (86,400 seconds) from the time it's created.

Retrieving Cookies in JavaScript

Retrieving cookies involves reading the document.cookie string as you already saw in the example above. This string contains all cookies for the current domain, stored in a semicolon-separated list. To find a specific cookie, you can split this string and search through the resulting array:

document.cookie = "username=JohnDoe; path=/"; function getCookie(name) { let cookieArray = document.cookie.split(';'); for(let i = 0; i < cookieArray.length; i++) { let cookiePair = cookieArray[i].split('='); if(name == cookiePair[0].trim()) { return cookiePair[1]; } } return null; } console.log(getCookie("username")); // Outputs: JohnDoe

Deleting Cookies

To delete a cookie, you can set its expiration date to a past date. This is effectively done by setting the expires attribute to a date that has already occurred.

document.cookie = "username=john; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/"; function getCookie(name) { let cookieArray = document.cookie.split(';'); for(let i = 0; i < cookieArray.length; i++) { let cookiePair = cookieArray[i].split('='); if(name == cookiePair[0].trim()) { return cookiePair[1]; } } return null; } console.log(getCookie("username"));

By setting the expiry date to January 1, 1970, the cookie is removed immediately by the browser.

When dealing with cookies that contain sensitive information, security becomes paramount. To enhance the security of cookies, you can use the Secure and HttpOnly attributes.

  • Secure: Ensures the cookie is sent only over HTTPS, preventing exposure through an HTTP connection.
  • HttpOnly: Prevents access to the cookie via JavaScript, protecting it from cross-site scripting (XSS) attacks.
If your website is served over HTTPS, add the Secure attribute to all cookies to prevent transmission over unsecure connections.
document.cookie = "sessionId=abc123; expires=Sat, 08 Jun 2024 12:00:00 UTC; path=/; Secure; HttpOnly";

This cookie is both secure and protected from being accessed by client-side scripts.

Conclusion

Cookies are a powerful tool for managing user-specific data and settings in web applications. By understanding how to create, retrieve, and securely manage cookies with JavaScript, developers can significantly enhance the user experience on their websites. Always remember to handle cookies with care, especially when dealing with personal or sensitive information.

Practice Your Knowledge

Which attributes can you use to enhance the security of cookies in JavaScript?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?