How to set a cookie and get a cookie with JavaScript?

JavaScript cookies allow you to store small pieces of data in the user's browser. You can set cookies using document.cookie and retrieve them by parsing the same property.

Setting Cookies

The simplest way to create a cookie is to assign a string value to the document.cookie object:

document.cookie = "key1=value1;key2=value2;expires=date";

The "expires" attribute is optional. If you provide this attribute with a valid date or time, the cookie will expire on that date and the cookie's value will no longer be accessible.

Example: Setting a Cookie

This example sets a customer name cookie when you enter a value and click the button:

<html>
   <head>
      <script>
         function WriteCookie() {
            if( document.myform.customer.value == "" ) {
               alert("Enter some value!");
               return;
            }
            cookievalue = escape(document.myform.customer.value) + ";";
            document.cookie = "name=" + cookievalue;
            document.write("Setting Cookies : " + "name=" + cookievalue);
         }
      </script>
   </head>
   <body>
      <form name="myform" action="">
         Enter name: <input type="text" name="customer"/>
         <input type="button" value="Set Cookie" onclick="WriteCookie();"/>
      </form>
   </body>
</html>

Getting Cookies

Reading a cookie is simple because the value of the document.cookie object contains all cookies. The document.cookie string keeps a list of name=value pairs separated by semicolons, where the name is the cookie name and value is its string value.

Example: Reading Cookies

This example reads and displays all cookies stored in the browser:

<html>
   <head>
      <script>
         function ReadCookie() {
            var allcookies = document.cookie;
            document.write("All Cookies : " + allcookies);
            
            // Get all the cookies pairs in an array
            cookiearray = allcookies.split(';');
            
            // Now take key value pair out of this array
            for(var i=0; i<cookiearray.length; i++) {
               name = cookiearray[i].split('=')[0];
               value = cookiearray[i].split('=')[1];
               document.write("Key is : " + name + " and Value is : " + value);
            }
         }
      </script>
   </head>
   <body>
      <form name="myform" action="">
         <p>Click the following button and see the result:</p>
         <input type="button" value="Get Cookie" onclick="ReadCookie()"/>
      </form>
   </body>
</html>

Modern Cookie Management

For better cookie handling, you can create utility functions:

// Set a cookie with expiration
function setCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

// Get a specific cookie by name
function getCookie(name) {
    var nameEQ = name + "=";
    var cookies = document.cookie.split(';');
    for(var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        while (cookie.charAt(0) == ' ') {
            cookie = cookie.substring(1, cookie.length);
        }
        if (cookie.indexOf(nameEQ) == 0) {
            return cookie.substring(nameEQ.length, cookie.length);
        }
    }
    return null;
}

// Example usage
setCookie("username", "John", 7); // Expires in 7 days
console.log(getCookie("username")); // Returns "John"
John

Conclusion

JavaScript cookies provide a simple way to store user data in the browser. Use document.cookie to set cookies and parse the same property to retrieve them. Modern applications often use utility functions for better cookie management.

Updated on: 2026-03-15T22:25:06+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements