Cookies are small pieces of data stored on the client side that can be accessed and modified by both the client and the server. The `document.cookie` string allows us to include attributes along with the key-value pair.
Cookies are commonly used to store user preferences, session identifiers, and other stateful information across multiple requests.
Here are some common attributes we can use:
we can set cookies using the `document.cookie` property.
// Set a cookie with multiple attributes document.cookie = "username=Alice Collin; expires=Fri, 3 Mar 2023 03:30:30 UTC; path=/home; domain=example.com; secure; HttpOnly";
// Retrieve Cookie or Get Cookie const cookies = document.cookie; console.log(cookies);
we can read the `document.cookie` property, which returns a semicolon-separated string of all cookies.
When retrieving or deleting a cookie, it's important to include the same attributes to ensure that the operation is performed on the correct cookie.
// Parse cookies into an object function parseCookies() { const cookies = document.cookie.split('; ').reduce((acc, cookie) => { const [name, value] = cookie.split('='); acc[name] = value; return acc; }, {}); return cookies; } const cookies = parseCookies(); console.log(cookies);
Cookies can be parsed into an object for easier access.
Specifies the expiration date of the cookie. Once the expiration date is reached, the cookie is automatically deleted.
Example: expires=Fri, 03 Mar 2023 03:30:30 UTC
Specifies the maximum age of the cookie in seconds. The cookie will be automatically deleted after this period.
Example: max-age=3600 (1 hour)
Limits the cookie to a specific domain and its subdomains.
Example: domain=example.com
Specifies the URL path for which the cookie is valid. It limits the cookie to a specific directory or path on the domain.
Example: path=/home
Indicates that the cookie should only be sent over secure, encrypted connections (HTTPS).
Example: secure
Prevents the cookie from being accessed through Javascript, enhancing security by protecting against certain types of cross-site scripting (XSS) attacks.
Example: HttpOnly