JavaScript Cookies

Cookies are another method for storing data on the client side, and they are commonly used for things like tracking user sessions, remembering login states, and storing small amounts of data across page reloads and visits. Unlike Local Storage or Session Storage, cookies can be sent back to the server with HTTP requests, making them useful for maintaining server-side sessions.

Desired Outcomes

  • Understand what cookies are and how they are used in web development.
  • Learn how to set cookies in the browser using JavaScript.
  • Learn how to retrieve and manipulate existing cookies.
  • Understand how to delete cookies by setting their expiration date in the past.
  • Explore cookie options such as expires, path, domain, secure, and HttpOnly.
  • Identify security concerns with cookies and how to mitigate risks using Secure and HttpOnly flags.

What are Cookies?

A cookie is a small text file stored on the user's computer by their web browser. Cookies are key-value pairs and can also include options like expiration dates, domain restrictions, and secure flags. They are commonly used for storing user preferences, session tokens, or tracking data.

16.1.1. Setting Cookies

To set a cookie in JavaScript, you simply assign a string to the document.cookie property. Cookies are stored as a string with key-value pairs.

Example: Setting a Cookie

document.cookie = "username=JohnDoe";

In this example, we create a cookie with the name username and the value JohnDoe. By default, this cookie will be deleted when the browser is closed.

Setting Expiration Date for Cookies

To make a cookie persist even after the browser is closed, you can set an expiration date using the expires attribute. This specifies when the cookie should expire.

let date = new Date();
date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // Expires in 7 days
document.cookie = "username=JohnDoe; expires=" + date.toUTCString();

In this example, we set a cookie that expires in 7 days.

Setting Additional Options

You can also include additional options when setting cookies, such as the path, domain, and secure attributes.

  • Path: Specifies the URL path that must be present in the requested resource before the browser sends the cookie.
  • Domain: Specifies which domain can access the cookie.
  • Secure: Ensures the cookie is only sent over HTTPS connections.

Example: Setting a Cookie with Additional Options

document.cookie = "username=JohnDoe; expires=" + date.toUTCString() + "; path=/; domain=.example.com; secure";

This example sets a cookie that is valid for all paths on example.com and will only be sent over secure HTTPS connections.

16.1.2. Getting Cookies

To retrieve a cookie, you can access document.cookie, which returns all cookies in a single string, formatted as key=value pairs, separated by semicolons. Since this returns all cookies, you often need to extract the specific cookie you need.

Example: Getting a Specific Cookie

function getCookie(name) {
    let value = "; " + document.cookie;
    let parts = value.split("; " + name + "=");
    if (parts.length === 2) return parts.pop().split(";").shift();
}

let username = getCookie('username');
console.log(username); // Output: JohnDoe

This function searches for a specific cookie by name and returns its value. If the cookie doesn't exist, it returns undefined.

16.1.3. Deleting Cookies

To delete a cookie, you can set its expires attribute to a past date. Once a cookie's expiration date has passed, it will be automatically deleted by the browser.

Example: Deleting a Cookie

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

This example deletes the username cookie by setting its expiration date to a time in the past. Always ensure you set the path and domain when deleting a cookie, as cookies are path-sensitive.

Limitations and Security Concerns

While cookies are useful, they come with some limitations and potential security risks:

  • Size Limit: Each cookie can only hold up to 4KB of data, and there’s a limit to how many cookies can be stored per domain (typically around 20).
  • Insecure Data: Unless marked with the Secure flag, cookies are sent over both HTTP and HTTPS, potentially exposing sensitive information to attackers. To mitigate this, use the Secure and HttpOnly flags when necessary.
    • Secure Flag: Ensures cookies are only sent over HTTPS.
    • HttpOnly Flag: Prevents JavaScript from accessing cookies, helping to prevent XSS (cross-site scripting) attacks.
// Function to set a cookie
function setCookie(name, value, days) {
    let date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    let expires = "expires=" + date.toUTCString();
    document.cookie = name + "=" + value + "; " + expires + "; path=/";
}

// Function to get a cookie by name
function getCookie(name) {
    let value = "; " + document.cookie;
    let parts = value.split("; " + name + "=");
    if (parts.length === 2) return parts.pop().split(";").shift();
    return null;
}

// Function to delete a cookie
function deleteCookie(name) {
    document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}

// Example usage
setCookie('username', 'JohnDoe', 7); // Set a cookie for 7 days
let username = getCookie('username'); // Retrieve the cookie
console.log(username); // Output: JohnDoe
deleteCookie('username'); // Delete the cookie

Summary

  • Setting Cookies: Use document.cookie to set cookies. You can add options like expiration, path, and security.
  • Getting Cookies: Extract cookies using document.cookie, which returns all cookies in a string. Functions like getCookie help in retrieving specific values.
  • Deleting Cookies: Set a cookie's expiration date to a past date to delete it.

Cookies are an essential tool for maintaining state and storing small pieces of data on the client-side. However, ensure that sensitive data is properly secured by using HTTPS and the appropriate cookie flags (Secure and HttpOnly).

Updated on:

Part of our complete: JavaScript Fundamentals guide

Want exercises and real projects for this lesson? Get the full course.