JavaScript & Internet Cookies: Developers Essential Practices

Cookies are one of the most important web technologies. A cookie is a small piece of data that a website stores in your browser, so the site can remember you on your next visit: a login session, a shopping cart, a language preference. Advertisers also use cookies to follow people across sites, which is why most websites now ask for consent before setting them:

Cookie settings dialog with Necessary always on, optional cookies off, and Reject all next to Accept all

If you only need the code, here is how to set, read and delete a cookie in three lines:

document.cookie = "theme=dark; max-age=31536000; path=/"; // set (1 year)
const theme = document.cookie.match(/(?:^|; )theme=([^;]*)/)?.[1]; // read
document.cookie = "theme=; max-age=0; path=/"; // delete

The rest of this guide explains each part.

The Basics of Browser Cookies

Every time the browser requests a page, it sends that site’s cookies along with the request. That is how the server remembers you between visits.

Each cookie is a name and value pair, plus a few optional attributes, such as when it expires and which pages can read it:

username = John Doe

For example, Google Analytics stores a random ID for your browser in a cookie named _ga and keeps it for up to 2 years (Chrome caps every cookie at 400 days). A cookie’s name and value can take up to 4096 bytes together, and Chrome, Edge and Firefox allow up to 180 cookies per domain.

Here are the cookies this site has stored in your browser right now:

The cookies this site stored on your device

This demo needs JavaScript.

A. Creating a Cookie with JavaScript

You create a cookie by assigning a string to document.cookie:

document.cookie = "username=John Doe; max-age=604800; path=/"; // 7 days
  • max-age sets the lifetime in seconds. Without it, the cookie is deleted when the browser closes.
  • The older expires attribute does the same with a UTC date in the future, such as expires=Fri, 31 Dec 2027 12:00:00 UTC.
  • path=/ makes the cookie available across the whole site. Without it, the cookie belongs to the current page’s directory only.

B. Reading Cookies with JavaScript

Reading document.cookie returns all the page’s cookies in one string:

document.cookie; // "theme=dark; username=John Doe"

It is not the string you wrote. You only get the name and value pairs back, never max-age or path. And setting a new cookie adds it to the string, without removing the others.

Try it: save, overwrite and delete cookies, and compare what you wrote with what document.cookie returns. Every cookie here starts with demo_, so the site’s own cookies stay untouched.

Cookie lab: set, read and delete

This demo needs JavaScript.

C. Updating and Deleting Cookies with JavaScript

To update a cookie, set it again with the same name. To delete it, set it again with max-age=0:

document.cookie = "username=John Smith; max-age=604800; path=/"; // update
document.cookie = "username=; max-age=0; path=/"; // delete

Use the same path and domain as when you created the cookie. If they don’t match, the browser treats it as a different cookie and the original stays. Google Analytics, for example, usually sets _ga with a domain attribute, so a delete without that same attribute leaves it in place.

Get a Cookie by Name

Since document.cookie returns every cookie in one string, reading a single cookie means splitting that string and finding the right pair:

function getCookie(name) {
  const row = document.cookie
    .split("; ")
    .find((row) => row.startsWith(name + "="));
  return row ? decodeURIComponent(row.slice(name.length + 1)) : null;
}

getCookie("theme"); // "dark", or null if there is no such cookie

Matching on name + "=" means a cookie called xtheme won’t match theme. And slice() keeps the whole value, even when it contains an = sign.

decodeURIComponent reverses encodeURIComponent, which you should use when storing a value that contains spaces, semicolons or commas.

With the Cookie Store API covered below, the same lookup is one line: (await cookieStore.get("theme"))?.value. It returns the raw value, so decode it yourself if you encoded it.

List All Cookies

To see every cookie the page can access, turn the string into an object:

const cookies = Object.fromEntries(
  document.cookie
    .split("; ")
    .filter(Boolean)
    .map((row) => {
      const i = row.indexOf("=");
      return [row.slice(0, i), row.slice(i + 1)];
    })
);

console.table(cookies);

filter(Boolean) handles a page with no cookies, where document.cookie is an empty string. The values come back exactly as stored, so run decodeURIComponent on the ones you encoded.

With the Cookie Store API, await cookieStore.getAll() returns the same list as an array of objects with name and value properties.

Neither method shows HttpOnly cookies or cookies set for a different path or domain. To see all of them, open Chrome DevTools and go to Application > Storage > Cookies.

Cookie Security Attributes

When working with cookies, especially those that store sensitive data like session tokens, you should be aware of the security attributes available. These attributes help protect against common attacks like cross-site scripting (XSS) and cross-site request forgery (CSRF).

SameSite – Controls whether a cookie is sent with cross-site requests. It accepts three values:

  • Strict – The cookie is only sent in a first-party context (same site). This is the most secure option.
  • Lax – The cookie is sent when a user follows a link to your site from another site, but not with cross-site requests such as images, iframes or fetch calls. Chrome and Edge use it as the default when no SameSite is set. Firefox and Safari don’t.
  • None – The cookie is sent with all requests, including cross-site. Requires the Secure attribute.

Secure – Ensures the cookie is only transmitted over HTTPS. Always use this for cookies containing sensitive data.

HttpOnly – Prevents JavaScript from accessing the cookie via document.cookie. This is set on the server side and is critical for session cookies, as it prevents XSS attacks from stealing them.

Here is an example of setting a cookie with security attributes via JavaScript:

