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 cookies in JavaScript?
Using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.
The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this:
document.cookie = "key1=value1;key2=value2;expires=date";
Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible.
Note ? Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript encodeURIComponent() function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding decodeURIComponent() function when you read the cookie value.
Basic Cookie Creation
Here's a simple example of creating a cookie with a name and value:
<!DOCTYPE html>
<html>
<head>
<title>Cookie Example</title>
</head>
<body>
<script>
// Create a simple cookie
document.cookie = "username=JohnDoe";
console.log("Cookie created: username=JohnDoe");
// Create cookie with expiration date
let expiryDate = new Date();
expiryDate.setTime(expiryDate.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days
document.cookie = "preferences=darkmode; expires=" + expiryDate.toUTCString();
console.log("Cookie with expiry created");
// Display all cookies
console.log("All cookies: " + document.cookie);
</script>
</body>
</html>
Cookie created: username=JohnDoe Cookie with expiry created All cookies: username=JohnDoe; preferences=darkmode
Interactive Cookie Example
Here's a complete example that sets a customer name in a cookie using a form:
<!DOCTYPE html>
<html>
<head>
<title>Set Cookie Example</title>
<script>
function WriteCookie() {
if(document.myform.customer.value == "") {
alert("Enter some value!");
return;
}
let cookievalue = encodeURIComponent(document.myform.customer.value);
document.cookie = "name=" + cookievalue;
document.getElementById("result").innerHTML = "Setting Cookie: name=" + cookievalue;
}
</script>
</head>
<body>
<form name="myform">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
<div id="result"></div>
</body>
</html>
Cookie Attributes
Cookies can have several attributes to control their behavior:
<!DOCTYPE html>
<html>
<body>
<script>
// Cookie with multiple attributes
let expires = new Date();
expires.setTime(expires.getTime() + (30 * 24 * 60 * 60 * 1000)); // 30 days
document.cookie = "sessionId=abc123; expires=" + expires.toUTCString() +
"; path=/; secure; SameSite=Strict";
console.log("Cookie with attributes created");
console.log("Current cookies: " + document.cookie);
</script>
</body>
</html>
Cookie with attributes created Current cookies: sessionId=abc123
Common Cookie Attributes
| Attribute | Purpose | Example |
|---|---|---|
expires |
Sets expiration date | expires=Wed, 01 Jan 2025 00:00:00 GMT |
path |
Specifies URL path | path=/ |
domain |
Specifies domain | domain=example.com |
secure |
HTTPS only | secure |
Conclusion
Creating cookies in JavaScript is straightforward using document.cookie. Always encode special characters and set appropriate expiration dates for better cookie management.
