0
0
JavascriptHow-ToBeginner · 4 min read

How to Use Cookies in JavaScript: Syntax, Examples, and Tips

In JavaScript, you use the document.cookie property to create, read, and delete cookies. To set a cookie, assign a string like name=value; expires=date; path=path to document.cookie. To read cookies, access document.cookie which returns all cookies as a single string.
📐

Syntax

Cookies in JavaScript are handled through the document.cookie property. To set a cookie, you assign a string with the cookie's name, value, and optional attributes like expiration date and path. To read cookies, you simply access document.cookie, which returns all cookies as a single string separated by semicolons.

  • Set cookie: document.cookie = "name=value; expires=DATE; path=PATH";
  • Read cookies: document.cookie
  • Delete cookie: Set the cookie with an expiration date in the past.
javascript
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";

console.log(document.cookie);
Output
username=JohnDoe
💻

Example

This example shows how to set a cookie named user with value Jane, read all cookies, and delete the cookie by setting its expiration date to the past.

javascript
function setCookie(name, value, days) {
  const expires = new Date(Date.now() + days * 864e5).toUTCString();
  document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires}; path=/`;
}

function getCookie(name) {
  return document.cookie.split('; ').reduce((r, v) => {
    const parts = v.split('=');
    return parts[0] === name ? decodeURIComponent(parts[1]) : r
  }, '');
}

function deleteCookie(name) {
  document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
}

// Set cookie
setCookie('user', 'Jane', 7);
console.log('Cookie set:', document.cookie);

// Read cookie
console.log('Read cookie user:', getCookie('user'));

// Delete cookie
deleteCookie('user');
console.log('Cookie after deletion:', document.cookie);
Output
Cookie set: user=Jane Read cookie user: Jane Cookie after deletion:
⚠️

Common Pitfalls

Common mistakes when using cookies in JavaScript include:

  • Not encoding cookie values, which can cause errors with special characters.
  • Forgetting to set the path attribute, causing cookies to be unavailable on other pages.
  • Not setting an expiration date, which creates session cookies that disappear when the browser closes.
  • Trying to read cookies immediately after setting them without considering browser behavior.
javascript
/* Wrong: No encoding and no path */
document.cookie = "user=John Doe";

/* Right: Encoding value and setting path */
document.cookie = "user=" + encodeURIComponent("John Doe") + "; path=/";
📊

Quick Reference

ActionSyntax ExampleDescription
Set cookiedocument.cookie = "name=value; expires=DATE; path=/";Creates or updates a cookie with optional expiry and path.
Read cookiesdocument.cookieReturns all cookies as a single string.
Delete cookiedocument.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";Deletes a cookie by setting its expiry in the past.
Encode valueencodeURIComponent(value)Encodes special characters in cookie values.
Decode valuedecodeURIComponent(value)Decodes encoded cookie values.

Key Takeaways

Use document.cookie to set, read, and delete cookies in JavaScript.
Always encode cookie values with encodeURIComponent to handle special characters.
Set the path attribute to control cookie availability across your site.
Set an expiration date to make cookies persistent; otherwise, they expire when the browser closes.
Delete cookies by setting their expiration date to a past date.