JavaScript Cookies
JavaScript Cookie is used to store some useful information on the client's browser which can be accessed in the consecutive HTTP requests.
A cookie is a small file containing information, stored at client's computer or to be more specific in the client's browser. Each time when the client requests for a web page, the server refers to the created cookie for information before displaying the requested web page.
Let's take a simple example to understand the concept of cookies, why its required and how we can use it. Well, if you have a website, which has no user login system, and on your website you have many articles. You want to add a new feature on your website, in which the articles which a user has read will be marked read on the website. But as you do not have a user login system so there is no way that you can save this user related data on your server(Database). In such case, cookies can be used. We can create a cookie, and store in the client's browser and in the cookie we can add the URLs(or some other identification) of the articles that the user has already read. When the user again visits any article, we can first check the cookie, if we find the the URL of the current article in the cookie, we can inform the user that you have already read it.
Well, this is how we can use cookies. To store useful information that we can retrieve in further requests to know about the user.
The size of the cookie depends on the browser but generally should not exceed 1K (1,024 bytes). So we should be careful with what all we store in our cookies.
A cookie is generally used to store the user information on a computer so that whenever the user visits the website again, you can know that the user is an old user of yours.
A cookie has several attributes, which contain vital information about the cookie such as its name, the domain name to which it belongs and the address of valid path within a domain.
Some commonly used attributes are given below:
1. Cookie Name Attribute
It represents a variable name and the corresponding value to be stored in the cookie.
2. Cookie Expires Attribute
It specifies the time when the cookie will be deleted. It is expressed as a Unix timestamp. In general a cookie is never deleted from the browser, it expires.
3. Cookie Domain Attribute
It represents a domain name(partial or complete) to which the cookie belongs.
For example, if the value for the valid domain attribute is www.studytonight.com then the client(browser) will send the cookie information to the web server as part of the HTTP request, every time the user visits the www.studytonight.com website.
NOTE: Browser will only provide the cookie which has the domain attribute value same as the current URL in the HTTP request.
4. Cookie Path Attribute
This attribute is used to create path specific cookies for the same domain name. For example, if we want to create a cookie for studytonight.com root path (/) and another cookie for studytonight.com/code/playground to be used in live coding section, then we can use the cookie path attribute to differentiate between the cookies.
It identifies websites based on various paths in the same domain. Setting this attribute to the server root(/) allows the entire domain to access the information stored in the cookie.
5. Cookie Secure Attribute
It restricts a browser from sending cookie information over unsecured connections. If not set, it allows the cookie to be sent over any type of HyperText Transfer Protocol(HTTP) connection.
The default value of the security flag attribute is 0. Setting the value to 1 allow the cookie to be sent over a secure HTTP connection only.
JavaScript Creating and Storing Cookies
In JavaScript, you can create your own cookies to store the user's information or any information you want.
To create a cookie, use document.cookie
property. Set the cookie value, path to specify where to store cookie and the expiry date to set lifetime of cookie.
Here is the syntax for creating a cookie:
document.cookie = cookieString;
where, the cookieString
is a string of form key=value, which will be saved in the cookie. Along with this information, we can provide information like max-age of cookie, expiry time of cookie, path attribute of cookie(its picked up automatically), etc. by separating each key=value pair with semicolon(;
).
Here is the syntax for each of the additional optional attribute that you can append to the cookieString to provide more information at the time of cookie creation.
Cookie Attribute |
Description |
;path=somepath |
By default cookie is created for the current URL, but we can change it by providing value for this attribute while creating a cookie.
For example:
document.write = "username=John Wick;path=/profile";
This cookie will be created for the path /profile for the current domain name.
|
;domain=domainName |
This is again picked up by default as the current domain name. Also, if you try to provide a different domain name than the one on which the JavaScript code is currently loaded the browser will ignore your request.
|
;max-age=max-age-in-seconds |
To specify the time for which the cookie should live or should not expire. It's value cane be 60*60*24*365 or 31536000 for a year, or 3600 for a day. |
;expires=date-in-GMTString-format |
This attribute is used to specify the exact time after which the cookie will expire. If we do not provide this attribute or the max-age attribute then the cookie is expired at the end of the current session for which cookie is created. |
;secure |
To specify that the cookie should only be provided over secured HTTP connections.
For example:
document.write = "username=John Wick;secure";
|
;samesite |
This attribute is used to prevent the browser from sending the cookie data for cross-site requests. |
Example Creating Cookies
In the code example below, we have created a cookie with some additional information,
document.cookie = "username=johnwick; expires=Thu, 17 May 2020 10:30:00 IST; path=/";
In the code above, we have created a cookie to store the name of website visitor. As you can see in the code example above, cookie is nothing but a string which has all the information appended, seprated by semicolon(;
).
JavaScript Reading Cookies
To read a cookie, we can use document.cookie
property. It will return all the stored cookie in the current location path.
var x = document.cookie;
Let's take a simple example to understand this:
<html>
<head>
<title>
Using onerror Event
</title>
<script type="text/javascript">
document.cookie = "name=johnwick";
document.cookie = "favorite_car=1969FordMustang";
function alertCookie() {
alert(document.cookie);
}
</script>
</head>
<body>
<!-- HTML body -->
<button onclick="alertCookie()">Show cookies</button>
</body>
</html>
name=johnwick; favorite_car=1969FordMustang
When you will click on the button, you will get the above output in the alert box. So, it's super easy to store cookies and then read them back.
JavaScript Update Cookie Value
To update the cookie, just set a new value for it and make sure the path should be same, so that it will update the cookie rather than create a new cookie.
document.cookie = "username=BruceWayne; expires=Sat, 15 Aug 2020 12:00:00 UTC; path=/";
It will overwrite the old cookie value.
JavaScript Delete Cookie
To delete a cookie, we need to set a past expiry date for the cookie to delete it immediately, or we can set an expiry date while creating the cookie to specify the time after which the cookie should be deleted.
document.cookie = "username=BruceWayne; expires=Thu, 10 Jan 2020 00:00:00 UTC; path=/;";
You should define the cookie path to ensure that you delete the right cookie.