Browser Cookies Syntax Information
Browser cookies are small pieces of data stored on a user's device by websites to remember information about the user. Cookies are commonly used for various purposes, such as tracking user sessions, storing user preferences, and collecting analytics data. The syntax for creating and managing cookies in web development involves using JavaScript and interacting with the document.cookie object.
Here's a basic overview of the syntax for working with cookies in JavaScript:
Setting a Cookie:
To set a cookie, you use the following syntax:
document.cookie = "name=value; expires=date; path=path; domain=domain; secure";
name=value: The key-value pair representing the data you want to store.
expires=date: Optional. Sets the expiration date of the cookie. If not provided, the cookie is considered a session cookie.
path=path: Optional. Specifies the path for which the cookie is valid.
domain=domain: Optional. Specifies the domain for which the cookie is valid.
secure: Optional. If present, the cookie will only be sent over secure (HTTPS) connections.
Example:
document.cookie = "username=John Doe; expires=Thu, 01 Jan 2025 00:00:00 UTC; path=/; domain=example.com; secure";
Getting a Cookie:
To retrieve a cookie, you can read the document.cookie property, which returns a semicolon-separated string containing all cookies for the current document.
Example:
let allCookies = document.cookie;
Parsing Cookies:
If you want to work with a specific cookie value, you can parse the document.cookie string to extract the desired value.
Example:
function getCookieValue(cookieName) {
const cookies = document.cookie.split("; ");
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].split("=");
if (cookie[0] === cookieName) {
return cookie[1];
}
}
return null;
}
let username = getCookieValue("username");
Deleting a Cookie:
To delete a cookie, you can set its expiration date to a past date.
Example:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=example.com; secure";
Keep in mind that working directly with document.cookie can be a bit manual and error-prone, and many developers prefer using JavaScript libraries or frameworks that provide higher-level abstractions for working with cookies.