Updated March 18, 2023
Overview of Cookies in JavaScript
Cookies in JavaScript is a set of data stored in the browser that is fetched whenever a web page is loaded, and the content of this cookie will be used to reload the web page whenever there is a connectivity issue or the server is not reachable. The basic properties of the cookies are that the cookies are saved as a pair of the cookie name as key & its value, the expire value of the cookie which gives the information on when the cookie will be deleted and if there is no value for this parameter then the cookie will be deleted when the browser window is closed, the secure parameter for indicating the security level, host field for server details, the path where the cookie is stored, and a domain name gives the website details.
How Does Cookies Work in JavaScript?
Whenever we make any request to the server it sends some data to the user browsers in the form of a cookie. In the browser, we have some settings for a cookie. The browser can accept the cookie. If the browser accepts the cookie it got in the form of name-value pair in the user’s system. So whenever a user visits any different page on the site browser sends the same information about the user to the server to let them know about user data for further retrieval.
cookies are stored in the form of plain text. Some of the property of the cookie is as follows,
1. Name=Value pair
Cookie gets stored in the form of key and value pair and retrieve in the same way only.
Example:
username = value;
;max-age=max-age-in-seconds (e.g., 60*60*24*365)
2. Expire
We have a date when will this data will expire, if we do not have any value for a date or it is empty then the cookie will expire when the user will quite the browser or exit from it.
Example:
;expires=date-in-GMTString-format. If we do not mention expire nor max-age it will expire when exit or end of the current session as explained above.
3. Secure
If this field contains the word “secure” then we cannot retrieve the cookie, this can only be retrieved from the secure server otherwise there is no such kind of restriction. This is another way to securing our user information from untrusted servers.
4. Host
This provides two benefits one is it allows us to use a cookie from the secure origin as well as the scope of the cookie is also limited to the path attribute we passed from the server. So it covers two functions one for security and another one is path attribute as well.
If the server does not wish to provide the path attribute then the “directory” of the request is used. For the Chrome browser, path attribute is always the origin.
It also points that the domain attribute not be present which prevents the cookie from being sent to other domains then mentioned.
5. Path
This is the path that sets the cookie. If this path is blank then you can retrieve the cookie from any page. The path must be absolute.
Example:
;path=path (e.g., ‘/’, ‘/mypath’)
6. Domain
It contains the name of site.
Example:
; samesite: It will protect the browser from sending this cookie to any other page or cross-site request. It has two possible values for the flag.
The key= value pair can use or cookie value can use the encoded URI just to ensure that the string does not contain any whitespace, semicolons, commas. Cookie value does not contain all the above-mentioned restrictions. By using JavaScript we can create, retrieve and delete the cookie. For that, we use the cookie property of the document object so we can manipulate the cookie object.
So JavaScript can create, read and modify cookies on the current webpage.
Syntax of Cookies in JavaScript
Following are the syntax in javascript explain in details,
1. Writing a New Cookie
Syntax:
document.cookie = "key1 = value1;key2 = value2;expires = date";
document.cookie = value;
Above syntax to show only one key = value pair and other is a way to set multiple cookies at the same time. But here the Expire attribute is optional. If we provide this attribute any valid date or time then it will remove the cookie on that date and time if not then nothing will happen and the cookie will still be accessible.
Here we are setting the value to cookie property of document object. In the above syntax document.cookie = value is a form pf key = value. We need to remember one thing while setting the value of a cookie that we can only set one cookie at a time. (create/update)
Code:
<html>
<head>
<script type = "text/javascript">
function createCookie() {
if( document.myform.customer.value == "" ) {
alert("please enter some value.");
return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
document.write ("Cookies : " + "name=" + cookievalue );
}
</script>
</head>
<body>
<form name = "myform" action = "">
<input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "createCookie();"/>
</form>
</body>
</html>
Output:
2. Reading Cookie
Syntax:
allCookieValue = document.cookie
In the above syntax, allCookieValue will contain all the values of cookie separated by a semicolon, so it is basically a string separated by a semicolon. In the form of key = value pair.
3. Reset Cookie Value
Code:
function resetOnceValue() {
document.cookie = "value1=; expires=Sat, 02 Jul ";
}
How to Delete a Cookie in JavaScript?
Sometimes we want to delete some cookies value. But to delete the value we just set the expire date attribute to some past value.
Code:
<html>
<head>
<script type = "text/javascript">
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
</script>
</head>
<body>
<input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</body>
</html>
Output:
Conclusion
So cookies basically solve the problem of how we can remember the user and their information. It saves as bane-value pair. It uses a different method to check whether the user is login or not example authenticates cookie method. Without this type of method, we can decide that the server should send the information or not.
Recommended Articles
This is a guide to Cookies in JavaScript. Here we discuss the basic concept, working, syntax, and how to delete cookie in javascript. You may also look at the following articles to learn more-