Home > Web Front-end > JS Tutorial > Comprehensive Guide to Cookies in JavaScript

Comprehensive Guide to Cookies in JavaScript

Linda Hamilton
Release: 2024-12-21 00:43:09
Original
582 people have browsed it

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";
Copy after login
Copy after login
  • 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=/";
Copy after login
Copy after login

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"
Copy after login

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
Copy after login

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; ..."
Copy after login

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=/";
Copy after login

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
Copy after login

6. Security Considerations

  1. Secure Flag:
    • Use Secure to ensure cookies are transmitted only over HTTPS.
   document.cookie = "sessionId=abc123; secure";
Copy after login
  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 = "key=value; expires=DATE; path=PATH; domain=DOMAIN; secure; SameSite=VALUE";
Copy after login
Copy after login

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:

document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
Copy after login
Copy after login

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.

The above is the detailed content of Comprehensive Guide to Cookies in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template