CYBER MONDAY SALE: Get 50% off Tabnine!
Home / Blog /
How to Use Cookies with JavaScript
//

How to Use Cookies with JavaScript

//
Tabnine Team /
6 minutes /
December 6, 2021

Cookies make it possible to store information about a web application’s user between requests.

After a web server sends a web page to a browser, the connection shuts down and all information held by the server is lost. This makes maintaining user state challenging, as we cannot refer to the server for values specific to the current user’s browser activity. Cookies overcome this obstacle by storing the required information on the user’s computer in the form of a name=value string.

Cookies are often used to store usernames, preferences, authentication tokens, and other similar items.

It is important to keep security in mind when storing sensitive information like authentication tokens. Cookies can be seen and modified by the user, potentially exposing sensitive information. For more about this issue see the section Set a path for a cookie below.

Set a cookie

Setting a cookie uses the following syntax:

document.cookie = ‘newCookie’

Let’s break this down into its components:

  • document.cookie is the command used to create a new cookie.
  • ‘newCookie’ is a string that sets the cookie value. It has its own syntax to be aware of: name=value
    • For readability reasons name should imply what the cookie stores (e.g. username)
    • value is simply the value.

Below is an example of setting a cookie using this syntax:

document.cookie = "username=Max Brown";

The above code will store a cookie named “username” with the value “Max Brown”.

Note: Cookies expire automatically based on an expiration date that can be set in code. If no expiration date is set, the cookie will be deleted as soon as the browser is closed. The next section covers setting an expiration date for your cookies.

By default, cookies will be automatically deleted once the browser is closed. This prevents users from re-using the cookie values on subsequent visits to your page. You can override this by setting an expiration date for your cookie. This can be done easily by adding expires=expirationDate in UTC separated by semicolon from the name=value, as seen in the following example:

document.cookie = "username=Max Brown; expires=Wed, 05 Aug 2020 23:00:00 UTC";

The above example sets the “username” cookie to “Max Brown” as before, but it also adds an expiration date of Wednesday, August 5th, 2020, with an expiration time of 23:00:00 UTC. When this expiration time is reached, the cookie value will be deleted.

Note: UTC is a time standard (the coordinated universal time).

By default, cookies are associated with the page that sets them. This can lead to cookie values that are very easily traced by a curious user using developer tools. AS such, it is not advisable to store sensitive data on the root path for your application. Instead, you can provide a path where this data should be stored. The syntax for this is as follows:

document.cookie = "username=Max Brown; expires=Wed, 05 Aug 2020 23:00:00 UTC; path=/"

In the above example, we have set our “username” cookie with the value of “Max Brown”, and set its expiration to the same date as before. The difference is the path parameter, which modifies where the cookie is stored on the user’s machine. This is very useful when trying to store sensitive information, as it makes the information harder to find.

All of the above examples hard-code the cookie values, which will be of limited utility in most cases. Cookie values can also be set using a JavaScript function. Take the following code for example:

let username = 'Max Brown';

// Set a Cookie
function setCookie(cName, cValue, expDays) {
        let date = new Date();
        date.setTime(date.getTime() + (expDays * 24 * 60 * 60 * 1000));
        const expires = "expires=" + date.toUTCString();
        document.cookie = cName + "=" + cValue + "; " + expires + "; path=/";
}

// Apply setCookie
setCookie('username', username, 30);

This code defines a function, setCookie(). This function will create a cookie with the name “username”, value “Max Brown” with an expiration date of 30 days from the time it was created. Let’s explore this function line-by-line:

  1. In the first line of the function body, variable date is created and given the current date and time value in UTC as its initial value, This UTC timestamp will be formatted using the UTC timestamp format (e.g. Thu Aug 06 2020 12:41:34 GMT+0000 (UTC)). This value may be adjusted based on the user’s time zone.
  2. The next line of code converts the UTC timestamp above into a number (E.g. 1599308841783). This number is an integer known as the “epoch” time, or Unix time unit, and can be converted to a UTC timestamp easily. This allows us to easily manipulate the time using integer time differentials. The second part of this row uses this epoch time to calculate an expiration date for the cookie. It requires the number of milliseconds that you want your cookie expiration to take. The above code converts the parameter expDays (with a value of 30 as passed in above), and converts those requested days into an equivalent number of milliseconds. These milliseconds are then added to the Unix epoch timestamp, creating the target expiration date and time for our cookie.
  3. The third line declares a new variable expires, and gives it the value calculated for the expiration date in the previous line. This value is converted into a UTC string, which always shows GMT time as opposed to local time (e.g. Sat, 05 Sep 2020 12:38:16 GMT).
  4. The final line of the function sets the new cookie with all of the parameters populated:
    username=Max Brown; expires=Sat, 05 Sep 2020 12:38:16 GMT; path=/

