Module 13 - Local Storage and Cookies

Introduction

Definition and Purpose

Cookies are small pieces of data stored on the user's device by the web browser. They serve the purpose of persistently storing information that can be retrieved and utilized across different sessions or page visits. The data is typically in the form of key-value pairs, and cookies play a crucial role in maintaining stateful information on the client side.

Small pieces of data stored on the user's device

Cookies are text files that contain small amounts of information. They are stored on the user's device, commonly as text strings. This data is managed by the web browser and sent back and forth between the client and server with each HTTP request, enabling the retention of user-specific information.

Used to store information persistently across sessions

One of the primary purposes of cookies is to persistently store information, ensuring that data remains available even when the user navigates away from a webpage and returns later. This is achieved by setting an expiration date for the cookie.

Examples and Best Practices

Example 1: Creating a Simple Cookie

// Set a cookie with the key "username" and value "John Doe"
document.cookie = "username=John Doe";

Example 2: Reading Cookies

// Retrieve all cookies
const allCookies = document.cookie;

// Parse individual cookies into an object
const cookies = Object.fromEntries(
allCookies.split("; ").map(cookie => cookie.split("="))
);

// Access a specific cookie value
const username = cookies.username;

Best Practice 1: Be Mindful of Size Limitations

Cookies have size limitations (commonly a few kilobytes). Avoid storing large amounts of data in cookies to ensure compatibility and optimal performance.

Best Practice 2: Understand Session vs. Persistent Cookies

Session cookies are temporary and expire when the browser is closed, while persistent cookies have a specified expiration date. Choose the appropriate type based on the data's lifecycle.

In summary, cookies are essential for persistently storing small amounts of information on the client side. They enable web applications to remember user preferences, maintain authentication states, and provide a personalized browsing experience. Understanding their definition, purpose, and best practices is fundamental for anyone learning JavaScript and web development.



Creating Cookies

document.cookie property

The document.cookie property is the primary interface for creating and managing cookies in JavaScript. It allows you to set, read, and modify cookies associated with the current document.

Syntax and format

The document.cookie property is a string that contains a semicolon-separated list of key-value pairs representing individual cookies. Each key-value pair is separated by an equals sign (=).

// Set a cookie with the key "username" and value "John Doe"
document.cookie = "username=John Doe";

Adding key-value pairs

You can add multiple key-value pairs to the document.cookie property by separating them with semicolons.

// Set multiple cookies
document.cookie = "username=John Doe; expires=Thu, 01 Jan 2025 00:00:00 UTC; path=/";
document.cookie = "language=English; max-age=3600; secure";

Set expiration date for cookies

Cookies can have an optional expiration date, determining how long they persist on the user's device.

1. Session cookies vs. persistent cookies

Session Cookies: These cookies are temporary and expire when the browser is closed. They don't have an explicit expiration date.

// Set a session cookie
document.cookie = "sessionCookie=value";

Persistent Cookies: These cookies have a specified expiration date, allowing them to persist beyond the current session.

// Set a persistent cookie (expires on January 1, 2025)
document.cookie = "persistentCookie=value; expires=Thu, 01 Jan 2025 00:00:00 UTC";

Examples and Best Practices

Example 1: Creating a Persistent Cookie

// Set a persistent cookie with the key "user_id" and value "123"
const expirationDate = new Date();
expirationDate.setFullYear(expirationDate.getFullYear() + 1); // Expires in one year
document.cookie = "user_id=123; expires=" + expirationDate.toUTCString();

Example 2: Creating a Session Cookie

// Set a session cookie with the key "visited" and value "true"
document.cookie = "visited=true";

Best Practice 1: Use UTC for Expiration Dates

When setting an expiration date for cookies, it's a best practice to use Coordinated Universal Time (UTC) to ensure consistency across different time zones.

Best Practice 2: Be Explicit About Path

Specify the path for the cookie to ensure it's accessible only on specific pages. If not specified, the cookie will be associated with the current page's path by default.

Understanding how to create cookies using document.cookie and setting appropriate expiration dates is crucial for managing user data effectively in web applications. Always consider the lifespan of the information you are storing and follow best practices to enhance the security and efficiency of your cookie management.



Reading Cookies

Accessing cookies using document.cookie

