An HTTP cookie (also known as web cookie, browser cookie) is a small piece of information stored by the server in the user's browser. Cookies are commonly used for session management, user-tracking, and storing user preferences.

In JavaScript, you can use the document.cookie property to create, read, and delete cookies. Note that the document.cookie property can only access cookies with the HttpOnly attribute unspecified.

To create a new cookie in JavaScript, assign a name=value string to document.cookie:

document.cookie = 'name=John Doe'

Since the cookie value can not contain semicolons, commas, or spaces, you need the encodeURIComponent() function to encode the value before storing it in the cookie:

document.cookie = `name=${encodeURIComponent('John Doe')}`

Note: When you set the value of document.cookie, the web browser does not overwrite existing cookies. Instead, it adds a new HTTP cookie to the user's computer.

By default, the above cookie lifespan is the current browser session, which means that it is removed when the user closes the browser. Such cookies are called session cookies.

To persist cookies beyond the current browser session, you need to specify its expiry date either using the expires attribute (in UTC/GMT format) or the max-age attribute (in seconds):

// Set cookie fixed expiration date
document.cookie = `name=${encodeURIComponent('John Doe')}; expires=Sun, 14 August 2022 03:11:45 UTC`

// Set cookie max age, e.g. expire after 7 days
document.cookie = `name=${encodeURIComponent('John Doe')}; max-age=${7 * 24 * 60 * 60}`

By default, a cookie is available to all web pages in the same directory and its subdirectories. However, you can explicitly specify a path attribute to ensure that the cookie is only accessible to that path and its subdirectories.

For example, if set the path to /, the cookie will be available throughout the website regardless of which page creates it:

document.cookie = `name=${encodeURIComponent('John Doe')}; path=/`

The cookies, by default, are available only to the web pages in the domain they were used to set in. However, you can use the domain attribute to make a cookie available across subdomains.

For exmaple, if a cookie created by a web page on help.example.com sets its path to / and its domain to example.com, that cookie is also available to all web pages on blog.example.com, dash.example.com, etc.

document.cookie = `name=${encodeURIComponent('John Doe')}; path=/; domain=example.com`

You can also make a cookie secure using the secure attribute. Such cookies are only transmitted over a secure (i.e. encrypted) connection such as HTTPS:

document.cookie = `name=${encodeURIComponent('John Doe')}; path=/; domain=example.com; secure`

Finally, let us write a JavaScript function that takes in the name, value, expiry days, path, and domain, and adds an HTTP cookie:

const setCookie = (name, value, days, path, domain, secure) => {
  let cookie = `${name}=${encodeURIComponent(value)}`

  // Add expiry date
  if (days) {
    const expiry = new Date()
    expiry.setDate(expiry.getDate() + days)
    cookie += `; expires=${expiry.toUTCString()}`
  }

  // Add Path, Domain, and Secure
  if (path) cookie += `; path=${path}`
  if (domain) cookie += `; domain=${domain}`
  if (secure) cookie += `; secure`

  // Set an HTTP cookie
  document.cookie = cookie
}

Now to set a cookie that lasts 3 months, use the following code:

setCookie('name', 'John Doe', 90);

The document.cookie property returns all cookies set by the server as a series of key-value pairs separated by semi-colons:

const cookies = document.cookie

console.log(cookies)
// _ga=GA1.2.315746813.1624003242; lesson_completed=false; theme=dark

Since all the values and names are URL-encoded, you have to decode them using the decodeURIComponent() method.

Let us write a function that takes the cookie name as input and returns its value. If the cookie is not found, it should return a null value.

const getCookie = name => {
  const cookies = document.cookie.split(';')
  for (let i = 0; i < cookies.length; i++) {
    let c = cookies[i].trim().split('=')
    if (c[0] === name) {
      return decodeURIComponent(c[1])
    }
  }
  return ''
}

console.log(getCookie('_ga'))
// GA1.1.1736818142.1621579881

The above code uses the JavaScript split() method to split the cookie string by semi-colon. Then it iterates through the result array to match the name of the requested cookie with the key-value pairs.

You can update a cookie in the same way as you create it with the same name, path, domain, and secure option:

document.cookie = 'name=Alex; expires=Mon, 15 August 2022 10:52:32 UTC'

Alternatively, you could also use the above setCookie() function:

setCookie('name', 'Alex', 10)

Deleting a cookie is very simple. All you need to do is set the expiration date to some time in the past with the same name, path, domain, and secure option:

document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC"

You can also use the setCookie() function to remove the cookie:

setCookie('name', '', -1)

Read Next: How to use cookies in Spring Boot

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.