Get AI Code Completions for Your IDE

Home   >   Tutorials   >   JavaScript   >   How to Get Cookies Using JavaScript

JavaScript - How to Get Cookies Using JavaScript

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 means that information cannot easily be persisted between requests, as at each new request the server will not have any local context on the user. 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, access passwords, etc.

Note: You should always keep security in mind when storing sensitive information like passwords. The information stored in cookies is stored as a plain string, and can be easily discovered with minimal technical knowledge.

To learn more about cookies check out this link.

Get cookies

Getting all of the cookies from a user’s machine is very simple. Just call document.cookie to retrieve the current value of all cookies. You can then store this value in a variable for further manipulation.

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

In the above code, the first two lines of code set the values of two different cookies – username, and userId. The third line retrieves both cookies and stores it to a variable named cookies.

To learn more about cookies, and setting a cookie, check out this link.

Get a cookie

Getting a specific cookie is a little more complex than retrieving all cookies, but not that big of a deal.

If you have the cookie’s name, all you need is a function that iterates through all of the user’s cookies and finds the specific cookie required. The code sample below defines a function, getCookie(), that takes the name of a cookie and returns that cookie’s value:

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 constant 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. The final result of the user’s input will be stored back to the user’s cookies. To learn more about cookies, and setting a cookie, visit this link.

 

Related Articles:

JavaScript – How to Use Cookies

JavaScript – How to Use the indexOf method

JavaScript – How to Use The Array forEach() Method

Get AI Code Completions for Your IDE