To read cookies, you can access the document.cookie property, which contains a semicolon-separated string of all the cookies associated with the current document.

Retrieving all cookies

const allCookies = document.cookie;

This code retrieves all cookies as a single string. The string contains key-value pairs separated by semicolons.

Parsing individual cookies

To work with individual cookies, you can parse the string into an object.

const cookies = Object.fromEntries(
allCookies.split("; ").map(cookie => cookie.split("="))
);

Here, the split method is used to separate each key-value pair. The resulting array is then transformed into an object using Object.fromEntries.

Examples and Best Practices

Example 1: Retrieving All Cookies

// Get all cookies
const allCookies = document.cookie;
console.log(allCookies);

Example 2: Parsing Individual Cookies

// Parse individual cookies into an object
const cookies = Object.fromEntries(
document.cookie.split("; ").map(cookie => cookie.split("="))
);
console.log(cookies);

Best Practice 1: Handle Empty Cookies

Before parsing cookies, ensure that there are cookies to parse. If document.cookie is empty, attempting to split it will result in unexpected behavior.

const allCookies = document.cookie.trim();
if (allCookies !== "") {
const cookies = Object.fromEntries(
allCookies.split("; ").map(cookie => cookie.split("="))
);
console.log(cookies);
} else {
console.log("No cookies found.");
}

Best Practice 2: Decoding Cookie Values

Cookie values are URL-encoded. When retrieving values, it's essential to decode them using decodeURIComponent to handle special characters.

const username = cookies.username ? decodeURIComponent(cookies.username) : null;
console.log(username);

Reading cookies is a fundamental part of working with client-side data. By understanding how to access and parse cookies using document.cookie, developers can retrieve and utilize stored information. Be mindful of empty cookies, decode values when necessary, and use this knowledge to build dynamic and personalized web experiences.



Modifying Cookies

Updating cookie values

Once a cookie is set, you can update its value by reassigning a new value to the document.cookie property.

// Update the value of the "username" cookie
document.cookie = "username=New Value";

This will effectively overwrite the existing value of the "username" cookie.

Changing expiration dates

You can modify the expiration date of a cookie to control how long it persists on the user's device.

// Change the expiration date of the "sessionCookie" to 1 hour from now
const expirationDate = new Date();
expirationDate.setTime(expirationDate.getTime() + 60 * 60 * 1000); // 1 hour in milliseconds
document.cookie = "sessionCookie=value; expires=" + expirationDate.toUTCString();

Deleting cookies

To delete a cookie, you can set its expiration date to a time in the past. This instructs the browser to remove the cookie.

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

Setting expiration to the past

By setting the expiration date to a time in the past (commonly the epoch), the browser interprets the cookie as expired and removes it.

Examples and Best Practices

Example 1: Updating Cookie Value

// Assume we have an existing "counter" cookie
const currentCounter = parseInt(cookies.counter) || 0;

// Increment the counter and update the cookie
document.cookie = "counter=" + (currentCounter + 1);

Example 2: Changing Expiration Date

// Extend the expiration date of the "sessionToken" cookie to 1 day from now
const expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + 1); // 1 day in the future
document.cookie = "sessionToken=value; expires=" + expirationDate.toUTCString();

Example 3: Deleting a Cookie

// Delete the "language" cookie
document.cookie = "language=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Best Practice 1: Be Explicit About Path and Domain

When modifying or deleting cookies, be explicit about the path and domain to ensure consistency and avoid unexpected behavior.

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=example.com;";

Best Practice 2: Update Cookies Securely

When modifying or updating cookies containing sensitive information, use secure connections (HTTPS) to protect data during transmission.

document.cookie = "secureCookie=value; secure;"; // This cookie will only be sent over HTTPS connections

Understanding how to update, modify, and delete cookies is essential for maintaining accurate and secure client-side data. Practicing caution, being explicit about paths and domains, and utilizing secure practices ensure the effective management of cookies in a web application.

Videos for Module 13 - Local Storage and Cookies

Key Terms for Module 13 - Local Storage and Cookies

No terms have been published for this module.

Quiz Yourself - Module 13 - Local Storage and Cookies

Test your knowledge of this module by choosing options below. You can keep trying until you get the right answer.

Skip to the Next Question