JavaScript Cookies

JavaScript Cookies

Cookies are small pieces of data that a website can store on a user’s browser. These tiny text strings help a website remember information across multiple page views, sessions, and even days or months. Unlike localStorage or sessionStorage, cookies can be automatically sent with HTTP requests to the server, making them useful for things like tracking login sessions or saving user preferences that need to be available across different parts of the site.

In JavaScript, working with cookies means manually writing and parsing strings. It may seem a bit old-school, but cookies remain one of the most essential tools in a web developer’s toolbox. They’re supported across all browsers and can be customized with attributes like expiration dates and paths. In this article, we’ll walk through how to actually use cookies with JavaScript — step by step, using real-world, fun, and engaging examples.

Creating a Cookie

To create a cookie in JavaScript, you use the document.cookie property and assign it a string in the format key=value. That’s it — just a string. Cookies set this way will last only until the browser session ends, unless you tell them otherwise.

Let’s start with Harry. Suppose he visits a magical website that wants to remember which house he belongs to. The site can create a cookie like this:

<!DOCTYPE html>
<html>
<head>

  <title>JavaScript | Cookies</title>

</head>
<body>

  <script>

    document.cookie = "house=Gryffindor";

  </script>

</body>
</html>

This simple line creates a cookie with the name house and the value Gryffindor. Once set, the browser keeps it for the current session, making it accessible across all scripts running on that same origin. If Harry closes the browser, the cookie disappears, unless we make it more permanent — which we’ll do next.

Creating a Cookie with an Expiration Date

Cookies don’t have to vanish at the end of a session. You can set an expiration date using the expires attribute, which takes a date string in UTC format. This is useful when you want a cookie to survive page reloads and browser restarts for days, weeks, or months.

Imagine Stewie sets a cookie to remember that he armed his laser gun, and he wants this information to stick around for 7 days. Here’s how that would look:

<!DOCTYPE html>
<html>
<head>

  <title>JavaScript | Cookies</title>

</head>
<body>

  <script>

    const date = new Date();
    date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days in milliseconds

    document.cookie = "weapon=laserGun; expires=" + date.toUTCString();

  </script>

</body>
</html>

In this code, we create a new Date object, set the time forward by 7 days, and then use toUTCString() to generate the correct expiration format. This ensures that the weapon cookie will remain in the browser for a full week unless explicitly removed.

Creating a Cookie with a Path

Cookies can also be scoped to specific parts of a website. This is where the path attribute comes into play. By default, a cookie is only accessible to the page or folder that set it. To make it accessible throughout the entire website, set path=/.

Let’s say Lucia is using a multilingual site and chooses Swahili as her preferred language. She wants the language preference to apply across all pages, not just the homepage. Here’s the code:

<!DOCTYPE html>
<html>
<head>

  <title>JavaScript | Cookies</title>

</head>
<body>

  <script>

    document.cookie = "language=Swahili; path=/";

  </script>

</body>
</html>

With the path=/ setting, this cookie will be accessible by every page on the site. That way, Lucia’s Swahili preference can be honored everywhere — from the homepage to the contact form.

Reading Cookies

Reading cookies isn’t as direct as setting them. When you access document.cookie, it returns one long string containing all cookies for the current path and domain, separated by semicolons. To get a specific value, you must split and search manually.

Suppose Harry wants to see which house he’s been sorted into. This is how he can read it from the cookie:

<!DOCTYPE html>
<html>
<head>

  <title>JavaScript | Cookies</title>

</head>
<body>

  <script>

    const cookies = document.cookie.split("; ");
    let house = "";

    for (const c of cookies) {

      if (c.startsWith("house=")) {
        house = c.split("=")[1];
      }

    }

    console.log(house); // Gryffindor

  </script>

</body>
</html>

Here, we split the cookie string into individual parts using ;, then loop through each part to find the one that starts with house=. Once found, we grab the value after the equal sign.

Updating a Cookie

To update a cookie, you simply set it again with the same name. If a cookie with that name already exists, it will be overwritten.

For instance, let’s say Hermione initially saved "language=Python" but has now changed her mind and prefers JavaScript. She can update her preference like this:

<!DOCTYPE html>
<html>
<head>

  <title>JavaScript | Cookies</title>

</head>
<body>

  <script>

    document.cookie = "language=JavaScript; path=/";

  </script>

</body>
</html>

