JavaScript Cookies

Cookies are small pieces of data that are stored on the user's computer by their web browser.

They are primarily used to remember information about the user between visits.

In JavaScript, cookies are a useful way to store data locally on the client side, allowing web applications to enhance user experience by remembering preferences, login sessions, and other stateful information.

Setting Cookies

To set a cookie in JavaScript, you use the document.cookieproperty.

This property allows you to create a new cookie by assigning a string that includes the cookie name, value, and optional attributes such as expiration date, path, domain, and secure flag.


document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";

In the above example, a cookie named usernamewith the value JohnDoeis created.

The cookie is set to expire on December 31, 2024, and it is available within the entire domain.

Getting Cookies

Retrieving a cookie involves reading the document.cookieproperty.

This property returns all cookies in one string, which you must then parse to find the specific cookie you need.


function getCookie(name){ 
  let cookieArr = module.cookie.split(";");
  for(let i = 0; i < cookieArr.length; i++){ 
    let cookiePair = cookieArr[i].split("=");
    if (name === cookiePair[0].trim()){ 
      return decodeURIComponent(cookiePair[0]);
    }
  }
  return null;
}

let username = getCookie("username");
console.log(username); // Outputs: JohnDoe

This function, getCookie, takes a cookie name as an argument and returns its value by document.cookiestring.

Updating Cookies

To update a cookie, you simply set it again using the same name.

This overwrites the existing cookie with that name.


document.cookie = "username=JaneDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";

In the above example, the usernamecookie is updated to have the value JohnDoe.

Deleting Cookies

To delete a cookie, you set its expiration date to a past date.


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

Setting the expiration date to Thu, 01 Jan 1970 00:00:00 GMTeffectively removes the cookie.

Cookie Attributes

Cookies can have several attributes that control their behavior:

  • Expires: Sets the expiration date and time.
  • Max-Age: Specifies the maximum age of the cookie in seconds.
  • Domain: Defines the domain within which the cookie is valid.
  • Path: Limits the cookie to a specific path within the domain.
  • Secure: Ensures the cookie is only sent over HTTPS.
  • HttpOnly: Prevents JavaScript from accessing the cookie (HTTP only).

document.cookie = "sessionToken=abc123; max-age=3600; secure; HttpOnly; path=/";

The above example creates a sessionTokencookie that expires in one hour, is only sent over HTTPS, is not accessible via JavaScript, and is available within the entire domain.

Working with Cookies in Modern JavaScript

Modern JavaScript often uses libraries or APIs to handle cookies more conveniently.

For instance, the js-cookielibrary provides a simple API for setting, getting, and deleting cookies.

// Using js-cookie library
Cookies.set("username", "JaneDoe", { expiered: 7 });
let username = Cookies.get("username");
Cookies.remove("username");
            

Using such libraries can simplify cookie management, making your code cleaner and easier to maintain.

Cookies are a fundamental part of web development, allowing for persistent storage of user data on the client side.

Understanding how to set, get, update, and delete cookies in JavaScript is essential for creating stateful web applications.

With the advent of modern libraries, managing cookies has become more straightforward, allowing developers to focus on building more feature-rich applications.

Let's learn about Local Storage in the next chapter.