Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create and read the value from cookies
Cookies are small pieces of data stored in the user's browser by web applications. They consist of name-value pairs and are sent back to the server with each HTTP request, allowing websites to remember user information across sessions.
Syntax
Following is the syntax to create a cookie using JavaScript
document.cookie = "cookieName=cookieValue; expires=date; path=/";
Following is the syntax to read cookies
var allCookies = document.cookie;
Parameters
-
cookieName The identifier for the cookie (e.g., "username", "sessionId").
-
cookieValue The data stored in the cookie (e.g., "john_doe", "12345").
-
expires The expiration date in GMT format. If omitted, the cookie expires when the browser closes.
-
path The URL path where the cookie is valid. "/" makes it available for the entire website.
Creating Cookies
To create a cookie, we assign a formatted string to document.cookie. The browser automatically handles the storage and retrieval process.
Example Basic Cookie Creation
<!DOCTYPE html>
<html>
<head>
<title>Creating Cookies</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Cookie Creation Example</h2>
<button onclick="createCookie()">Create Cookie</button>
<button onclick="showCookies()">Show All Cookies</button>
<p id="result"></p>
<script>
function createCookie() {
var cookieName = "username";
var cookieValue = "john_doe";
var expiryDays = 30;
var date = new Date();
date.setTime(date.getTime() + (expiryDays * 24 * 60 * 60 * 1000));
var expires = "expires=" + date.toUTCString();
document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";path=/";
document.getElementById("result").innerHTML = "Cookie created: " + cookieName + "=" + cookieValue;
}
function showCookies() {
var cookies = document.cookie;
if (cookies) {
document.getElementById("result").innerHTML = "All cookies: " + cookies;
} else {
document.getElementById("result").innerHTML = "No cookies found";
}
}
</script>
</body>
</html>
The output shows the cookie creation and display functionality
Cookie created: username=john_doe All cookies: username=john_doe
Reading Cookies
Reading cookies requires parsing the document.cookie string since it returns all cookies as a single semicolon-separated string.
Example Reading Specific Cookie Values
<!DOCTYPE html>
<html>
<head>
<title>Reading Cookies</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Cookie Reading Example</h2>
<button onclick="setCookies()">Set Sample Cookies</button>
<button onclick="readSpecificCookie()">Read Username Cookie</button>
<p id="output"></p>
<script>
function setCookies() {
document.cookie = "username=alice; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
document.cookie = "theme=dark; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
document.getElementById("output").innerHTML = "Sample cookies set: username and theme";
}
function getCookieValue(cookieName) {
var name = cookieName + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var cookieArray = decodedCookie.split(';');
for (var i = 0; i < cookieArray.length; i++) {
var cookie = cookieArray[i].trim();
if (cookie.indexOf(name) === 0) {
return cookie.substring(name.length, cookie.length);
}
}
return "";
}
function readSpecificCookie() {
var username = getCookieValue("username");
if (username) {
document.getElementById("output").innerHTML = "Username cookie value: " + username;
} else {
document.getElementById("output").innerHTML = "Username cookie not found";
}
}
</script>
</body>
</html>
The output demonstrates reading specific cookie values
Sample cookies set: username and theme Username cookie value: alice
Complete Cookie Management System
Following example demonstrates a complete cookie management system with create, read, and user interaction
<!DOCTYPE html>
<html>
<head>
<title>Complete Cookie System</title>
</head>
<body onload="checkUserCookies()" style="font-family: Arial, sans-serif; padding: 20px;">
<h1 style="text-align: center; color: #2c3e50;">Welcome to TutorialsPoint</h1>
<div id="userInfo" style="background: #ecf0f1; padding: 15px; border-radius: 5px; margin: 10px 0;"></div>
<button onclick="clearUserData()">Clear User Data</button>
<script>
function createCookie(cookieName, cookieValue, expiryDays) {
var date = new Date();
date.setTime(date.getTime() + (expiryDays * 24 * 60 * 60 * 1000));
var expires = "expires=" + date.toUTCString();
document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";path=/";
}
function readCookieValue(cookieName) {
var name = cookieName + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var cookieArray = decodedCookie.split(';');
for (var i = 0; i < cookieArray.length; i++) {
var cookie = cookieArray[i].trim();
if (cookie.indexOf(name) === 0) {
return cookie.substring(name.length, cookie.length);
}
}
return "";
}
function checkUserCookies() {
var username = readCookieValue("client_name");
var location = readCookieValue("client_location");
if (username && location) {
document.getElementById("userInfo").innerHTML =
"<h3>Welcome back, " + username + " from " + location + "!</h3>" +
"<p>Your information was retrieved from cookies.</p>";
} else {
var name = prompt("Please enter your name:", "");
var city = prompt("Please enter your city:", "");
if (name && city) {
createCookie("client_name", name, 30);
createCookie("client_location", city, 30);
document.getElementById("userInfo").innerHTML =
"<h3>Hello " + name + " from " + city + "!</h3>" +
"<p>Your information has been saved in cookies for 30 days.</p>";
}
}
}
function clearUserData() {
document.cookie = "client_name=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
document.cookie = "client_location=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
document.getElementById("userInfo").innerHTML = "<p>User data cleared. Refresh the page to enter new information.</p>";
}
</script>
</body>
</html>
When first visited, the page prompts for user information and stores it in cookies. On subsequent visits, it welcomes the user back with their stored information.
Cookie Properties and Options
Cookies support several optional attributes that control their behavior
| Attribute | Description | Example |
|---|---|---|
| expires | Sets the expiration date | expires=Fri, 31 Dec 2024 23:59:59 GMT |
| max-age | Sets expiration in seconds | max-age=3600 (1 hour) |
| path | Restricts cookie to specific path | path=/admin |
| domain | Restricts cookie to specific domain | domain=.example.com |
| secure | Only sends over HTTPS | secure |
| SameSite | Controls cross-site request behavior | SameSite=Strict |
Best Practices
-
Set expiration dates Always specify when cookies should expire to prevent indefinite storage.
-
Use descriptive names Choose clear, meaningful names for your cookies.
-
Minimize data storage Cookies have size limits (4KB) and are sent with every request.
-
Consider security Use secure and HttpOnly flags for sensitive data when possible.
-
Handle missing cookies gracefully Always check if a cookie exists before using its value.
Conclusion
Cookies provide a simple mechanism for storing small amounts of user data in web browsers. By using document.cookie to create and read cookies, developers can maintain user preferences and session information across page visits. Always implement proper expiration dates and consider security implications when working with sensitive user data.
