How to use document.cookie In Javascript

In this approach, we are using the document.cookie property to both set and retrieve cookies. When setting a cookie, we assign a string formatted as “name=value” to document.cookie, and to retrieve cookies, we split the cookie string and parse it into a key-value map.

Syntax:

document.cookie = "username=name; 
expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";

Example: The below example uses document.cookie to set and retrieve cookies using JavaScript.

HTML
<!DOCTYPE html>

<head>
    <title>Example 1</title>
</head>

<body>
    <h1 style="color: green;">
        w3wiki
    </h1>
    <h3>Using document.cookie</h3>
    <input type="text" id="uInput" 
        placeholder="Enter cookie value">
    <button onclick="setFn()">
        Set Cookie
    </button>
    <button onclick="getFn()">
        Get Cookie
    </button>
    <p id="cookieVal"></p>
    <script>
        function setFn() {
            const value =
                document.getElementById('uInput').value;
            document.cookie =
                `exampleCookie=${value}`;
            alert('Cookie has been set!');
        }
        function getFn() {
            const cookies =
                document.cookie.split('; ');
            const cookieMap = {};
            cookies.forEach(cookie => {
                const [name, value] = cookie.split('=');
                cookieMap[name] = value;
            });
            const cookieVal = cookieMap['exampleCookie'];
            document.getElementById('cookieVal').textContent =
                `Cookie Value: ${cookieVal}`;
        }
    </script>
</body>

</html>

Output:

How to Set & Retrieve Cookies using JavaScript ?

In JavaScript, setting and retrieving the cookies is an important task for assessing small pieces of data on a user’s browser. This cookie can be useful for storing user preferences, session information, and many more tasks.

Table of Content

  • Using document.cookie
  • Using js-cookie library

Similar Reads

Using document.cookie

In this approach, we are using the document.cookie property to both set and retrieve cookies. When setting a cookie, we assign a string formatted as “name=value” to document.cookie, and to retrieve cookies, we split the cookie string and parse it into a key-value map....

Using js-cookie library

In this approach, we are using the js-cookie library, which provides a simple way to manage cookies in JavaScript. This library has methods like Cookies.set() and Cookies.get() to easily set and retrieve cookies....

Contact Us