JAVASCRIPT COOKIE
Cookies let you store user's data in the browser for you. A cookie is the most commonly used method for remembering user.
In this JavaScript cookie article, you will learn about cookies in-depth.
- What are cookies?
- how does cookies work
- Different options in cookie
- Get cookie
- Set cookie
- Update cookie
- Delete cookie
- Get and set cookie function
Table Of Contents
What are Cookies?
Cookies in browsers are small strings of user data that is stored in browsers.
A cookie is a part of the HTTP protocol which let you store users data in a browser for a period of time.
In most commercial and non-commercial websites it is required to maintain among different pages. For example, login information across the different webpage of any website is maintained through cookie information.
A cookie is one of the most efficient ways of tracking and remembering actions, interests, purchases, preferences, etc.
Cookies were invented to solve the problem of how to remembering users's information:
- when a visits any webpage then user's name can be stored in cookie
- Next time when user visit the page then cookie remembers the name
Cookies stores the information in key-value pair. Example:
username=john smith
How do cookies work?
- When a user request for something then the server detects it as a new user even when the user has already interacted with the server.
- So to recognize the old user server respond with a cookie.
- If the user accepts the cookie then the cookie is stored in the browser in form of plain text in a user's hard drive.
- Next time when the user arrives at another page of the same website then the browser sends the same cookie to the server for retrieval for the server to remember about this user.
Different options in cookie
Cookies are plain text data which store data in key-value pair. It consists of 5 variable-length fields:
- Expire - The date at which cookie will expire. If this field is blank then by the cookie will expire when the user quit the browser.
- Domain - It provides domain name (name) of the website.
- Path - The path or webpage that sets the cookie.
- Secure - This makes the cookie only accessible through a secure server. If the field contains the word "secure" then the cookie is only retrieved with a secure server while if this field is blank, there are no such restrictions.
- name=value - Cookies store data in a key-value pair.
Get cookie
JavaScript provides document.cookie
object which returns all the cookies associate with the document.
Let's check if your browser stores any cookie from this site.
let allCookies = document.cookie;
console.log(allCookies); // return empty string if no cookie
Try It
The document.cookie
returns all the cookie in 1 string saperated by a semicolon and a space, like: cookie1:value1; cookie2:value2; cookie3:value3;
Set cookie javascript
Using document.cookie
you can not only read cookie but can also create, update and delete the cookie.
To create a cookie set cookie data in key-value pairs.
document.cookie = "user=john smith"; // creating cookie
console.log(document.cookie); // read cookie
Try It
set cookie expire time
You can also set the expiry date of the cookie. The expiry date should be in UTC time.
By default, the cookie is deleted when the user quit the browser.
The following example sets a cookie that expires in 24 hours.
let time = new Date(new Date() + 24 * 60 * 60 * 1000);
time = time.toUTCString();
document.cookie = "user=john smith; expire=" + time; // setting 24 hour expiry time
console.log(document.cookie);
Try It
set cookie path
You can set what path or location cookie belongs to. The url path must be absolute, it makes cookie accessible in the page under those path.
For example, if cookie set in path /home then the cookie is accessible in /home, /home/shop, etc but not in /category or /offers.
You should usually set a cookie to the root path=/. By default, cookie belongs to the current page.
document.cookie = "user=john smith; path=/"; // setting path as root
console.log(document.cookie);
Try It
set cookie domain
A domain defines from where the domain is accessible. The default value is the site itself.
A cookie set at one site is practically not accessible at another site even if you set domain value to that site, also it is not accessible at its subdomain.
However, if you explicitly set the domain of the cookie then only it is accessible at sub-domain.
// never accessible at site2.com when set at site.com
document.cookie = "user=john smith; domain=/site2.com";
// only accessible at site.com and not at shop.site.com
document.cookie = "user=john smith;";
// accessible at all sub domain like shop.site.com
document.cookie = "user=jack johnson; domain=site.com";
Try It
set cookie secure
When mentioned the word "secure" then the cookie is only accessible at the secure server.
By default, if you set a cookie at http://site.com
then you can access it from https://site.com
and vice versa. but if "secure" is set in the cookie and cookie is set by HTTPS protocol then it is not accessible through HTTP protocol.
document.cookie = "user=john smith; secure;";
console.log(document.cookie);
Try It
Update existing cookie value in JavaScript
You can change the cookie the same way you created it.
Update the value of cookie using document.cookie
.
// OLDER - "user=john smith;"
document.cookie = "user=Bob johnson; expires=Mon, 12 Jan 2050 12:00:00 UTC; secure;"; // updating
console.log(document.cookie);
Try It
Delete cookie JavaScript
To delete a cookie just set the expiration date with a passed date, which makes cookie expired and gets deleted.
You must specify the cookie path to ensure right cookie deletion.
document.cookie = "user=john smith; expires=Mon, 12 Jan 2000 12:00:00 UTC; path=/"; // updating
console.log(document.cookie);
Try It
How to get and set cookies in javascript?
Here is an example below which creates a cookie by taking the user's name in the input.
If user already visited the page and filled the name then it alerts a message and welcomes the user.
There are 2 functions in the example below:
- A function to check the cookie
- A function to set the cookie
A function to set the cookie
If the cookie does not exist then we will set a cookie with an expiration time of 24 hours.
The function accepts cookie name, cookie value and expiration time in days.
function setCookie() {
let cookieName = prompt("Enter cookie name:");
let cookieValue = prompt("Enter cookie value:");
let expireDay = prompt("Enter expiry days:");
let now = new Date();
let expireTime = new Date(now + expireDay * 24 * 60 * 60 * 1000);
document.cookie = cookieName + "=" + cookieValue + "; " + "expire=" + expireTime.toUTCString() + "path=/";
}
A function to check the cookie
When a user visits the page then we will first check if the cookie exists or not.
If the cookie does not exist then we will use prompt
to take user name as input.
function checkCookie(cookieName) {
let allCookies = decodeURIComponent(document.cookie);
cookieArray = allCookies.split(';');
for (var i = 0; i < cookieArray.length; i++) {
name = cookieArray[i].split('=')[0];
value = cookieArray[i].split('=')[1];
if (name == cookieName) {
console.log("Welcome " + value);
return;
}
}
setCookie();
}
Here is complete working code:
function checkCookie(cookieName) {
let allCookies = decodeURIComponent(document.cookie);
cookieArray = allCookies.split(';');
cookieArray.forEach(cookie => {
cookie = cookie.trim();
console.log(cookie);
let name = cookie.split('=')[0];
let value = cookie.split('=')[1];
if (name == cookieName) {
console.log(name, value);
return;
}
});
// if cookie not found
// setCookie();
}
function setCookie() {
let cookieName = prompt("Enter cookie name:");
let cookieValue = prompt("Enter cookie value:");
let expireDay = prompt("Enter expiry days:");
let now = new Date();
let expireTime = new Date(now + expireDay * 24 * 60 * 60 * 1000);
document.cookie = cookieName + "=" + cookieValue + ";expires=" + expireTime.toUTCString();
}
checkCookie("user");
Try It