Cookies in JavaScript: Set, Get & Delete Example

⚡ Smart Summary

Cookies in JavaScript store small key and value pairs on the visitor computer so a stateless HTTP connection can remember information. This article explains how to set, read, and delete cookies, describes every cookie attribute, and compares cookies with browser storage alternatives.

  • 🍪 Core Definition: A cookie is a key and value pair saved by the browser and returned automatically with every matching request.
  • ✍️ Write Operation: Assigning to document.cookie adds or replaces one cookie at a time and never erases the others.
  • 📖 Read Operation: Reading document.cookie returns one semicolon separated string, so the required pair must be split out manually.
  • 🗑️ Delete Operation: Setting an expiry date in the past removes a cookie, and the path and domain must match the original values.
  • 🔐 Security Attributes: Secure restricts transmission to HTTPS, HttpOnly blocks script access, and SameSite controls cross-site sending.
  • 📏 Size Limits: Each cookie holds roughly 4 KB and browsers keep about 50 cookies per domain, so large data belongs elsewhere.
  • 💾 Storage Alternatives: localStorage and sessionStorage hold more data and are never attached to network requests.

Cookies in JavaScript

What are Cookies?

A cookie is a piece of data that is stored on your computer to be accessed by your browser. You also might have enjoyed the benefits of cookies knowingly or unknowingly. Have you ever stayed signed in to a site such as Facebook so that you do not have to type your details each and every time you try to log in? If yes, then you are using cookies. Cookies are saved as key/value pairs.

An important clarification: a cookie does not hold your password. It holds a session identifier, which is a random token the server issues after a successful login. The server matches that token to your account, so the password itself never leaves the server.

Why do you need a Cookie?

The communication between a web browser and server happens using a stateless protocol named HTTP. A stateless protocol treats each request independently. So, the server does not keep the data after sending it to the browser. But in many situations, the data will be required again. Here come cookies into the picture. With cookies, the web browser will not have to communicate with the server each time the data is required. Instead, it can be fetched directly from the computer.

Typical uses include remembering a signed-in session, storing a language or theme preference, keeping items in a shopping basket between pages, and counting first-time versus returning visitors.

Javascript Set Cookie

You can create cookies using the document.cookie property like this.

document.cookie = "cookiename=cookievalue"

You can even add an expiry date to your cookie so that the particular cookie will be removed from the computer on the specified date. The expiry date should be set in the UTC/GMT format. If you do not set the expiry date, the cookie will be removed when the user closes the browser.

document.cookie = "cookiename=cookievalue; expires= Thu, 21 Aug 2031 20:00:00 UTC"

You can also set the domain and path to specify to which domain and to which directories in the specific domain the cookie belongs. By default, a cookie belongs to the page that sets the cookie.

document.cookie = "cookiename=cookievalue; expires= Thu, 21 Aug 2031 20:00:00 UTC; path=/ "

//create a cookie with a domain of the current page and a path covering the entire domain.

⚠️ Warning: The expiry date must be in the future. A date that has already passed instructs the browser to delete the cookie immediately, which is exactly the technique used in the delete section below.

JavaScript Get Cookie

You can access the cookie like this, which will return all the cookies saved for the current domain.

var x =  document.cookie

The returned value is a single string in the form name1=value1; name2=value2. There is no built-in method to read one cookie by name, so the string has to be split. The helper below returns a single value and an empty string when the name is absent.

function getCookie(name) {
    const pairs = document.cookie.split(";");
    for (let i = 0; i < pairs.length; i++) {
        const pair = pairs[i].trim();
        if (pair.indexOf(name + "=") === 0) {
            // decode in case the value contained spaces or symbols
            return decodeURIComponent(pair.substring(name.length + 1));
        }
    }
    return "";
}

document.cookie = "username=Ann Smith; path=/";
console.log(getCookie("username"));
console.log(getCookie("missing") === "");

Output:

Ann Smith
true

JavaScript Delete Cookie

To delete a cookie, you just need to set the value of the cookie to empty and set the value of expires to a date that has already passed.

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

One detail causes most failed deletions. The browser identifies a cookie by its name together with its path and domain, so the deletion statement must repeat the same path and domain that were used when the cookie was created.

// created with an explicit path
document.cookie = "theme=dark; path=/; max-age=2592000";

// deletion must repeat that same path
document.cookie = "theme=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";

// max-age=0 achieves the same result in one shorter line
document.cookie = "theme=; path=/; max-age=0";

Cookie Attributes Explained

Every attribute after the first semicolon changes how long the cookie lives, which requests carry it, and which code may read it. The reference below covers all of them.

