Cookies are small pieces of data stored on the user’s computer by the web browser while browsing a website. JavaScript can create, read, and delete cookies, allowing developers to store data such as user preferences, session information, or tracking data.
What Are Cookies?
- Purpose: Cookies store small amounts of data to provide a personalized experience. For example, they remember user login states or shopping cart contents.
- Size Limit: Typically, cookies are limited to 4KB of data.
- Lifespan: Cookies can have an expiration date, making them session-based (deleted when the browser closes) or persistent (saved for longer periods).
Working with Cookies in JavaScript
- Creating Cookies
- Syntax:
document.cookie = "key=value; expires=date; path=path";
- Example:
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
- Explanation:
key=value
: The data to store.expires
: Sets the cookie’s expiration date (optional). If not set, the cookie is a session cookie.path
: Defines the scope of the cookie. Use/
to make it accessible site-wide.
- Reading Cookies
- Syntax:
let allCookies = document.cookie;
- Example:
console.log(document.cookie);
- Cookies are returned as a single string with multiple key-value pairs separated by
;
.
- Deleting Cookies
- To delete a cookie, set its
expires
date to a past date. - Example:
- To delete a cookie, set its
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
- Updating Cookies
- To update a cookie, simply set it again with the same key but new value or properties.
- Example:
document.cookie = "username=JaneDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
Managing Cookies in JavaScript
Since the document.cookie
API has limitations, such as no built-in methods for parsing, developers often write utility functions for easier cookie handling:
Utility Functions
- Set Cookie
function setCookie(name, value, days) {
let expires = "";
if (days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
- Get Cookie
function getCookie(name) {
let nameEQ = name + "=";
let cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
if (cookie.indexOf(nameEQ) == 0) return cookie.substring(nameEQ.length);
}
return null;
}
- Delete Cookie
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
Security Concerns
- HTTP-Only Cookies:
- JavaScript cannot access cookies with the
HttpOnly
flag, making them secure against XSS attacks.
- JavaScript cannot access cookies with the
- Secure Cookies:
- Use the
Secure
flag to send cookies only over HTTPS connections.
- Use the
- SameSite Cookies:
- Control cross-origin cookie sharing to mitigate CSRF attacks.
Alternatives to Cookies
While cookies are useful, other storage mechanisms like LocalStorage and SessionStorage are often preferred for larger data storage or when security and performance are critical.
Conclusion
Cookies are essential for storing small amounts of data directly in the browser. They play a crucial role in session management, user preferences, and tracking. Mastering cookies allows developers to create personalized and secure user experiences. For more tutorials and insights, visit The Coding College.