JavaScript Functions Manage Cookies Set Get And Remove

This page provides instructions on how to manage cookies using JavaScript, including methods for adding, using, and removing cookies.

What is cookies?

Cookies are small text files stored on a user's device by websites they visit. These files contain data such as site preferences, login status, and tracking information that help improve user experience by remembering user interactions and personalizing content. Cookies can have different lifetimes, from session cookies that expire when the browser is closed to persistent cookies that remain until a specified expiration date.

What are the attributes of cookies?

Cookies have several attributes that determine behavior, scope, and security. Below is a detailed description of each attribute and its use.

  1. Name: The name of the cookie. Cookie names must contain printable ASCII characters and avoid special characters.

  2. Value: The actual data or information stored in the cookie, which can be a string, number, or any other data type.

  3. Expires: The expiration date of the cookie. Defines when to delete the cookie. If not set, the cookie is a session cookie and is deleted when the browser is closed. Must be in UTC time format. Example Expires=Wed, 21 Mar 2024 07:28:00 GMT

  4. Max-Age: The maximum age of the cookie in seconds. Defines how long the cookie should be retained. Overrides the Expires attribute if both are set. Example Max-Age=3600 (cookie will expire in 1 hour)

  5. Domain: The domain within which the cookie is accessible. Specifies the domain to which the cookie should be sent. If not set, defaults to the domain of the page setting the cookie. Example Domain=.example.com (available to all subdomains of example.com)

  6. Path: The URL path that must exist in the requested URL for the browser to send the cookie header. Example Path=/blog (cookie is only accessible within /blog and its subpaths)

  7. Secure: Indicates that the cookie should only be sent over secure (HTTPS) connections. Enhances security by ensuring the cookie is not sent over unsecured HTTP connections.

  8. HttpOnly: Indicates that the cookie is not accessible via JavaScript.

    When this attribute is set, the cookie is accessible only through the HTTP protocol and cannot be accessed by client-side scripts, such as JavaScript. This helps protect against cross-site scripting (XSS) attacks. Although HttpOnly cannot be set via JavaScript

  9. SameSite: Controls whether a cookie is sent with cross-site requests. Helps protect against cross-site request forgery (CSRF) attacks.

    • Strict: Cookie is sent only with same-site requests.
    • Lax: Allows the cookie to be sent in a cross-site subrequest, but only if the request is a GET request or a top-level navigation.
    • None: Cookie is sent with both same-site and cross-site requests (must be used with Secure).

Note: JavaScript cannot modify HTTPS cookies with the HttpOnly attribute set. This attribute is used to prevent client-side scripts from accessing the cookie's data, which increases security by protecting against cross-site scripting (XSS) attacks. However, cookies without the HttpOnly attribute can be read, written, and deleted by JavaScript using the document.cookie property.

These functions provide a simple and effective way to manage cookies in JavaScript. Here's a simple JavaScript function to set, get, and remove cookies

Set Cookie

Function to set a cookie. Sets a cookie with the specified name, value, and expiration in days. If days is not provided, the cookie will be a session cookie.

JavaScript
const setCookie = (name, value, days, attributes) => {
    const cookie = [];
    // Encode the value to escape semicolons, commas, and white-space
    let name_value = encodeURIComponent(name) + "=" + encodeURIComponent(value);
    cookie.push(name_value);
    if (typeof days == "number") {
        let expires = "expires=" + new Date(Date.now() + 864E5 * days).toUTCString();
        cookie.push(expires);
    }
    // Initialize attributes object if not provided or not an object
    if (typeof attributes !== 'object') {
        attributes = {};
    }
    // Set the default path to / if not provided
    if (attributes.path === undefined) {
        attributes.path = "/";
    }
    for (const key in attributes) {
        if (key != "expires" && key != "max-age") {
            let attr = key+"="+attributes[key];
            cookie.push(attr);
        }
    }
    return document.cookie = cookie.join("; ");
};

Usage Set Cookie

The setCookie() function creates and sets a cookie in the browser with the specified name, value, expiration date, and other attributes. It ensures that the value is properly encoded and handles default attribute values when they are not provided.

