5.1 Basic Cookie Properties
Cookies are small pieces of data that websites can save on the client side (in the user's browser). They appeared 20 years before localStorage and have been helping to perform similar functions ever since. Even now, they are often used to save session state information, user preferences, tracking, and other tasks.
Main Cookie Properties:
- Name and Value (name=value): a key-value pair that stores data.
- Domain and Path (domain, path): determine which URLs and domains the cookies apply to.
- Lifetime (expires, max-age): specifies when the cookie expires and is deleted.
- Security (secure, HttpOnly): indicates how and when cookies can be transmitted.
Setting Cookies
Cookies can be set using JavaScript or server-side code. In JavaScript, this is done using the document.cookie property.
Example of Setting a Cookie with JavaScript:
document.cookie = "username=JohnDoe";
Additional Cookie Parameters:
- expires: specifies the expiration date of the cookie. After this date, the cookie will be deleted.
- path: determines the path for which the cookie is valid. Usually set to / to make the cookie accessible across the entire site.
- domain: specifies the domain for which the cookie is valid.
- secure: if set, the cookie will only be transmitted over HTTPS.
- HttpOnly: if set, the cookie cannot be accessed via JavaScript (only server-side).
Example of Setting a Cookie with Additional Parameters:
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
5.2 Managing Cookies
1. Reading Cookies
All cookies for the current document are stored in one long string in document.cookie. To get a cookie value, you need to parse this string.
Example of Reading a Cookie:
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
return null;
}
// Getting the value of "username" cookie
const username = getCookie('username');
console.log(username); // Outputs: JohnDoe
2. Updating Cookies
To update a cookie's value, simply set it again with the same name but new value and parameters.
Example of Updating a Cookie:
document.cookie = "username=JaneDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
3. Deleting Cookies
To delete a cookie, you need to set an expired expiration date.
Example of Deleting a Cookie:
// Setting an expired expiration date
document.cookie = "username=JohnDoe; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
5.3 Cookie Usage Examples
Explanation:
setCookie
: sets a cookie with a given name, value, and lifespan (in days)getCookie
: returns the value of the cookie with the given namedeleteCookie
: deletes a cookie with the given name
Example:
<!DOCTYPE html>
<html>
<head>
<title>Cookie Example</title>
</head>
<body>
<button onclick="handleSetCookie()">Set Cookie</button>
<button onclick="handleGetCookie()">Get Cookie</button>
<button onclick="handleDeleteCookie()">Delete Cookie</button>
<script>
function setCookie(name, value, days) {
let expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i].trim();
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function deleteCookie(name) {
document.cookie = name + '=; Max-Age=0; path=/';
}
function handleSetCookie() {
setCookie('username', 'JohnDoe', 7);
alert('Cookie "username" assigned value "JohnDoe" for 7 days');
}
function handleGetCookie() {
const cookieValue = getCookie('username');
if (cookieValue) {
alert('Cookie "username" has value: ' + cookieValue);
} else {
alert('Cookie "username" not found');
}
}
function handleDeleteCookie() {
deleteCookie('username');
alert('Cookie "username" deleted');
}
</script>
</body>
</html>
5.4 Setting Cookies Server-Side
Let's look at working with HttpOnly and Secure cookies on the server (Node.js).
Example:
const express = require('express');
const app = express();
app.get('/setcookie', (req, res) => {
res.cookie('secureServerCookie', 'ServerJohnDoe', {
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
httpOnly: true,
secure: true,
sameSite: 'strict'
});
res.send('Secure server cookie set');
});
app.get('/getcookie', (req, res) => {
const cookie = req.cookies.secureServerCookie;
res.send(`Cookie value: ${cookie}`);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Examples of Using Cookies:
- Authentication: cookies are often used to store session tokens that authenticate the user between requests.
- User Preferences: cookies can store user settings like interface language or themes.
- User Tracking: cookies can be used to track user behavior on the site for analytics and content personalization.
GO TO FULL VERSION