document.cookie = "theme=dark; max-age=2592000; path=/; SameSite=Lax; Secure";

You cannot set the HttpOnly flag from JavaScript – it can only be set by the server in the Set-Cookie HTTP header. This is by design: HttpOnly cookies are invisible to document.cookie, which is exactly what makes them secure against XSS. For security headers and session management, always set HttpOnly on the server side.

First-Party vs Third-Party Cookies

A first-party cookie is set by the site you are visiting, like a login session on example.com. A third-party cookie is set by another domain whose content is embedded on the page, such as an ad network or a social widget. That is how ads follow people from site to site.

A page’s JavaScript can only read and delete its own site’s cookies, so it cannot remove third-party cookies. Visitors do that in their browser settings.

Safari has blocked third-party cookies by default since 2020, and Firefox gives each site its own cookie jar (Total Cookie Protection). Chrome still allows them: in April 2025 Google dropped its plan to phase them out, and in October 2025 it retired most Privacy Sandbox APIs, keeping CHIPS and FedCM.

If your site relies on third-party cookies for functionality (e.g., embedded payment forms, federated login), test thoroughly and consider alternatives like the Storage Access API or partitioned cookies (CHIPS).

Example – JavaScript Cookie

Here is a complete example. The site asks for the visitor’s name once, saves it in a cookie, and greets them on every visit after that. It uses the getCookie() function from above:

// <form id="name-form"><input name="name"><button>Save</button></form>
// <p id="greeting"></p>
const form = document.querySelector("#name-form");
const greeting = document.querySelector("#greeting");
const saved = getCookie("username");

if (saved) {
  greeting.textContent = `Welcome back, ${saved}!`;
  form.hidden = true;
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const value = form.elements.name.value.trim();
  if (!value) return;
  document.cookie = `username=${encodeURIComponent(value)}; max-age=31536000; path=/`;
  greeting.textContent = `Hi, ${value}! See you next time.`;
  form.hidden = true;
});

Try the same idea here. Save your name, reload the page, then delete the cookie and watch the site forget you:

Does the site remember you?

This demo needs JavaScript.


If you want to see a real-world example of using cookies with JavaScript to control when a popup appears, check out this guide on creating a popup in WordPress using JavaScript cookies.

The Cookie Store API

The traditional document.cookie API is synchronous, which means it blocks the main thread every time you read or write a cookie. For most use cases this is fine, but in performance-sensitive applications it can be a concern.

The Cookie Store API (cookieStore) is a modern, asynchronous alternative that reached Baseline status in 2025. It provides a cleaner, Promise-based interface:

// Set a cookie
await cookieStore.set("theme", "dark");

// Get a cookie
const cookie = await cookieStore.get("theme");
console.log(cookie.value); // "dark"

// Delete a cookie
await cookieStore.delete("theme");

// Listen for cookie changes
cookieStore.addEventListener("change", (event) => {
  console.log("Changed cookies:", event.changed);
  console.log("Deleted cookies:", event.deleted);
});

The Cookie Store API is available in all major browsers (Chrome 87+, Edge 87+, Firefox 140+, Safari 18.4+) and works only in secure contexts (HTTPS). It also works in Service Workers, which document.cookie does not.

The Cookie Store API is a great choice for new projects, but document.cookie remains perfectly valid and is supported everywhere. If you need to support older browsers or are working with existing code, there is no rush to migrate.

FAQs

Common questions about JavaScript cookies:

What is the difference between cookies and localStorage?
Cookies are sent with every HTTP request to the server, have a 4KB size limit, and can have an expiration date. localStorage stores up to 5-10MB of data, persists until explicitly cleared, and is only accessible via JavaScript (never sent to the server). Use cookies when the server needs the data (e.g., session tokens), and localStorage when only the client needs it (e.g., UI preferences).
What does the SameSite attribute do?
The SameSite attribute controls whether a cookie is sent with cross-site requests. Strict only sends the cookie in first-party context, Lax (the default in Chrome and Edge) also sends it when a user follows a link from another site, and None sends it with all requests but requires the Secure flag. It helps protect against CSRF attacks.
Why can't I access some cookies with document.cookie?
Cookies with the HttpOnly flag are invisible to JavaScript. This is a security measure to prevent XSS attacks from stealing sensitive cookies like session tokens. These cookies can only be set and read by the server via HTTP headers.
How many cookies can a website set?
Chrome, Edge and Firefox allow up to 180 cookies per domain. A cookie's name and value together can take up to 4096 bytes, and attributes such as path and domain are limited separately, to 1024 bytes each.
Should I use expires or max-age for cookie expiration?
max-age is generally easier to work with because you specify the lifetime in seconds (e.g., max-age=86400 for one day) rather than calculating a UTC date string. Both are supported in all modern browsers. If both are set, max-age takes precedence.
Are third-party cookies still supported?
Safari blocks them by default, and Firefox isolates them per site. Chrome still allows them: Google dropped its plan to phase them out in April 2025. If your site depends on third-party cookies, test for breakage and consider alternatives like the Storage Access API, partitioned cookies (CHIPS), or server-side solutions.

Summary

The document.cookie API lets you set, read, update and delete cookies from JavaScript, and the Cookie Store API is a cleaner, asynchronous alternative for new projects. For anything sensitive, use SameSite and Secure, and set HttpOnly on the server. Further reading:

Discussion
[  1 Comments  ]
  • Brian
    Brian 3 September 2023, 3:25

    Thanks, Very Helpful & Nice Blog!

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!