To update a cookie, simply overwrite its value in the cookie object. You do this by setting a new cookie on the document with the same Name, but a different Value. The following code shows this in action:

username = 'Jen Brown';

setCookie('username', username, 30);

In the above code, we did not create a new cookie, as we already have a value in the cookie “username” of “Max Brown”. This call to setCookie() overwrites the value of the “username” cookie, changing it from “Max Brown” to “Jen Brown”.

To delete a cookie, you can simply provide an expiration date that occurred in the past. When the browser sees that the cookie has expired, it will delete the cookie automatically.

Fun fact: the formal Unix time count began on Thursday, January 1st 1970 at midnight GMT. This is known as the “Epoch” time. Timestamps in integers are similarly also known as “milliseconds since epoch”, or the number of milliseconds that have taken place since January 1st 1970.

To easily delete any cookie, simply set its expiration date as the epoch timestamp:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";

This statement will delete a cookie named “username” if one exists.

Some browsers will not allow the deletion of a cookie if the path is not specified. Therefore, it is important to always specify the path when working with cookies.

Get cookies

Getting all cookies is very simple. Cookies are stored as a set of strings separated by semicolons. You can access this value by calling document.cookie as seen in the example below:

document.cookie = "username=Debra White; path=/";
document.cookie = "userId=wjgye264s; path=/";
let cookies = document.cookie;
console.log(cookies); // expected output: username=Debra White; userId=wjgye264s

The above code sets two cookies – username and userId, and returns the cookie values to the variable cookies as a single semicolon-delimited string. Note that the return value does not include the specified path.

Get a cookie

Retrieving the value of a single cookie requires a little bit of legwork.

First, we’ll write a function that can determine the value of a cookie when given the cookie’s name. Here is our sample code:

function getCookie(cName) {
      const name = cName + "=";
      const cDecoded = decodeURIComponent(document.cookie); //to be careful
      const cArr = cDecoded .split('; ');
      let res;
      cArr.forEach(val => {
          if (val.indexOf(name) === 0) res = val.substring(name.length);
      })
      return res;
}

Exploring function getCookie() by line

The function getCookie takes a cookie’s name as a parameter, then performs the following steps:

  1. The first line assigns the requested cookie name to a const variable name. It appends an equals sign to the end of the name. For example, passing in a cookie value ‘username’ will result in ‘username=’ being stored in the name variable.
  2. The next line retrieves all of the cookies using document.cookie, then applies decodeURIComponent() to the result. This function “cleans” the string from “encoding traces” that may have been included in the cookie content. You have likely seen these encoding traces before, they look similar to this: %20%24username%20.
  3. As explained in the previous section, document.cookie returns results as a string containing all cookie values separated by semicolons (;). Here I have used the split() method, asking it to split the string’s values apart when it encounters a semicolon followed by a blank space. The result will be an array of cookie strings.
  4. The following two lines define the return variable, res, and call the forEach() method on the array of cookies obtained in line 4 (cArr). The forEach() iterates through an array, executing a callback function once for each array element. In the above example, if the value stored in variable name appears at the beginning of the string (i.e. at index 0), the inner block assigns the content of the cookie (i.e. the value after the “=” sign) to the variable res. The value length is larger than index by one. This allows us to trim off both the full string name of the cookie, and the trailing equality sign by starting the trim at index = name.length. For trimming I used the substring() method, which produces a substring of the specified length from the original input string.
  5. If the forEach() method was not able to find the requested cookie, the value ‘undefined’ will be returned.

Keep in mind that in many cases, working with cookies will begin with fetching a cookie’s value, and then requesting information from the user if the requested cookie is not found.

 

Related Articles:

JavaScript – How to Use The Array forEach() Method

JavaScript – How to Use the String length Property

JavaScript – How to Get an Input’s Value