How to Set Cookie in JavaScript

Migel Hewage Nimesha Feb 02, 2024
  1. Set Cookie in JavaScript
  2. Set an Expiration Date for a Cookie
  3. Set a Path for a Cookie
  4. the setCookie() Function
How to Set Cookie in JavaScript

A cookie is a piece of information that enables a connection between the client and server sides. The web browser stores it at the time of browsing.

Generally, a cookie contains data in the format of a name-value pair separated by semi-colons as a string. Also, a cookie maintains the user’s state and recollects the user’s information across all the web pages.

When considering JavaScript, a cookie can be created, read, updated, and deleted using the document.cookie property. A cookie comprises six segments: name, value, expires, path, domain, and security, as per the syntax below.

Syntax:

document.cookie = 'name=VALUE; expires=DATE; path=PATH; domain=DOMAIN; secure';

Here, the presence of the first segment: name=VALUE, is essential, and the other segments can be provided by the user if necessary, based on the requirement.

document.cookie = 'new_cookie'

First, consider each segment in detail as a start-up with the above syntax.

  1. The document.cookie command creates a new cookie.
  2. Here, the new_cookie is the string that sets the value of the cookie and has its syntax as name=VALUE, where the name should imply what the cookie should store in a readability format, and VALUE is simply the value given by the user as preferred.

An example to set a cookie:

document.cookie = 'username=John Ricks';

Here the cookie is stored with username as the name and the value John Ricks.

Output:

set username cookie

A cookie automatically expires based on the user’s expiration date set on the code. If an expiration date is not set, the cookie will be removed when the browser is closed by the user, preventing the user from reusing the cookie values when visiting the web pages.

We can override this issue by setting an expiration date for the cookie simply by adding expires=DATE in UTC (Universal Time Coordinated), a time standard separated by a semi-colon, as in the below example.

document.cookie = 'username=John Ricks; expires=Wed, 31 Aug 2022 21:00:00 UTC';

Output:

Set an Expiration Date for a Cookie

With the path parameter, the user can tell the browser which path the cookie belongs to in the directory or web page. By default, the cookie belongs to the current page accessed by the user.

This path may be blank once we get the cookie from any directory or web page. This parameter modifies where the cookie is stored on the user’s machine and is beneficial when storing sensitive information, as it is hard to find.

We can add the path to a cookie, as in the below code.

document.cookie =
    'username=John Ricks; expires=Wed, 31 Aug 2022 21:00:00 UTC; path=/'

Output:

Set a Path for a Cookie

Also, depending on the necessity, a domain and security can be added when setting a cookie. The purpose of adding a domain is to allow cookies to other subdomains.

The secure part is a Boolean value where the default value is false, a blank field. If the cookie is marked secure, the value is true, so the cookie will be sent to a web server and may only be retrieved with a secure communication channel.

the setCookie() Function

We can set cookie values using a JavaScript function without hard-coding the cookie values, which can be of limited utility on most occasions. The below code defines the setCookie() function.

let username = 'John Ricks';

// To set a cookie
function setCookie(cookie_name, cookie_value, expire_date) {
  const c_d = new Date();  // current date
  c_d.setTime(c_d.getTime() + (expire_date * 24 * 60 * 60 * 1000));
  let expires = 'expires=' + c_d.toUTCString();
  document.cookie =
      cookie_name + '=' + cookie_value + '; ' + expires + '; path=/';
}
// to apply setCookie
setCookie('username', username, 20);

Output:

setCookie

This function will create a cookie with the name username and the value of John Ricks and an expiration date of 20 days from when we generated it.

Similarly, we can use JavaScript functions to get a cookie by creating a getCookie() function, and cookies can also be updated or deleted if required.

Migel Hewage Nimesha avatar Migel Hewage Nimesha avatar

Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.

Related Article - JavaScript Cookie