This line sets a new value for the language cookie. If the previous value was "Python", it’s now "JavaScript". The browser automatically replaces the old value with the new one.

Deleting a Cookie

Cookies can be deleted by setting their expires attribute to a date in the past. Once expired, the browser removes them automatically.

Brian had a cookie named weapon, but he wants to disarm. Here’s how he deletes it:

<!DOCTYPE html>
<html>
<head>

  <title>JavaScript | Cookies</title>

</head>
<body>

  <script>

    document.cookie = "weapon=; expires=Thu, 01 Jan 1970 00:00:00 UTC;";

    console.log(document.cookie);

  </script>

</body>
</html>

Setting the expiration to a date that has long passed (like January 1, 1970) effectively removes the cookie from the browser.

Storing Multiple Cookies

You can store as many cookies as you want, as long as each has a unique name. They’re all stored as part of the same document.cookie string.

Let’s say Percy wants to store two different cookies: one for his favorite movie and one for his cat’s name. Here’s how:

<!DOCTYPE html>
<html>
<head>

  <title>JavaScript | Cookies</title>

</head>
<body>

  <script>

    document.cookie = "movie=Black Panther";
    document.cookie = "cat=Whiskers";

  </script>

</body>
</html>

To read both values later, he can use:

<!DOCTYPE html>
<html>
<head>

  <title>JavaScript | Cookies</title>

</head>
<body>

  <script>

    const cookies = document.cookie.split("; ");
    let movie = "", cat = "";

    for (const c of cookies) {

      if (c.startsWith("movie=")) movie = c.split("=")[1];
      if (c.startsWith("cat=")) cat = c.split("=")[1];

    }

    console.log(movie); // Black Panther
    console.log(cat);   // Whiskers

  </script>

</body>
</html>

Each cookie is saved and retrieved independently, making it easy to store multiple small pieces of user data.

Saving Objects as Cookies (Manually)

Because cookies only store strings, saving objects or arrays means manually converting them. To do that, you use JSON.stringify() to convert the data to a string and encodeURIComponent() to ensure it’s safe for storage.

Stewie wants to store a user object with his name and role. Here’s how he does it:

<!DOCTYPE html>
<html>
<head>

  <title>JavaScript | Cookies</title>

</head>
<body>

  <script>

    const user = { name: "Stewie", role: "Baby Genius" };
    document.cookie = "user=" + encodeURIComponent(JSON.stringify(user));

  </script>

</body>
</html>

Later, to read and parse the data back:

<!DOCTYPE html>
<html>
<head>

  <title>JavaScript | Cookies</title>

</head>
<body>

  <script>

    const raw = document.cookie.split("; ").find(c => c.startsWith("user="));
    const userData = JSON.parse(decodeURIComponent(raw.split("=")[1]));

    console.log(userData.name); // Stewie

  </script>

</body>
</html>

This approach allows Stewie to store complex data structures in a cookie, even though cookies are designed for plain text only.

Writing a Page View Stat Tracker with Cookies

Cookies are also great for tracking how many times someone visits a page. Let’s say Brian is obsessed with the Dog Facts page and wants to know how often he’s visited it.

We can use a cookie called dogPageViews to track the count:

<!DOCTYPE html>
<html>
<head>

  <title>JavaScript | Cookies</title>

</head>
<body>

  <p id="output"></p>

  <script>

    let visits = 0;
    const cookies = document.cookie.split("; ");

    for (const c of cookies) {

      if (c.startsWith("dogPageViews=")) {
        visits = parseInt(c.split("=")[1]);
      }

    }

    visits++;

    const date = new Date();
    date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000)); // 30 days
    document.cookie = "dogPageViews=" + visits + "; expires=" + date.toUTCString() + "; path=/";

    document.getElementById('output').textContent = `You've visited this page ${visits} times.`;

  </script>

</body>
</html>

This code reads the cookie, increases the count, and saves it again with a new expiration. Brian can come back tomorrow, next week, or a month later — and his visit count will still be remembered.

Conclusion

JavaScript cookies are a powerful and flexible way to store small amounts of data directly in the browser. With just a few lines of code, you can create cookies, read them, update values, delete them, and even use them to track activity like page views. Whether you’re building a preference-based app, storing user settings, or just having fun tracking how many times Brian visits Dog Facts, cookies give your web pages memory — even without a database.

References

If you want to learn more about JavaScript cookies and related topics, these resources are excellent starting points:

Scroll to Top