How to create and read value from cookie ?
Last Updated :
31 Mar, 2020
The web servers host the website. The client-server makes a request for data from the webserver and the webserver fetches the required pages and responds to the client by sending the requested pages. The web server communicates with the client-server using HTTP (HyperText Transfer Protocol). HTTP is a stateless protocol which means the server needs not to retain the user information once the transaction ends and the connection is closed. The web browser is an example of a client-server which communicates with the web server using HTTP. HTTP prevents long engagement of the client with the webserver and the connection is closed automatically once the request is serviced. But often it is required to store the user information for future references. One of the most common uses of cookies is for authentication. Cookies serve the purpose of retaining user information even when the connection is lost. Cookies are data, stored in text files, on the computer.
Cookies comprise of five variable fields:
- Expires:Specifies when the cookie will expire. If left empty the cookie expires immediately when the connection is lost.
- Domain: Specifies the domain name of the website.
- Name=Value: Cookies are stored in the form of name-value pairs.
- Path: Specifies the webpage or directory that sets the cookie.
- Secure: Specifies whether the cookie can be retrieved by any server (secure or non-secure).
However, cookies can store only a small amount of data like
userID or
sessionID. Clearing the cookies will logout the user of every site that it had logged in. HTTP can be made stateful by using cookies. Stateful web applications store the information from the previous requests and can use it for serving future requests.
Working Principle: When the client or web browser establishes a connection with the webserver, the webserver sends some data to the browser in the form of a cookie. The browser may accept or reject the cookie. If the browser accepts it, the cookie gets stored in the hard disk of the client device. The CGI scripts on the server can read and write cookie values that are stored on the client, so when the client visits the same website again it retrieves the cookie data from the browser. JavaScript can be used to manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies for the current web page. The code below demonstrates how JavaScript can be used to create and read a value from the cookie.
Create cookie using JavaScript: This function creates a cookie using the field-name, field-value, and expiry date. The path is left blank such that it applies to the current webpage. However, we can specify any other webpage or directory name.
Program:
javascript
function createCookie(fieldname, fieldvalue, expiry) {
var date = new Date();
date.setTime(date.getTime()+ (expiry*24*60*60*1000));
var expires = "expires=" + date.toGMTString();
document.cookie = fieldname + "=" + fieldvalue +
";" + expires + ";path=/";
}
Read cookie using JavaScript: This function retrieves the cookie data stored in the browser. The cookie string is automatically encoded while sending it from the server to the browser. Hence it needs to be decoded before the actual data can be retrieved. Next, the decoded string is split into an array to get all the cookie name-value pairs. Loop through the array to find the field-name and respective field-values. If the cookie is found, the value is returned else the function returns the empty string.
Program:
javascript
function readCookie(cname) {
var name = cname + "=";
var decoded_cookie = decodeURIComponent(document.cookie);
var carr = decoded_cookie.split(';');
for(var i=0; i<carr.length;i++){
var c = carr[i];
while(c.charAt(0)==' '){
c=c.substring(1);
}
if(c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Create and read cookies using JavaScript: When the webpage is loaded the
runApp() function is called and it checks if there exists a cookie in the browser it is retrieved else a new cookie is created for the same.
Program:
html
<!DOCTYPE html>
<html>
<head>
<title>
Create and read cookies
using JavaScript
</title>
<script type="text/javascript">
function createCookie(fieldname, fieldvalue, expiry) {
var date = new Date();
date.setTime(date.getTime()+ (expiry*24*60*60*1000));
var expires = "expires=" + date.toGMTString();
document.cookie = fieldname + "=" + fieldvalue
+ ";" + expires + ";path=/";
}
function readCookie(cname) {
var name = cname + "=";
var decoded_cookie =
decodeURIComponent(document.cookie);
var carr = decoded_cookie.split(';');
for(var i=0; i<carr.length;i++){
var c = carr[i];
while(c.charAt(0)==' '){
c=c.substring(1);
}
if(c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function runApp() {
var user = readCookie("username");
if(user != ""){
alert("Hello "+user);
}else{
user=prompt("Enter your name: ", "");
if(user!= "" && user!=null){
createCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="runApp()"></body>
</html>
Output:
- Creating Cookie:

- Reading Cookie:

Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read