0% found this document useful (0 votes)
10 views5 pages

Secure Cookies

The document provides a comprehensive guide on managing cookies in JavaScript, including creating, retrieving, and deleting cookies with various attributes such as Secure and Domain. It includes examples of cookie management functions and highlights key points about cookie security and expiration. The conclusion emphasizes the importance of cookies for enhancing user experience in web applications.

Uploaded by

rportugali01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views5 pages

Secure Cookies

The document provides a comprehensive guide on managing cookies in JavaScript, including creating, retrieving, and deleting cookies with various attributes such as Secure and Domain. It includes examples of cookie management functions and highlights key points about cookie security and expiration. The conclusion emphasizes the importance of cookies for enhancing user experience in web applications.

Uploaded by

rportugali01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

🔐 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:

document.cookie = "token=abc123; Secure; path=/";

🌍 Cookies for Subdomains Only: Domain


You can make a cookie valid only for certain subdomains by using the Domain attribute.

document.cookie = "user=John; domain=example.com; path=/";

This means the cookie will be available across all subdomains of example.com, such as
blog.example.com.

🧩 Flowchart for Retrieving a Cookie


1. The user performs an action.
2. JavaScript searches for the requested cookie.
3. Check if the cookie exists.
4. Return the value of the cookie if it exists.
5. Return null if it does not exist.

❌ Deleting Cookies
If you want to delete a cookie, you can simply set its expiration date to a past date.

Example of Deleting a Cookie

// Delete a cookie by setting its expiration date in the past


document.cookie = "user=; expires=Thu, 01 Jan 1970 00:00:00 UTC;
path=/";

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=/";
}

// Function to get a cookie


function getCookie(name) {
let cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
if (cookie.indexOf(name + '=') === 0) {
return cookie.substring((name + '=').length,
cookie.length);
}
}
return null;
}

// Create a cookie and display its value


function manageCookies() {
createCookie('user', 'John', 7);
let user = getCookie('user');
alert('The stored user is: ' + user);
}
</script>
</head>
<body>
<button onclick="manageCookies()">Create and Get Cookie</button>
</body>
</html>

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">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Secure Cookie Example</title>

<script>

// Function to create a secure cookie

function createSecureCookie(name, value, days) {

let date = new Date();

date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); //


Set expiration date

let expires = "expires=" + date.toUTCString(); // Convert


expiration date to UTC format

document.cookie = name + "=" + value + ";" + expires + "; Secure;


SameSite=Strict; path=/";

// Function to get a cookie by name

function getCookie(name) {

let cookies = document.cookie.split(';');

for (let i = 0; i < cookies.length; i++) {

let cookie = cookies[i].trim();

if (cookie.indexOf(name + '=') === 0) {

return cookie.substring((name + '=').length,


cookie.length);

return null;

}
// Create a secure cookie and retrieve its value

function manageSecureCookie() {

// Create a secure cookie

createSecureCookie('secureToken', 'secureValue123', 7);

// Retrieve the secure cookie

let secureToken = getCookie('secureToken');

if (secureToken) {

alert('The secure cookie value is: ' + secureToken);

} else {

alert('No secure cookie found.');

</script>

</head>

<body>

<h1>Secure Cookie Example</h1>

<button onclick="manageSecureCookie()">Create and Retrieve Secure


Cookie</button>

</body>

</html>

Key Points:

1. Secure: Ensures the cookie is transmitted only over HTTPS.


2. SameSite=Strict: Restricts the cookie from being sent with cross-site
requests, enhancing security.
3. path=/: Makes the cookie available to all paths of the website.
4. expires: Specifies when the cookie should expire.

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!

Summary of Key Methods

• document.cookie: Create, read, and delete cookies.


• expires: Set the cookie's expiration date.
• Secure: Make the cookie accessible only over HTTPS connections.
• path and domain: Control where the cookie is valid.

You might also like