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.
Cookies are created by assigning a string to document.cookie.
document.cookie = "key=value; expires=DATE; path=PATH; domain=DOMAIN; secure; SameSite=VALUE";
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
The document.cookie property returns all cookies for the current domain and path as a single string.
console.log(document.cookie); // Output: "username=JohnDoe; theme=dark; sessionId=abc123"
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
To update a cookie, set it again with the same key but different value or options.
document.cookie = "username=JaneDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/"; console.log(document.cookie); // Output: "username=JaneDoe; ..."
To delete a cookie, set its expiration date to a past date.
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
Special characters in cookie values must be encoded using encodeURIComponent and decoded with decodeURIComponent.
document.cookie = "userInfo=" + encodeURIComponent("John Doe & Admin"); console.log(decodeURIComponent(getCookie("userInfo"))); // Output: John Doe & Admin
document.cookie = "sessionId=abc123; secure";
HttpOnly Cookies:
SameSite Attribute:
document.cookie = "key=value; expires=DATE; path=PATH; domain=DOMAIN; secure; SameSite=VALUE";
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. |
To make cookie management easier, encapsulate common operations in utility functions.
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
Cookies are a fundamental tool for maintaining state in web applications. Proper handling ensures functionality while protecting user data.
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!