Open In App

How to create cookie with the help of JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

A cookie is an important tool as it allows you to store the user information as a name-value pair separated by a semi-colon in a string format. If we save a cookie in our browser then we can log in directly to the browser because it saves the user information.

Approach: When a user sends the request to the server then the cookie tells that this user is already logged in your browser and the server recognizes the user and allows the user to log in. We can apply various operations on cookie-like create, delete, read, add an expiry date to it so that users can never be logged in after a specific time. A cookie is created by the document.cookie keyword as shown below.

Example: In the below example, we will take input from the user as a name for the cookie and store it in cookievalue. Then cookievalue is stored in string format adding the ‘name’ attribute and then the cookie is created in the browser.

HTML




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


Output:

Adding an expiry date (in UTC): We can add expire date for the cookie to ensure that after that time the cookie will no longer be in use.

Syntax:

document.cookie = "username=geeksforgeeks; 
expires=Sun, 16 JAN 2022 12:00:00 UTC";

Deleting the Cookie: When you want to delete the cookie just simply set the expires parameter and leave the username blank.

document.cookie = "username=; 
expires=Sun, 16 JAN 2022 12:00:00 UTC";


Last Updated : 10 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads