Secure Cookies
Secure Cookies
If you want to ensure that a cookie is only sent over secure connections
(HTTPS), you can add the Secure option when creating it:
This means the cookie will be available across all subdomains of example.com, such as
blog.example.com.
❌ Deleting Cookies
If you want to delete a cookie, you can simply set its expiration date to a past date.
This code deletes the cookie named user because its expiration date is set earlier than
the current date.
📋 Complete Example: Creating, Storing, and
Retrieving a Cookie
Now that you know how to create, store, and retrieve cookies, let’s look at a full
example of cookie management on a web page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Cookie Management</title>
<script>
// Function to create a cookie
function createCookie(name, value, days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 *
1000));
let expiration = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + ";" + expiration +
"; path=/";
}
This example creates a cookie named user with the value "John" and stores it for 7
days. When you click the button, the cookie is retrieved, and its value is displayed in an
alert box.
SECURE COOKIE EXAMPLE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script>
function getCookie(name) {
return null;
}
// Create a secure cookie and retrieve its value
function manageSecureCookie() {
if (secureToken) {
} else {
</script>
</head>
<body>
</body>
</html>
Key Points:
You can test this code only on an HTTPS-enabled site; otherwise, the browser will
ignore the Secure attribute.
Conclusion
Cookies in JavaScript are powerful tools for storing and retrieving user data in the
browser. With what you've learned today, you can create cookies, store them securely,
retrieve them to personalize the user experience, and delete them when they are no
longer needed.
Now that you know all the secrets of cookies, it's time to roll up your sleeves and start
managing cookies in your web applications!