An HTTP cookie is a small piece of data sent by the server to the browser while returning a response for the request made by the browser.

The web browser stores the HTTP cookie on the user's computer in a small text file and sends it back to the same server with the subsequent requests.

An HTTP cookie is also known as a web cookie, browser cookie, or just a cookie.

Here is an example of the server response that includes headers telling the web browser to store e pair of cookies:

HTTP/2.0 200 OK
Content-Type: text/html
Set-Cookie: admin=false
Set-Cookie: username=attacomsian
...

The browser will store this information and will send them back with every subsequent request to the server using the Cookie header:

GET /articles HTTP/2.0
Host: www.example.com
Cookie: admin=false; username=attacomsian
...

Why cookies?

Since the HTTP protocol is stateless, the server can not know if the two subsequent HTTP requests are from the same web browser.

Cookies were invented to solve this problem: help the server remember the client across multiple requests. Without cookies, the server would treat every request as a new client.

In practice, cookies are commonly used for session management, user-tracking, and storing user preferences.

An HTTP cookie may contain the following information stored by the web browser:

Name

A unique, case-insensitive string that identifies the cookie.

Value

A URL-encoded value that is stored along with the name of the cookie.

Domain

The Domain attribute specifies the hosts that are allowed to receive the cookie. If unspecified, it defaults to the same domain that sets the cookie, excluding sub-domains.

If the domain is specified, then subdomains are always included. For example, if Domain=exmaple.com is set, then cookies are available on subdomains like jobs.example.com.

Path

The Path attribute specifies a URL path for which the cookie should be sent to the server.

For example, if Path=/jobs is specified, the following paths are qualified to receive the cookie:

  • /jobs
  • jobs/web-development
  • /jobs/engineer-at-google

The cookie will not be sent for the following paths:

  • /
  • /login
  • /about

Expiration

The Expires attribute indicates when the web browser should remove the cookie. In other words, when the browser should stop sending the cookie to the server.

The expiration date must be set in UTC format: Www, dd Mmm yyyy hh:mm:ss UTC.

If no expiration time is specified for a cookie, it lasts as long as the session is not expired. Such cookies as called session cookies. Session cookies remain active until the user closes their browser or clears their cookies.

Secure

The secure flag is used to make a cookie secure.

A secure cookie is only sent to the server over an encrypted HTTPS connection. Secure cookies cannot be transmitted to the server over unencrypted HTTP connections.

HttpOnly

The HttpOnly attribute is used to prevent JavaScript access to cookie values. HttpOnly cookies are used to prevent cross-site scripting (XSS) attacks.

When the HttpOnly flag is set for a cookie, it tells the browser that this particular cookie should only be accessed by the server.

Cookies in JavaScript

You can use the document.cookie property to create, read, and delete cookies in JavaScript.

Note that the document.cookie property can only access cookies with the HttpOnly attribute unspecified.

To read a cookie in JavaSript, you just access document.cookie:

const cookies = document.cookie;

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

_ga=GA1.2.315746813.1624003242; _gid=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.

If you are looking for a specific cookie value, you can use the following function:

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 c[1];
        }
    }
    return "";
}

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

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

With JavaScript, you can create a cookie like this:

document.cookie = 'name=John Doe';

You can also set expiry date (in UTC time) to allow the browser to store the cookie even after the browser is closed by the user:

document.cookie = 'name=John Doe; expires=Sun, 20 Jun 2021 03:11:45 UTC';

You can also specify a path attribute to tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.

document.cookie = 'name=John Doe; expires=Sun, 20 Jun 2021 03:11:45 UTC; path=/';

Note that when 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.

To make things easier, you can also write a function that takes in the name, value, and expiry days, and add 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, you could use:

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

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=John Doe; expires=Sat, 10 Jul 2021 10:52:32 UTC';

You could also use the above setCookie() function:

setCookie('name', 'John Doe', 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.