JS Cookies

Cookies are a way to store small amounts of data on the client side. They are useful for maintaining user sessions, storing preferences, and tracking user activity.

How Cookies Work

1. Setting Cookies:

When a server responds to a request, it can send cookies along with the response. The browser stores these cookies.

The next time the browser sends a request to the same server, it includes the cookies in the request headers, allowing the server to recognize the user and maintain the session.

2. JavaScript and Cookies:

JavaScript can create, read, update, and delete cookies using the document.cookie property.

Creating, Reading, Updating, and Deleting Cookies in JavaScript

Creating a Cookie

To create a cookie, you assign a string to document.cookie with the following syntax:

document.cookie = "name=value; expires=expiration_date; path=/";

name=value: The name-value pair of the cookie.

expires=expiration_date: Optional. The expiration date of the cookie. If omitted, the cookie is a session cookie and will be deleted when the browser is closed.

path=/: Optional. Defines the path within the domain where the cookie is valid.

Example:

document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";

Reading a Cookie

To read a cookie, access document.cookie and parse the string:

Example:

<script>
const cookies = document.cookie.split('; ');
const cookieObject = {};
cookies.forEach(cookie => {
    const [name, value] = cookie.split('=');
    cookieObject[name] = value;
});
document.write(cookieObject.username);
</script>

Updating a Cookie

To update a cookie, simply set it again with the new value. Ensure you include the same name and path to overwrite the existing cookie:

Example:

document.cookie = "username=JaneDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";

Deleting a Cookie

To delete a cookie, set its expiration date to a past date:

Example:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";

Example: Creating, Reading, Updating, and Deleting Cookies

<script>
    // Create a cookie
    document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";

    // Read cookies
    function getCookie(name) {
        const cookies = document.cookie.split('; ');
        const cookie = cookies.find(row => row.startsWith(name + '='));
        return cookie ? cookie.split('=')[1] : null;
    }
    document.write("Username cookie:", getCookie("username")); // Outputs: JohnDoe

    // Update the cookie
    document.cookie = "username=JaneDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
    document.write("Updated username cookie:", getCookie("username")); // Outputs: JaneDoe

    // Delete the cookie
    document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
    document.write("Deleted username cookie:", getCookie("username")); // Outputs: null
</script>