W3docs

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

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. The domain attribute controls scope: by default, cookies are limited to the current host and its subdomains. Setting domain=.example.com makes the cookie available to all subdomains, while domain=app.example.com restricts it to that specific subdomain.

Here is how you can create a basic cookie:


javascript— editable

This line of code creates a cookie named username with the value John Doe (encoded to safely handle the space), sets it to expire on June 8, 2025, and makes it accessible to the entire website. If the value contains spaces or special characters, always encode it using encodeURIComponent to prevent parsing issues.

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.

Warning

Always specify an expiration date for your cookies to ensure they only persist for the intended duration.


javascript— editable

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:


javascript— editable

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. Note: You must also match the exact path and domain attributes used when the cookie was created, otherwise the browser will not delete it.


javascript— editable

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 SameSite attributes via JavaScript. Note that the HttpOnly attribute cannot be set client-side; it must be configured on the server.

  • Secure: Ensures the cookie is sent only over HTTPS, preventing exposure through an HTTP connection.
  • SameSite: Restricts how cookies are sent with cross-site requests, helping prevent CSRF attacks.
Warning

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 2025 12:00:00 UTC; path=/; Secure; SameSite=Lax";

This cookie is secure and restricts cross-site requests. (HttpOnly protection must be handled server-side.)

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

Practice

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