javascript - javascript cookie

Storing User Data with Javascript Cookies

Here’s an interesting revelation about Javascript: Since Javascript is a client-side web development language, it has access to information about a user that other programming languages don’t.

The Javascript standard provides developers the chance to enhance user experiences using that data via Javascript cookies. 

Every web user has heard of a cookie at some point; we have to accept them at most websites we visit. Usually, we choose to accept them because a dialog box blocks our way, and then we go about our day. Those dialog boxes don’t tell us much about what a cookie is, though, and how many of us have really stopped to think about what they are?

In this article, we describe what Javascript cookies are and how they make your web browsing experience more interesting. Then, we’ll go over how developers manipulate and manage Javascript cookies.

Javascript Cookies and the User Experience

Cookies are small text files kept on a web server that identify the person using a web page. Users have identical text files on their computers for security purposes. If a user’s cookie matches with a web server’s cookie, the web server can retrieve any information it has about the user or their activities.

Web pages don’t have a built-in way to remember what was on any previously visited page; they are “stateless.” Cookies give web pages the ability to remember information from previous pages, such as the contents of an online shopping cart, the name on a person’s online account, or which files they have uploaded in the past.

Many web page operations may depend on the successful use of cookies, including error-handling. Proper validation of cookies is essential for web security; if a web server validates the wrong cookie, a privacy breach may occur where another person’s information is accessed.

By default, browsers are enabled to store and read cookies. It is possible to turn off cookies, at the cost of a less personalized user experience. A lot of the customizations we rely on when handling online profiles and accounts won’t work without cookies. At minimum, your websites must announce reduced functionality to the user.

Javascript Cookie Structure

Javascript cookies may contain many different fields, but the following three are vital for every cookie.

  • Domain — Domain name of the web page.
  • Path — Address to the specific directory or web page on the domain where the cookie should be stored.
  • Name=Value — Unique identifier of a piece of information, followed by its value.

Other common fields that further refine how cookies act are:

  • Expires — Time when a cookie will no longer be valid.
  • Max-age — Amount of seconds after which a cookie will no longer be valid; takes priority over Expires.
  • HttpOnly — Prevents Javascript from modifying a cookie after it’s been created.
  • Secure — Cookie that can only be read through a secure HTTPS protocol.

A cookie may contain multiple pieces of data specified by Name=Value. Unique data identifiers must not have the same names as cookie fields, such as Domain. If the same cookie file specifies the same identifier or field more than once, the last instance of that identifier or field will overwrite any previous ones.

The following example of a cookie places a cookie in the “cookie_folder” of a site called “example.com,” which expires on Halloween of 2021 and contains two pieces of unique user information.

Domain=http://www.example.com
Path=cookie_folder
Expires=Thu, 31 Oct 2021 07:28:00 GMT;
MyInfo=ThisInfo
MyInfo2=More

Operations with Javascript Cookies: Create, Get, Set, and Delete

Javascript manages its cookies through the document.cookie property. It’s possible to create, get, set, and delete cookies through this property.

Since remembering all the different ways to use document.cookie can be confusing, it’s often easier to write Javascript functions that handle all cookie operations clearly. These examples show how to use document.cookie and how to create simple functions that make cookie handling easier.

The examples are intentionally simple for illustrative purposes, and the functions could easily be expanded to take many cookie fields at once for easier handling.

Creating Javascript Cookies

Create a cookie by specifying the cookie name and value in a string assigned to document.cookie. Specify multiple fields with a semicolon between each field.

document.cookie = "myName=This Person";
document.cookie = "myName=This Person; expires=Thu, 18 Dec 2013 12:00:00 UTC";

function createCookie(name, value, expires) {
    document.cookie = name + "=" + value + "; expires" + expires;
}

Getting Javascript Cookies

Get all cookies at once by assigning the value of document.cookie to a variable. All cookies are separated by semicolons. Since fields within cookies are separated by semicolons as well, it is important to split the result of document.cookie carefully using Javascript regexes.

let cookies = document.cookie;

function getCookie(name) {
    let cookies = document.cookie;
    // complex parsing logic here
    return parsedCookie;
}

Setting Javascript Cookies

Setting new values for established Javascript cookies follows the same procedure as creating cookies, minus the creation step.

Deleting Javascript Cookies

To delete a cookie, its value must be an empty string and its expiration date must be a time in the past. Modern browsers will not allow you to delete cookies without also specifying the cookie’s path in the string assigned to document.cookie.

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

function deleteCookie(name, path) {
    document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=" + path;
}

Conclusion

Javascript cookies are an important tool that modern websites use to enhance user experiences. Developers must be careful to handle cookies properly so they don’t accidentally change users’ data or breach users’ privacy by exposing their data when it should be hidden.

Basic Javascript functionality on most websites includes cookies, but developers should have backup plans in place so their websites work even if users don’t want to use cookies. Misusing cookies, or failing to account for users who don’t want them, can drive away your web audience.

Enroll in our Intro to Programming Nanodegree Program today to learn more about Javascript cookies and other programming concepts.

Start Learning

Jessica Reuter Castrogiovanni
Jessica Reuter Castrogiovanni