How to work with cookies in JavaScript

Overview

There are many ways of storing users’ data on a website, which helps a developer perform various activities on the website and the user get the best user experience. These methods include cookies, local storage or session storage.

This shot is focused on cookies and how to work with them in JavaScript.

What are cookies?

A cookie is data stored with a unique user identity on a user’s browser by websites. This data is held the first time a user visits a website; cookies can be stored on our devices every time we visit a website. Cookies suggest content that is most important to us, and are used to keep our logins and help us remember them, prevent fraud, and more.

Cookies are the most common method of identifying users.

Cookies are always saved in name-value pairs. It has a name and a value attached to it:

username = akande

Requests made by a browser from the server for web pages will be delivered with cookies belonging to that page. Information about the users can be remembered this way.

How to create a cookie

In JavaScript, it’s easy to create cookies. The JavaScript’s document.cookie is used to create a cookie, set the expiry date, and the path for which the cookie works. It is also used to delete a cookie.


document.cookie = "myName=Akande Olalekan Toheeb; expires=Fri , 20 May 2022 23:59:59 GMT; path=/";

The cookie above has three parts which are explained below:

  1. The cookie: myName=Akande Olalekan Toheeb. This is the cookie that is stored. It has a name, myName, and a value Akande Olalekan Toheeb.
  2. Expiry date: This is a manual way to set a date for the cookie to be automatically deleted. expires=Fri , 20 May 2022 23:59:59 GMT. It has a day, date, and time. The cookie will be automatically deleted at this exact time.
  3. The path: This is the path on our website for the cookie to act upon. We can set it to act on any file on our website.

Change the value of a cookie

The value of a cookie is changed the same way we create it. It is mutable. All you need to do is change the value.

Delete a cookie

A cookie can be deleted by setting the expiry date to a past date.

  • We don’t have to specify the value when deleting a cookie.
  • We always specify a path to make sure we delete the right cookie.

Free Resources