How to Set Cookies With JavaScript

Ready to become a JavaScript cookie monster? Let’s get those cookies set and show the browser who’s boss.

Published Categorized as JavaScript

One of the great things about JavaScript is that, as a scripting language invented specifically for web development, it has native support for almost all of the interfaces in a web browser — including cookies.

Cookies are tiny text files that a website can store on the user’s browser. As long as the user hasn’t blocked cookies and doesn’t clear them, the website can access their contents during the current browsing session, and very often in subsequent sessions, too.

How to Set a Cookie in JavaScript

To set a cookie in JavaScript, you can use the document.cookie property:

document.cookie

Cookies are made up of key-value pairs, where the key and the value are separated by the equals sign (=).

document.cookie = "username=johndoe"

Alternatively, you can use the setCookie() function to set a cookie in JavaScript:

setCookie("username", "johndoe", "Thu, 1 Jan 2023 12:00:00 UTC");

What’s the difference between document.cookie and setCookie(), you might be wondering?

document.cookie is a property of the document object in JavaScript, that allows you to read, write, and delete cookies. It is a string containing all the cookies for the current page.

setCookie() is a custom function which can be created by you — the website’s developer — to set a cookie in JavaScript. The function takes the name, value, and expires date of the cookie as arguments, and sets the cookie by creating a string containing the key-value pairs and the expires date, and then setting the document.cookie property to that string.

If you don’t set an expires date for your cookie as the third parameter in your setCookie() function, it will be set as a session cookie, which gets deleted after the user closes the browser or tab.

The advantage to setCookie() is that, as a function, you can parametrize and/or reuse it as you wish. Below is an example:

