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 ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API