The parameters for the setCookie() function are as follows

  • name: The name of the cookie.
  • value: The value of the cookie.
  • days: (optional) The number of days until the cookie expires.
  • attributes: (optional) An object containing additional attributes for the cookie, such as path, domain, secure, etc.

Set a cookie that expires when the user closes the browser

Sets a cookie with the specified name, value, and expiration in days and. If days is not provided, the cookie will be a session cookie

setCookie("username", "jhon");
// This cookie will expires when the user exits the browser

Set a cookie that expires in 30 days

setCookie("username", "jhon", 30);

Set the cookie path to the current page

setCookie("username", "jhon", 30, {path:""});

Set additional attributes for the cookie, such as path, domain, secure

setCookie("username", "jhon", 30, {
    path: "/",
    domain: ".example.com",
    SameSite: "none",
    Secure: true
});

Get Cookie

Function to get a cookie. This JavaScript function is designed to retrieve the name of a cookie. By passing the name of the cookie as a function parameter, you get the decoded value of the cookie if it exists, otherwise you get a null value. If you don't specify a cookie name as a parameter, you get all visible cookies as an empty {} object.

JavaScript
const getCookie = (name) => {
    const cookies = document.cookie.split('; ');
    const cookies_list_obj = {};
    cookies.forEach(cookie => {
        let [key, ...values] = cookie.split('=');
        let value = decodeURIComponent(values.join('='));
        key = decodeURIComponent(key);
        cookies_list_obj[key] = value;

        if (name === key) {
            return;
        }
    });

    if (name !== undefined) {
        return cookies_list_obj[name] ? cookies_list_obj[name] : null;
    } else {
        return cookies_list_obj;
    }
};

Usage Get Cookie

Read cookie

Function parameter Give the name of a cookie

getCookie('username'); // = 'jhon'
getCookie('nothing'); // = null

Read all visible cookies

Call getCookie() function without add parameter, If there are no visible cookies, an empty object is returned.

getCookie(); // = { username: 'jhon' }

Check if the cookie name exists or not

if (getCookie('username') != null) {
    // cookie name exists
    // do something
} else {
    // no cookie
    // do something
}

Show all visible cookies as an object.

Retrieve all cookies that are currently visible and convert them into objects.

const cookies_obj = getCookie();
// = { username: 'jhon', 'second-name': 'second-value' }
if(cookies_obj['your_cookie_name']){
  // do something
}else{
  // no cookie
}

Remove Cookie

Function to remove a cookie. This JavaScript function code is used to remove a cookie. It accepts two parameters: the cookie name and the cookie attributes.

JavaScript
const removeCookie = (name, attributes) => {
    const cookie = [];
    let name_value = encodeURIComponent(name) + "=";
    attr.push(name_value);
    if (typeof attributes !== 'object') {
        attributes = {};
    }
    if (attributes.path === undefined) {
        attributes.path = "/";
    }
    // Set the expiration date to a past date
    attributes.expires = "Thu, 01 Jan 1970 00:00:01 GMT";
    for (const key in attributes) {
        if (key != "max-age") {
            let attr = key+"="+attributes[key];
            cookie.push(attr);
        }
    }
    return document.cookie = cookie.join("; ");
};

Usage Remove Cookie

Delete cookie

removeCookie("username");

Delete the cookie using the path of the current page

When deleting a cookie you must set the same path and domain attributes that were used to set the cookie.

setCookie("user_country", "India", { path: "" });
removeCookie("user_country"); // fail!
removeCookie("user_country", {path: ""}); // removed!

Set the maximum age of the cookie in seconds

To set a cookie with an expiration time specified in seconds using the Max-Age attribute

javaScript
const setCookieMaxAgeInSeconds = (name, value, second, attributes) => {
    const cookie = [];
    // Encode the value to escape semicolons, commas, and white-space
    let name_value = encodeURIComponent(name) + "=" + encodeURIComponent(value);
    cookie.push(name_value);
    if (typeof second == "number") {
        let max_age = "max-age=" + second;
        cookie.push(max_age);
    }
    if (typeof attributes !== 'object') {
        attributes = {};
    }
    if (attributes.path === undefined) {
        attributes.path = "/";
    }
    for (const key in attributes) {
        if (key != "expires" && key != "max-age") {
            let attr = key + "=" + attributes[key];
            cookie.push(attr);
        }
    }
    return document.cookie = cookie.join("; ");
};