Attribute Purpose Example
expires Absolute deletion date in UTC format expires=Thu, 21 Aug 2031 20:00:00 UTC
max-age Lifetime in seconds counted from now max-age=2592000
path Directory scope inside the domain path=/
domain Host scope, including subdomains domain=example.com
Secure Sent only over an HTTPS connection Secure
HttpOnly Hidden from document.cookie, set by the server only HttpOnly
SameSite Controls sending on cross-site requests SameSite=Lax

SameSite deserves particular attention because browsers now apply a default. The three accepted values behave as follows.

  • Strict: The cookie is never sent when the request originates from another site, which is the safest setting for banking sessions.
  • Lax: The cookie travels with top-level navigation such as clicking a link, but not with cross-site images or frames. This is the modern browser default.
  • None: The cookie is sent on every cross-site request and must be paired with the Secure attribute, otherwise the browser rejects it.
// a well configured cookie set from client side script
document.cookie = "language=en; path=/; max-age=31536000; SameSite=Lax; Secure";

💡 Tip: The HttpOnly attribute cannot be applied from JavaScript, by design. Only a server response header can set it, and that is what protects session cookies from cross-site scripting attacks.

Try this Example yourself

The script below combines all three operations. It creates a cookie with an expiry measured in days, reads it back by name, and greets a returning visitor. Special instructions to make the code work … Press the run button twice.

<html>
<head>
	<title>Cookie!!!</title>
	<script type="text/javascript">
		function createCookie(cookieName,cookieValue,daysToExpire)
        {
          var date = new Date();
          date.setTime(date.getTime()+(daysToExpire*24*60*60*1000));
          document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
        }
		function accessCookie(cookieName)
        {
          var name = cookieName + "=";
          var allCookieArray = document.cookie.split(';');
          for(var i=0; i<allCookieArray.length; i++)
          {
            var temp = allCookieArray[i].trim();
            if (temp.indexOf(name)==0)
            return temp.substring(name.length,temp.length);
       	  }
        	return "";
        }
		function checkCookie()
        {
          var user = accessCookie("testCookie");
          if (user!="")
        	alert("Welcome Back " + user + "!!!");
          else
          {
            user = prompt("Please enter your name");
            num = prompt("How many days you want to store your name on your computer?");
            if (user!="" && user!=null)
            {
            createCookie("testCookie", user, num);
            }
          }
        }
	</script>
</head>
<body onload="checkCookie()"></body>
</html>

Expected Behaviour:

First run  : "Please enter your name"  -> Ann
             "How many days you want to store your name on your computer?" -> 5
Second run : alert box shows  Welcome Back Ann!!!

Code explanation: The createCookie function converts a number of days into milliseconds and adds them to the current time, which produces the expiry date. The accessCookie function splits the cookie string on semicolons, trims each fragment, and compares the start of the fragment with the requested name. The checkCookie function ties the two together on page load.

⚠️ Warning: The example uses toGMTString(), which is a deprecated alias. New code should call toUTCString() instead, since the deprecated form may eventually be removed from browsers.

Cookies vs localStorage vs sessionStorage

Cookies are not the only place a browser can keep data. Two Web Storage options exist, and choosing correctly avoids sending unnecessary bytes on every request.

Feature Cookie localStorage sessionStorage
Capacity About 4 KB About 5 MB About 5 MB
Sent to the server Yes, with every matching request No No
Lifetime Until the expiry date Until explicitly removed Until the tab closes
Server can write it Yes No No
Accessible across tabs Yes Yes No
Typical use Sessions and authentication Preferences and cached data Single-visit form state

The practical rule is simple. If the server needs the value, use a cookie. If only the page needs it, use localStorage or sessionStorage, because those values never add weight to a network request.

Cookie handling code is usually shared across many pages, so review internal and external JavaScript before deciding where to place it. The string splitting used here builds on JavaScript strings and JavaScript array methods, and further working scripts appear in the practical JavaScript code examples.

FAQs

Roughly 4 KB per cookie, and most browsers keep about 50 cookies for each domain. Larger values should be placed in localStorage or fetched from the server on demand.

Common causes are a past expiry date, a mismatched path, a page opened from the file system rather than a server, or the browser blocking cookies. Check the Application panel in developer tools.

No. HttpOnly cookies are deliberately hidden from document.cookie so that injected scripts cannot steal a session token. Only the server sees them, in the request headers.

First-party cookies belong to the domain in the address bar. Third-party cookies are set by an embedded domain such as an advertiser, and browsers now restrict or block them by default.

Yes. A small cookie usually stores a conversation identifier so the widget can restore the thread on the next visit. The messages themselves are kept on the provider servers.

No. Cookies travel with every matching request and are readable by scripts unless HttpOnly is set. Store only an opaque identifier and keep personal data on the server.

Summarize this post with: