DEV Community

Abhay Yt
Abhay Yt

Posted on

Comprehensive Guide to Cookies in JavaScript

Cookies in JavaScript

Cookies are small pieces of data stored on the user's browser by a website. They are commonly used to store user preferences, track sessions, or maintain state between requests.

JavaScript provides simple methods to create, read, and delete cookies, making it an essential tool for client-side storage and session management.


1. Setting Cookies

Cookies are created by assigning a string to document.cookie.

Syntax:

document.cookie = "key=value; expires=DATE; path=PATH; domain=DOMAIN; secure; SameSite=VALUE";
Enter fullscreen mode Exit fullscreen mode
  • key=value: Key-value pair of the cookie.
  • expires: Expiration date (optional). If not set, the cookie is a session cookie and is deleted when the browser is closed.
  • path: Path within the site where the cookie is accessible (default: current path).
  • domain: Domain where the cookie is accessible (default: current domain).
  • secure: Cookie is only sent over HTTPS.
  • SameSite: Controls cross-site behavior (Strict, Lax, or None).

Example:

document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
Enter fullscreen mode Exit fullscreen mode

2. Reading Cookies

The document.cookie property returns all cookies for the current domain and path as a single string.

Example:

console.log(document.cookie);
// Output: "username=JohnDoe; theme=dark; sessionId=abc123"
Enter fullscreen mode Exit fullscreen mode

To extract specific cookies, parse the string:

function getCookie(name) {
  const cookies = document.cookie.split("; ");
  for (let cookie of cookies) {
    const [key, value] = cookie.split("=");
    if (key === name) return value;
  }
  return null;
}
console.log(getCookie("username")); // Output: JohnDoe
Enter fullscreen mode Exit fullscreen mode

3. Updating Cookies

To update a cookie, set it again with the same key but different value or options.

Example:

document.cookie = "username=JaneDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
console.log(document.cookie); // Output: "username=JaneDoe; ..."
Enter fullscreen mode Exit fullscreen mode

4. Deleting Cookies

To delete a cookie, set its expiration date to a past date.

Example:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
Enter fullscreen mode Exit fullscreen mode

5. Handling Special Characters

Special characters in cookie values must be encoded using encodeURIComponent and decoded with decodeURIComponent.

Example:

document.cookie = "userInfo=" + encodeURIComponent("John Doe & Admin");
console.log(decodeURIComponent(getCookie("userInfo"))); // Output: John Doe & Admin
Enter fullscreen mode Exit fullscreen mode

6. Security Considerations

  1. Secure Flag:
    • Use Secure to ensure cookies are transmitted only over HTTPS.
   document.cookie = "sessionId=abc123; secure";
Enter fullscreen mode Exit fullscreen mode
  1. HttpOnly Cookies:

    • Cannot be accessed via JavaScript (set on the server side).
  2. SameSite Attribute:

    • Controls cross-site cookie behavior to prevent CSRF attacks.
   document.cookie = "sessionId=abc123; SameSite=Strict";
Enter fullscreen mode Exit fullscreen mode

7. Cookie Attributes Summary

Attribute Description
expires Expiration date for the cookie.
path Limits cookie to specific paths.
domain Specifies the domain for the cookie.
secure Ensures cookie is sent over HTTPS.
SameSite Controls cross-site cookie behavior.

8. Managing Cookies with JavaScript

To make cookie management easier, encapsulate common operations in utility functions.

Example:

// Set a cookie
function setCookie(name, value, days) {
  const date = new Date();
  date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  const expires = "expires=" + date.toUTCString();
  document.cookie = `${name}=${value}; ${expires}; path=/`;
}

// Get a cookie
function getCookie(name) {
  const cookies = document.cookie.split("; ");
  for (let cookie of cookies) {
    const [key, value] = cookie.split("=");
    if (key === name) return value;
  }
  return null;
}

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

// Example usage
setCookie("theme", "dark", 7); // Set theme cookie for 7 days
console.log(getCookie("theme")); // Output: dark
deleteCookie("theme"); // Remove theme cookie
Enter fullscreen mode Exit fullscreen mode

9. Summary

Cookies are a fundamental tool for maintaining state in web applications. Proper handling ensures functionality while protecting user data.

  • Use Secure and SameSite for safer cookies.
  • Avoid storing sensitive information directly in cookies.
  • Use JavaScript utilities to simplify cookie management.

Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.

Top comments (0)