6
30

How to set cookie, read cookie and delete cookie in JavaScript

Reading Time: 2 minutes

Previously we have shown you how to set cookie, read and delete it in React. Here, we will show you how to do the same operations in pure JavaScript.

Usage of cookies:

Cookies are a very common type of storage mechanism for any webpage to store information that needs to exist even if user restart their browser or after it crash. Hence, these information is considered to be stateful.

Here are some of the common properties of a cookie (Maybe different based on browsers):

  • Maximum size of 4KB or 4096 Bytes per cookie
  • Maximum of 20 cookies per domain

For example is the storage of user information so that the user does not need to re-login even after they restart the application.

Set Cookie

In pure javascript, a cookie can be set as easy as what is shown below. It is basically compose by setting a key value pair. To overwrite the existing value, just need to re-assign the value to the same key.

document.cookie = "userName=someNameA";
console.log(document.cookie);
// Output: "userName=someNameA;"

document.cookie = "userName=someNameBBB";
console.log(document.cookie);
// Output: "userName=someNameBB;"

However, the above declaration will result in the cookie deleted when the browser closed. Thus, it is a good practice to add an expire date in UTC time. Let’s also add a path parameter to have the cookie to be use by all pages in this domain.

document.cookie = "userName=someNameA; expires=Wed, 10 Dec 2025 12:00:00 UTC; path=/";

Read Cookie

To read the cookie, just assign it to a variable. But be careful that you will receive all the cookie that was set together. Hence, the processing after reading it need to be done carefully.

document.cookie = "userName=someNameA";
document.cookie = "userName1=someNameB";

let cookies = document.cookie;
console.log(document.cookie);

// Output: "userName=someNameA; userName1=someNameB;"

Delete Cookie

To delete a cookie or key value pair to be more exact, we will just need to set the expiry date to some date in the pass.

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

Conclusion

With JavaScript cookie, we can have data stored into the browser with a expiry date and use it whenever user visit our webpage again.

Show Comments

No Responses Yet

Leave a Reply