Usage set Cookie MaxAge In Seconds

This function takes in four parameters: name, value, max-age (in seconds), and an attribute object (optional) (including path, domain, and sameSite).

Set the third parameter to specify the duration (in seconds) after which the cookie should be deleted.

In this example, the logSession cookie will expire in 1800 seconds (30 minutes)

30 minutes cookie

setCookieMaxAgeInSeconds("logSession", "key_j45", 1800);
// This cookie will expire in 30 minutes

One hour cookie

setCookieMaxAgeInSeconds("logSession", "key_j45", 3600);
// This cookie will expire in 1 hour

A simple lightweight JavaScript function handles cookies

This JavaScript function code is used to set get and remove cookies.

JavaScript
(function(global, factory) {
    global.Cookies = factory();
})(this, function() {
    // Generated by https://www.html-code-generator.com/javascript/function/set-get-remove-cookies
    return {
        set: (name, value, days, attributes) => {
            const cookie = [];
            // Encode the value to escape semicolons, commas, and white-space
            let name_value = encodeURIComponent(name) + "=" + encodeURIComponent(value);
            cookie.push(name_value);
            if (typeof days == "number") {
                let expires = "expires=" + new Date(Date.now() + 864E5 * days).toUTCString();
                cookie.push(expires);
            }
            if (typeof attributes !== 'object') {
                attributes = {};
            }
            if (attributes.path === undefined) {
                attributes.path = "/";
            }
            for (const key in attributes) {
                if (key != "expires" && key != "max-age") {
                    let attr = key + "=" + attributes[key];
                    cookie.push(attr);
                }
            }
            return document.cookie = cookie.join("; ");
        },
        get: (name) => {
            const cookies = document.cookie.split('; ');
            const cookies_list_obj = {};
            cookies.forEach(cookie => {
                let [key, ...values] = cookie.split('=');
                let value = decodeURIComponent(values.join('='));
                key = decodeURIComponent(key);
                cookies_list_obj[key] = value;
                if (name === key) {
                    return;
                }
            });
            if (name !== undefined) {
                return cookies_list_obj[name] ? cookies_list_obj[name] : null;
            } else {
                return cookies_list_obj;
            }
        },
        remove: (name, attributes) => {
            const cookie = [];
            let name_value = encodeURIComponent(name) + "=";
            attr.push(name_value);
            if (typeof attributes !== 'object') {
                attributes = {};
            }
            if (attributes.path === undefined) {
                attributes.path = "/";
            }
            attributes.expires = "Thu, 01 Jan 1970 00:00:01 GMT";
            for (const key in attributes) {
                if (key != "max-age") {
                    let attr = key + "=" + attributes[key];
                    cookie.push(attr);
                }
            }
            return document.cookie = cookie.join("; ");
        }
    };
});

Usage Get Set Remove Cookie

As mentioned above, the cookies function parameter should be used here as well. Here only the name of the function changes.

set cookie

Cookies.set("user_country","IN",30);

get cookie

Cookies.get("user_country");

remove cookie

Cookies.remove("user_country");

What is the maximum amount of data that can be stored in a cookie?

Cookies can only store a limited amount of data, and this limit can change a little bit depending on the web browser you're using. Here are some general restrictions

  1. Size per cookie: Each cookie can typically store up to 4 KB (4096 bytes) of data. This includes all attributes of the cookie like name, value, domain, path, expiration and more..
  2. Number of cookies per domain: Different browsers have different limits, Browsers generally allow a single domain to store around 20 to 50 cookies.
  3. Total size per domain: The combined size of all cookies for a single domain can be up to 100 KB in some browsers.
  4. Total cookies per browser: There may also be a limit on the total number of cookies a browser can store across all domains, typically around 3000 to 4000 cookies.

Alternative storage options

  • Local Storage: Stores data with no expiration date, limited to about 5-10 MB per domain.
  • Session Storage: Stores data for the duration of the page session, also limited to about 5-10 MB per domain.
  • IndexedDB: A low-level API for storing large amounts of structured data, providing significantly larger storage capacities.