function setCookie(cookieName, cookieValue, expiryDate) {
  var d = new Date();
  d.setTime(d.getTime() + (expiryDate*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = cookieName + "=" + cookieValue + "; " + expires + "; path=/";
}

How to Verify That a Cookie Is Set

There are a few methods for verifying that a cookie is set:

Using Your Browser’s Developer Tools

The first method is to use the browser’s developer tools to inspect the cookies stored in the browser.

Google Chrome:

  1. Right-click on the page and select “Inspect” or press Ctrl + Shift + I on Windows or Cmd + Opt + I on Mac.
  2. Select the “Application” tab on the developer tools.
  3. In the left sidebar, expand the “Cookies” section under “Storage”.
  4. Select the domain you want to inspect.
  5. The cookies for the domain will be listed in the right pane.

Mozilla Firefox:

  1. Right-click anywhere on the page and select “Inspect Element” or press Ctrl + Shift + I on Windows or Cmd + Opt + I on Mac.
  2. Select the “Storage” tab on the developer tools.
  3. Select “Cookies” from the left sidebar.
  4. The cookies for the domain will be listed in the right pane.

Safari:

  1. Click on “Develop” in the top menu bar, then select “Show Web Inspector” or press Cmd + Opt + I on Mac.

Using JavaScript

You can also use JavaScript to check if a specific cookie exists and retrieve its value.

You can use JavaScript to check if a specific cookie exists and retrieve its value by using the getCookie(name) function, where name is the name of the cookie you want to check.

Here’s an example of how you can check if a cookie named “username” exists:

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

var username = getCookie("username");
if (username) {
  console.log("Cookie 'username' exists with value: " + username);
} else {
  console.log("Cookie 'username' does not exist");
}

Inspect the Headers of an HTTP Response

Finally, you can check the headers of an HTTP response or request to see if the Set-Cookie header is present — and it contains the desired cookie.

You can check the headers of an HTTP response or request to see if the Set-Cookie header is present and contains the desired cookie by using the XMLHttpRequest object in JavaScript. Here is an example of how you can check if a cookie named “username” is present in the headers of an HTTP response:

var xhr = new XMLHttpRequest();
xhr.open("GET", "example.com", true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    var headers = xhr.getAllResponseHeaders();
    if (headers.indexOf("Set-Cookie: username=") !== -1) {
      console.log("Cookie 'username' is present in the headers");
    } else {
      console.log("Cookie 'username' is not present in the headers");
    }
  }
};
xhr.send();

This code creates a new XMLHttpRequest object and opens a GET request to example.com. It then listens for the onreadystatechange event, which is fired when the request’s status and ready state change. When the request is complete and the status is 200, it gets the headers of the response and checks if the Set-Cookie header is present.

What Can I Store in a Cookie?

You can generally store any text-based information you want in a cookie, as long as you remember that it will be saved as a string.

Keep in mind that the use of cookies is subject to data protection regulations, including the GDPR in European Union member states and CCPA in the state of California. Also, the user may choose to block or delete them from their browser.

This means that non-string data types, such as numbers or booleans, will be converted to strings when stored in a cookie. And you’ll need to convert them back to their original data type if you want to use them as such after retrieving them from a cookie.

But let’s not get carried away, because in this post, we’re focusing on setting cookies rather than getting the information that’s stored in them.

What Attributes Can a Cookie Have?

When setting a cookie in JavaScript, you can also specify the following additional attributes for that cookie:

  • expires for the date and time when the cookie should expire. If this attribute is not set, the cookie will be deleted immediately when the user closes the browser or tab.
  • path for the URL path for which the cookie should be sent back to the server. If this attribute is not set, the cookie will be sent back to the server for any URL path under the domain that set the cookie.
  • domain for the domain for which the cookie should be sent back to the server. If this attribute is not set, the cookie will be sent back to the server for the same domain that set the cookie.
  • secure for a boolean value indicating that the cookie should only be sent back to the server over a secure (HTTPS) connection.
  • httpOnly for a boolean value indicating that the cookie should not be accessible to client-side JavaScript. This can help prevent cross-site scripting (XSS) attacks.

All these attributes are optional, and you set them by concatenating them to the document.cookie property like so:

document.cookie = "username=johndoe; expires=Thu, 1 Jan 2023 12:00:00 UTC; path=/; domain=example.com; secure; HttpOnly";

Cookies are supposed to be small — their size is limited to 4KB in most of the browsers.

How to Update a Cookie in JavaScript

In JavaScript, you can update a cookie by setting its value again with the new value.

You can do this by setting the document.cookie property to the new key-value pair for the cookie, including the same attributes such as the expires date and path, as the original cookie.

For example, the JavaScript code snippet below will update the username=johndoe cookie to username=janedoe:

document.cookie = "username=janedoe; expires=Thu, 1 Jan 2023 12:00:00 UTC; path=/; domain=example.com; secure; HttpOnly";

If you don’t set the same expires date for a cookie, the original expires date of the cookie will be overridden, and the cookie will get deleted as soon as the user closes the browser or tab. This is known as a session cookie.

Questions & Answers

What does the semicolon do in a cookie?

When setting a cookie in JavaScript, you can use the semicolon (;) character to separate the different attributes of that cookie. Each attribute, such as the key-value pairs, expires date, path, domain, and so on, are concatenated to the document.cookie property, and separated by semicolon.

What is a first-party cookie?

A first-party cookie is a cookie set by the website the user is currently on. In other words, it’s a cookie set by the domain that appears in the user’s browser address bar. These cookies are typically used to remember preferences, login credentials, or to keep track of items in a shopping cart. They can also be used for web analytics or personalization of the user experience.

What is a third-party cookie?

A third-party cookie is a cookie set by a domain other than the one the user is currently on. In other words, it’s a cookie that set by a domain different from the one that appears in the user’s browser address bar. These cookies are set by third-party advertisers to track the user’s browsing behavior across multiple websites — and they’re are gradually being phased out due to privacy concerns.

What are the security implications of using cookies in JavaScript?

Cookies are widely used in web development to store small pieces of information on the client-side, but they can also present security risks if not handled properly. Some of the main security implications of using cookies in JavaScript include cross-site scripting (XSS) attacks, cross-site request forgery (CSRF) attacks, session hijacking, and cookie replay.

What are the performance implications of using cookies in JavaScript?

Some of the main performance implications of using cookies in JavaScript include network overhead for the client and the parsing and serialization that the browser needs to do to parse the cookie and serialize it back to the server.

By Dim Nikov

Editor of Maker's Aid. Part programmer, part marketer. Making things on the web and helping others do the same since the 2000s. Yes, I had Friendster and Myspace.

Leave a comment

Your email address will not be published. Required fields are marked *