Cookies: document.cookie In JavaScript

Cookies: document.cookie In JavaScript


In JavaScript, cookies are small pieces of data stored in the user's browser that can be used to store information such as user preferences, login sessions, or other details that should persist across page reloads. The document.cookie property is used to read, set, and manage cookies in the browser.

Working with Cookies: document.cookie

The document.cookie property allows you to access and manipulate cookies associated with the current document. However, cookies are stored as a single string of key-value pairs, separated by semicolons.

Basic Syntax

document.cookie = "key=value"; // Setting a cookie
  • To read cookies, just access document.cookie.
  • To set cookies, assign a string to document.cookie.

Setting Cookies

When setting a cookie, you can specify the following options:

  1. key=value: The name and value of the cookie.
  2. expires: The expiration date of the cookie.
  3. max-age: The maximum age (in seconds) from the time the cookie is set.
  4. path: The path for which the cookie is valid.
  5. domain: The domain that can access the cookie.
  6. secure: Ensures the cookie is sent over HTTPS only.
  7. SameSite: Controls cross-site cookie behavior (e.g., Strict, Lax, None).

Basic Cookie Example

document.cookie = "username=JohnDoe";

This sets a simple cookie with the name username and value JohnDoe.

Setting Cookies with Expiration Date

To set a cookie that expires after a certain date, use the expires attribute:

const date = new Date(); date.setMinutes(date.getMinutes() + 10); // Set expiry to 10 minutes from now document.cookie = "username=JohnDoe; expires=" + date.toUTCString();

This sets the cookie to expire 10 minutes from the current time.

  • The expires value must be in UTC string format (e.g., Wed, 21 Oct 2025 07:28:00 GMT).

Setting Cookies with Max-Age

Alternatively, you can use the max-age attribute to specify the lifetime of the cookie in seconds. For example, setting a cookie to expire after 1 hour:

document.cookie = "username=JohnDoe; max-age=3600"; // Expires in 1 hour (3600 seconds)
  • The max-age attribute takes precedence over the expires attribute.

Setting Cookies with Path

By default, cookies are available only to the current path (the directory of the document). To make the cookie available across the entire site, set the path attribute:

document.cookie = "username=JohnDoe; path=/"; // Cookie available to the entire site

Setting Cookies with Secure and SameSite

To improve security, you can add the secure and SameSite attributes:

  • secure: Ensures that the cookie is only sent over HTTPS.
  • SameSite: Prevents the cookie from being sent in cross-site requests.

Example: Using Secure and SameSite

document.cookie = "username=JohnDoe; secure; SameSite=Strict";

This cookie will only be sent over HTTPS connections, and will not be sent in cross-site requests.

Valid Values for SameSite:

  • Strict: The cookie will only be sent in first-party contexts (i.e., not sent with requests initiated by third-party websites).
  • Lax: The cookie is sent with top-level navigations and will be sent along with GET requests initiated by third-party websites (less strict than Strict).
  • None: The cookie will be sent with cross-site requests, but it requires the cookie to be marked as secure.

Reading Cookies

To read cookies, simply access the document.cookie property. This will return a string containing all cookies for the current page, formatted as key-value pairs separated by semicolons:

console.log(document.cookie); // "username=JohnDoe; sessionID=abc123"

To extract individual cookies, you can split the document.cookie string into an array and then search for the desired cookie:

const cookies = document.cookie.split(';'); let username = ""; cookies.forEach(cookie => { const [key, value] = cookie.trim().split('='); if (key === "username") { username = value; } }); console.log(username); // "JohnDoe"

Deleting Cookies

To delete a cookie, you can set its expires date to a past date. This will invalidate the cookie:

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

This effectively deletes the username cookie.

Example: Full Cookie Operations

// Setting a cookie document.cookie = "username=JohnDoe; max-age=3600; path=/; secure; SameSite=Strict"; // Reading cookies console.log(document.cookie); // "username=JohnDoe" // Deleting a cookie document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT"; // Verifying deletion console.log(document.cookie); // ""

Important Notes:

  1. Cookie Size Limit: Cookies are limited in size, usually around 4 KB (kilobytes).
  2. Domain and Path: Cookies are sent to the server based on the domain and path that match the current document's location.
  3. Third-Party Cookies: Cookies set by other domains (e.g., advertising or analytics scripts) are often blocked by default in modern browsers for privacy reasons.
  4. Access Restrictions: JavaScript can only access cookies that belong to the same domain and path as the current page (unless SameSite=None is used).

Summary

  • The document.cookie property is used to manage cookies in JavaScript.
  • You can set cookies with attributes like expires, max-age, path, secure, and SameSite.
  • Reading cookies is done by accessing document.cookie, but you need to parse the string to get individual cookies.
  • Deleting cookies is done by setting the expires date to a past value.
Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close