Subscribe

Vanilla JavaScript Cookies πŸͺ

✍️

2020 - All about working with HTTP cookies in JavaScript. Look at the code examples and explanations.

11 Jul, 2020 Β· 2 min read

In this tutorial, we'll be looking into working with browser cookies in Vanilla JavaScript. It's not the most widely used functionality, but great to keep track of small things like whether someone clicked a cookie bar.

We can set, get, change and, delete a cookies.

To set a cookie in Vanilla JavaScript, we use the document.cookie property.

First, we must understand cookies are set as a key-value pair.

key = value

So, to set an HTTP cookie, you use the following:

document.cookie = 'username=Chris';

We can even set an expiry date:

document.cookie = 'username=Chris; expires=Sun, 01 Jan 2023 12:00:00 UTC';

Get cookies in Vanilla JS

To get and read a specific cookie, we can use the following:

const username = document.cookie;
username = Chris;
second = bla;

This will return the complete cookie object, so we need to split it like so:

const username = getCookie('username');
console.log(username);
// Chris

function getCookie(name) {
  // Add the = sign
  name = name + '=';

  // Get the decoded cookie
  const decodedCookie = decodeURIComponent(document.cookie);

  // Get all cookies, split on ; sign
  const cookies = decodedCookie.split(';');

  // Loop over the cookies
  for (let i = 0; i < cookies.length; i++) {
    // Define the single cookie, and remove whitespace
    const cookie = cookies[i].trim();

    // If this cookie has the name of what we are searching
    if (cookie.indexOf(name) == 0) {
      // Return everything after the cookies name
      return cookie.substring(name.length, cookie.length);
    }
  }
}

Sometimes we want to update a cookie. To do that, we first get the cookie and then set it again:

document.cookie = 'username=Nicole; expires=Sun, 01 Jan 2023 12:00:00 UTC';

To delete a specific web cookie, we have to set its date to be passed:

document.cookie = 'username=; expires=Thu, 01 Jan 1970 00:00:00 UTC;';

View the demo code to try getting and setting cookies in JavaScript right on Codepen.

See the Pen JavaScript get and set all cookies by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next πŸ“–

Removing all vowels with JavaScript

3 Dec, 2022 Β· 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 Β· 3 min read

10 games to learn JavaScript

Join 1990 devs and subscribe to my newsletter