A cookie is a small text file that allows you to store a limited amount of data (usually up to 4KB) on the user's computer. It is commonly used to retain information like user preferences, which the website can retrieve to personalize the page for future visits.
Cookies were initially designed as a client-side storage mechanism primarily for use by server-side scripting languages such as PHP, ASP, etc. However, cookies can also be created, accessed, and modified directly using JavaScript, although the process can be somewhat intricate and messy.
Tip: Cookies can store up to 4 KB of data, including their names and values. If a cookie exceeds this length, it will be trimmed to fit. Additionally, whenever the browser requests a page from the server, all data stored in the cookie is automatically sent to the server along with the request.
Warning: Avoid storing sensitive data such as passwords or credit card information in cookies, as they could potentially be manipulated by malicious users.
In JavaScript, you can manage cookies using the document.cookie
property, which represents all cookies associated with a document.
To create or store a new cookie, assign a name=value
string to this property, like this:
A cookie value cannot contain semicolons, commas, or spaces. Therefore, you should use encodeURIComponent()
to encode values containing these characters before storing them in a cookie. Similarly, use decodeURIComponent()
when reading the cookie value.
By default, a cookie lasts only for the current browser session and is deleted when the user exits the browser. To make a cookie persist beyond the current session, specify its lifetime in seconds using the max-age
attribute. For example, the following cookie will last for 30 days:
You can also set the lifetime of a cookie using the expires
attribute, which takes an exact date (in GMT/UTC format) when the cookie should expire, rather than an offset in seconds.
Here's a function that sets a cookie with an optional max-age
attribute. You can also use this function to delete a cookie by passing the value 0
for the daysToLive
parameter.
function setCookie(name, value, daysToLive) {
// Encode value in order to escape semicolons, commas, and whitespace
var cookie = name + "=" + encodeURIComponent(value);
if(typeof daysToLive === "number") {
/* Sets the max-age attribute so that the cookie expires
after the specified number of days */
cookie += "; max-age=" + (daysToLive*24*60*60);
document.cookie = cookie;
}
}
By default, a cookie is accessible to all web pages within the same directory and any subdirectories of that directory. However, you can specify a path
to make the cookie available to all web pages in that path and its subdirectories. For example, setting the path to /
makes the cookie available throughout the entire website, regardless of which page originally created the cookie.
Additionally, you can use the domain
attribute to allow a cookie to be accessed across subdomains. By default, cookies are only available to pages within the domain they were set in.
If a cookie created on blog.example.com
sets its path
attribute to /
and its domain
attribute to example.com
, that cookie will also be accessible to all web pages on backend.example.com
, portal.example.com
, and so forth. However, cookies cannot be shared outside of their domain.
There's also a boolean attribute named secure
. If specified, the cookie will only be transmitted over a secure (encrypted) connection, such as HTTPS.
Reading a cookie is slightly more complex because the document.cookie
property returns a string that lists all cookies as a semicolon and space separated name=value
pairs (for example, firstName=John; lastName=Doe;
). This string does not include the attributes like expires
, path
, domain
, etc., that may have been set for each cookie.
To retrieve a specific cookie from this list, you need to use the split()
method to break it into individual name=value
pairs and then search for the specific name, as demonstrated below:
function getCookie(name) {
// Split cookie string and get all individual name=value pairs in an array
var cookieArr = document.cookie.split(";");
// Loop through the array elements
for(var i = 0; i < cookieArr.length; i++) {
var cookiePair = cookieArr[i].split("=");
/* Removing whitespace at the beginning of the cookie name
and compare it with the given string */
if(name == cookiePair[0].trim()) {
// Decode the cookie value and return
return decodeURIComponent(cookiePair[1]);
}
}
// Return null if not found
return null;
}
Next, we will create another function named checkCookie()
. This function checks if the firstName
cookie is set by using the earlier defined getCookie()
function. If the cookie is set, it displays a greeting message. If not, it prompts the user to enter their first name and saves it in the cookie using the existing setCookie()
function.
function checkCookie() {
// Get cookie using our custom function
var firstName = getCookie("firstName");
if(firstName != "") {
alert("Welcome again, " + firstName);
} else {
firstName = prompt("Please enter your first name:");
if(firstName != "" && firstName != null) {
// Set cookie using our custom function
setCookie("firstName", firstName, 30);
}
}
}
To update or modify a cookie, you need to create a new cookie with the same name
and path
as the existing one. If you create a cookie with the same name but a different path, it will add an additional cookie instead of updating the existing one. Here's an example:
// Creating a cookie
document.cookie = "firstName=Christopher; path=/; max-age=" + 30*24*60*60;
// Updating the cookie
document.cookie = "firstName=Alexander; path=/; max-age=" + 365*24*60*60;
To delete a cookie, you can overwrite it by setting the same name
with an empty or arbitrary value, and setting its max-age
attribute to 0. If you originally set a path
and domain
for the cookie, you must include these attributes when deleting it. Here's how you can do it:
// Deleting a cookie
document.cookie = "firstName=; max-age=0";
// Specifying path and domain while deleting cookie
document.cookie = "firstName=; path=/; domain=example.com; max-age=0";
Alternatively, you can delete a cookie using the expires
attribute by setting its value (the expiration date) to a date that has already passed, like shown below: