If you've read through the previous blog post, you now know what cookies are and why you need a cookie policy. In this tutorial, we’ll go a step further and walk through how to create a cookie policy and implement it in your web app using JavaScript. We’ll also look at how to manage cookies and give users the ability to control their cookie settings.
Step 1: The HTML Structure of Your Cookie Policy Page
First things first, we need a place to display the cookie policy to users. You should create a Cookie Policy page where users can easily access the information. Here’s a basic HTML structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie Policy</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Our Cookie Policy 🍪</h1>
</header>
<main>
<section id="what-are-cookies">
<h2>What Are Cookies?</h2>
<p>Cookies are small files stored on your device to remember information about you, like your preferences and previous activity on our site.</p>
</section>
<section id="types-of-cookies">
<h2>Types of Cookies We Use</h2>
<ul>
<li><strong>Essential Cookies:</strong> These keep the website functioning.</li>
<li><strong>Analytics Cookies:</strong> These track how you interact with our site to improve performance.</li>
<li><strong>Advertising Cookies:</strong> These help us serve you relevant ads.</li>
</ul>
</section>
<section id="how-to-manage-cookies">
<h2>How to Manage Your Cookies</h2>
<p>You can manage or disable cookies directly in your browser settings. Disabling cookies might affect your experience on our site.</p>
</section>
</main>
</body>
</html>
Step 2: Setting Cookies with JavaScript 🍫
To store cookies in your web app, you can use JavaScript. Here’s how to create and set cookies in JavaScript:
// Function to set a cookie
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=/";
}
// Example: Setting a cookie named "userConsent" that expires in 30 days
setCookie("userConsent", "accepted", 30);
This function allows you to create a cookie by specifying its name, value, and how long it should last before expiring.
Step 3: Checking for and Reading Cookies 🍪
To check if a user has already accepted your cookie policy, you can read cookies with this simple JavaScript function:
// Function to get a cookie by name
function getCookie(name) {
const nameEQ = name + "=";
const cookiesArray = document.cookie.split(';');
for (let i = 0; i < cookiesArray.length; i++) {
let cookie = cookiesArray[i].trim();
if (cookie.indexOf(nameEQ) === 0) return cookie.substring(nameEQ.length, cookie.length);
}
return null;
}
// Example: Checking if the user has accepted the cookie policy
const userConsent = getCookie("userConsent");
if (userConsent === "accepted") {
console.log("User has accepted the cookie policy.");
} else {
console.log("User has not accepted the cookie policy.");
}
This function searches for a specific cookie by its name and returns its value if found.
Step 4: Implementing a Cookie Consent Banner 📢
Now that you can set and read cookies, it’s time to create a consent banner. When the user first visits the site, they’ll see a banner asking if they accept your cookie policy. If they accept, you’ll set a cookie to remember their choice.
Here’s the HTML and JavaScript for the consent banner:
<div id="cookie-banner" style="display: none; position: fixed; bottom: 0; background: #333; color: #fff; padding: 10px; width: 100%; text-align: center;">
<p>We use cookies to improve your experience. <a href="cookie-policy.html" style="color: #fff;">Read more</a></p>
<button id="accept-cookies" style="background: #28a745; color: #fff; border: none; padding: 10px 20px; cursor: pointer;">Accept</button>
</div>
<script>
// Check if the user has already accepted cookies
if (!getCookie("userConsent")) {
document.getElementById("cookie-banner").style.display = "block";
}
// Set the cookie when the user accepts
document.getElementById("accept-cookies").addEventListener("click", function() {
setCookie("userConsent", "accepted", 30);
document.getElementById("cookie-banner").style.display = "none";
});
</script>
In this code:
- The banner will only appear if the user hasn't previously accepted the cookie policy (i.e., if there’s no
userConsent
cookie). - When the user clicks the Accept button, a
userConsent
cookie is created, and the banner is hidden.
Step 5: Letting Users Manage Their Cookies ⚙️
As part of the cookie policy, users should be able to manage their cookies. Most browsers allow users to manage their cookies through settings, but you can also offer a simple "delete cookie" option within your app:
// Function to delete a cookie
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
// Example: Deleting the "userConsent" cookie
deleteCookie("userConsent");
// Show the cookie banner again after deleting the cookie
document.getElementById("cookie-banner").style.display = "block";
This function deletes the specified cookie by setting its expiration date to a past date.
Step 6: Styling Your Cookie Policy 🍬
You can style your cookie banner and policy page with CSS to make them visually appealing. Here’s a basic example:
#cookie-banner {
position: fixed;
bottom: 0;
background: #333;
color: #fff;
padding: 10px;
width: 100%;
text-align: center;
}
#accept-cookies {
background: #28a745;
color: #fff;
border: none;
padding: 10px 20px;
cursor: pointer;
}
a {
color: #fff;
}
Step 7: Testing and Iterating 🔍
After implementing your cookie policy, test your app thoroughly:
- Make sure the consent banner appears on the first visit.
- Confirm the banner disappears after acceptance and doesn't reappear on subsequent visits.
- Check the cookies in your browser's developer tools to ensure they’re being set correctly.
Step 8: Updating Your Policy 📅
Cookie policies aren’t a one-and-done thing. If your app starts using new cookies or third-party services that use cookies (e.g., Google Analytics or Facebook Pixel), update your cookie policy and banner to reflect these changes.
Conclusion
And there you have it! A complete guide to creating a cookie policy, from setting cookies to managing user consent. With this in place, you’ll not only be compliant with privacy regulations like GDPR, but you’ll also ensure that your users feel informed and empowered.
Happy coding, and enjoy baking those (digital) cookies! 🍪
About Me
As a dedicated remote web developer, I specialize in crafting modern, scalable web applications with a focus on performance and user experience. My expertise spans across full-stack development, utilizing cutting-edge technologies and best practices to deliver tailored solutions for diverse client needs. I’m committed to creating responsive, dynamic websites that bring ideas to life. Explore my portfolio here to see my latest projects, and connect with me on LinkedIn to discuss how I can help bring your next project to fruition!
References:
Happy coding! 🎉
Top comments (0)