How to use the document.cookie Property In Javascript
The document.cookie property can directly interact with cookies. It’s a simple method for basic cookie management without external dependencies. Here, Cookies are stored in key-value pairs separated by semicolons. The “document. cookie” property allows us to set, retrieve, and delete these cookies.
Example: The example below shows how to set cookies session per visitor in JavaScript using the document.cookie Property.
<!DOCTYPE html>
<html>
<head>
<title>Set cookies session</title>
</head>
<body>
<h2>Welcome To GFG</h2>
<p>
Default code has been
loaded into the Editor
</p>
<script>
function storeUserState(stateName,
stateValue, expiryDays = 0) {
// Create a date object set to the current time.
const currentDate = new Date();
if (expiryDays > 0) {
currentDate.setTime(currentDate
.getTime() +
(expiryDays * 24 * 60 * 60 * 1000));
}
const expires = "expires=" +
currentDate.toUTCString();
//Build the cookie string with
//name, value, expiration, and path.
const cookieString =
`${stateName}=${stateValue};${expires};path=/`;
// Set the cookie using document.cookie
document.cookie = cookieString;
}
function retrieveUserState(stateName) {
const name = stateName + "=";
const decodedCookie = decodeURIComponent(document.cookie);
const stateEntries = decodedCookie.split(';');
for (let i = 0; i < stateEntries.length; i++) {
let stateEntry = stateEntries[i];
while (stateEntry.charAt(0) === ' ') {
stateEntry = stateEntry.substring(1);
}
if (stateEntry.indexOf(name) === 0) {
return stateEntry
.substring(name.length, stateEntry.length);
}
}
return "";
}
storeUserState("userSession", "loggedIn", 1);
const userState = retrieveUserState("userState");
console.log("Session value:", userState);
</script>
</body>
</html>
Output :
How to Set Cookies Session per Visitor in JavaScript?
Managing session cookies in JavaScript is essential for web developers to maintain user state and preferences across multiple sessions. The document. cookie property provides a basic mechanism for cookie management, utilizing JavaScript libraries or frameworks can offer enhanced security and flexibility.
Table of Content
- Using the document.cookie Property
- Using a Cookie Library
- Using a Express and cookie-parser