Cookies are one of the most important web technologies. A cookie is a small piece of data from a specific website that is stored in the browser so that the same site can access and use the information at a later stage.
When a specific user returns to a site, that same cookie provides information and allows the site to display specific settings or content for that user.
For example, cookies can store information such as items in a shopping cart, usernames and passwords for forms, and more. Advertisers use cookies to track the activity of users across different websites in order to display targeted advertisements.
Although this method is intended to provide users with a more personalized web experience, some view it as a privacy concern. This is why most websites now display a consent banner requesting permission to use cookies, regardless of the visitor’s location:

The Basics of Browser Cookies
When a browser requests a web page from a server, the cookies associated with that page are added to the request. This allows the server to receive the necessary information to remember details about users.
Cookies are essentially pieces of data that contain fields like name and value, along with several optional parameters. The values of these fields are strings in which you can store any text you want, according to the needs of your application or website. Cookies are stored as key & value pairs, for example:
username = John DoeOne common cookie, such as Google Analytics’ cookie, is named _ga and is one of the most widely used cookies. In GA4, it typically looks like this:
- Name: _ga
- Value: GA1.1.1197596843.1673515099
- Domain: .example.com
- Path: /
- Expires / Max-Age: 2 years (effectively ~13 months due to browser policies)
The value breaks down as: version (GA1), domain level (1), a random client ID, and the timestamp when the cookie was created.
You can store up to 4096 bytes of data in a cookie. The number of cookies allowed per domain varies among browsers – Chrome allows up to 180, Firefox up to 150, and Safari and Edge up to 50.
A. Creating a Cookie with JavaScript
With JavaScript, you can create, read, and delete cookies using the document.cookie property. For example, you can create a cookie like this:
document.cookie = "username=John Doe";You can also add an expiration date to a cookie (in UTC time). By default, cookies are deleted when the browser is closed:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2025 12:00:00 UTC";A more modern approach is to use max-age, which sets the lifetime in seconds. This is often easier to work with than calculating a UTC date string:
// Cookie expires in 7 days (7 * 24 * 60 * 60 = 604800 seconds)
document.cookie = "username=John Doe; max-age=604800";Using the path parameter, you can specify to which path or page the cookie belongs. By default, a cookie belongs to the current page:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/";B. Reading Cookies with JavaScript
You can read cookies using JavaScript like this:
let x = document.cookie;Using document.cookie will return all cookies as a string: cookie1=value; cookie2=value; cookie3=value;
C. Modifying Cookies with JavaScript
You can modify cookies using JavaScript similarly to how you create them. In this case, the old cookie will be overwritten by the new one you create:
document.cookie = "username=John Smith; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/";D. Deleting Cookies with JavaScript
Deleting a cookie is straightforward – you don’t need to provide the cookie’s value. Just set the expires parameter to a date that has already passed:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";Make sure to specify the correct path to ensure you’re deleting the right cookie. Certain browsers won’t allow you to delete a cookie if you don’t specify the path.
E. Cookie String Representation
The document.cookie property looks like a regular text string, but it’s not. Even if you write the entire cookie string to document.cookie, when you read it, you’ll only get the name-value pairs.
If you set a new cookie, old cookies won’t be deleted. The new cookie will be appended to document.cookie, so if you read document.cookie again, you’ll get something like:
cookie1 = value; cookie2 = value;For the purpose of understanding cookie string representation, use the buttons below to create, display, and delete cookies.
If you want to find the value of a specific cookie, you need to create a JavaScript function that searches for the value within its string.
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 with top-level navigations and GET requests from third-party sites. This is the default in modern browsers.None– The cookie is sent with all requests, including cross-site. Requires theSecureattribute.
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 domain you are visiting directly. For example, if you visit example.com, any cookie set by example.com is first-party. These are used for login sessions, preferences, and analytics.
A third-party cookie is set by a domain other than the one you are visiting – typically by ads, social media widgets, or tracking scripts embedded on the page. For example, an ad network running on example.com might set a cookie under adnetwork.com.
Third-party cookies have been the backbone of cross-site tracking and retargeting for years. However, browsers are increasingly restricting them. Safari and Firefox already block third-party cookies by default. Chrome began restricting them for a percentage of users in 2024 as part of the Privacy Sandbox initiative, with broader restrictions planned.
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
In the following example, we’ll create a cookie that stores the visitor’s name on the website. The first time the visitor arrives on the page, they will be prompted to enter their name, and that name will be stored in a cookie. The next time the user visits the page, they will receive a “Welcome Roee” message.
For the example, we will create three JavaScript functions:
- A function to set the value of the cookie.
- A function to read the value of the cookie.
- A function to check the value of the cookie.
These functions and the code below were taken and adapted from this source.
1. Function to Set a Cookie
First, we’ll create a function that sets the user’s name in a cookie:
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
let expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}The parameters of this function are the cookie name (cname), the cookie value (cvalue), and the number of days until the cookie expires (exdays).
The function sets the cookie by concatenating the cookie name, value, and the expiration text.
2. Function to Read a Cookie
Now, we’ll create a function that returns the value of a specific cookie:
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}This function takes a cookie name, appends = to it, then loops through all cookies (split by ;) and trims whitespace from each one. When it finds a cookie that starts with the target name, it returns the value portion. If no match is found, it returns an empty string.
3. Function to Check a Cookie
The final function checks if the cookie is defined. If it is, it displays a welcome message; if not, it prompts the user to enter their name and stores it in a cookie for 365 days using the setCookie function we defined earlier:
function checkCookie() {
let username = getCookie("username");
if (username != "") {
alert("Welcome again " + username);
} else {
username = prompt("Please enter your name:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
}
}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+, Firefox 138+, Safari 18.5+, Edge 87+) 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:
SameSite attribute controls whether a cookie is sent with cross-site requests. Strict only sends the cookie in first-party context, Lax (the default) also sends it on top-level navigations, and None sends it with all requests but requires the Secure flag. It helps protect against CSRF attacks.document.cookie?
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.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.Summary
Cookies remain a fundamental part of web development. The document.cookie API lets you create, read, modify, and delete cookies directly from JavaScript. For new projects, the Cookie Store API offers a cleaner, asynchronous alternative.
When working with cookies, always consider security: use SameSite, Secure, and HttpOnly attributes where appropriate, and be mindful of the ongoing shift away from third-party cookies. For further reading and inspiration, check out these resources:


Thanks, Very Helpful & Nice Blog!