Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

How to create cookie with the help of JavaScript ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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.


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


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.


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";

My Personal Notes arrow_drop_up
Last Updated : 10 Feb, 2022
Like Article
Save Article
Similar Reads
Related Tutorials