Cookies

Cookies are small pieces of data stored on the user's device, typically in the form of key-value pairs and that can be accessed and modified by both the client and the server.

Working with cookies in Javascript involves using the "document.cookie" property, which allows us to "create", "read", and "delete cookies".

They are often used for storing user preferences, session information, and other small pieces of data.

Here's an overview of working with cookies in JavaScript:

Setting Cookies:

To set a cookie, we assign a string to "document.cookie".

The string should contain the key-value pair and any optional attributes like "expiration date", "path", and "domain".

Example:

document.cookie = "username=Alice Collin; expires=Fri, 03 Mar 2023 03:03:30 UTC; path=/";

a cookie named "username" with the value "Alice Collin" is set. It also has an expiration date and a specific path ("/") indicating that the cookie is accessible on the entire domain.

Retrieve Cookie or Get Cookie:

Example:

// 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.

Example:

// 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);

Parsing Cookies:

Cookies can be parsed into an object for easier access.

Expires:

  • 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

Max-Age:

  • Specifies the maximum age of the cookie in seconds. The cookie will be automatically deleted after this period.

  • Example: max-age=3600 (1 hour)

Domain:

  • Limits the cookie to a specific domain and its subdomains.

  • Example: domain=example.com

Path:

  • 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

Secure:

  • Indicates that the cookie should only be sent over secure, encrypted connections (HTTPS).

  • Example: secure

HttpOnly:

  • Prevents the cookie from being accessed through Javascript, enhancing security by protecting against certain types of cross-site scripting (XSS) attacks.

  • Example: HttpOnly