gdpr-cookie-consent
Version:
Lightweight, headless cookie consent library providing technical tools for implementing consent mechanisms. Data-attribute driven, no dependencies, framework-agnostic. Legal compliance is user's responsibility - consult legal professionals.
1,119 lines (912 loc) β’ 33.2 kB
Markdown
# πͺ GDPR Cookie Consent Library
[](https://github.com/CarterOgunsola/gdpr-cookie-consent)
[](LICENSE)
[](https://cdn.jsdelivr.net/npm/gdpr-cookie-consent)
[](https://github.com/CarterOgunsola/gdpr-cookie-consent)
A **production-ready**, **headless**, **data-attribute-driven** cookie consent library that provides technical tools for implementing cookie consent mechanisms. Built with security-first principles and comprehensive error handling.
> **π Version 1.0** features enhanced security with XSS protection, secure cookie implementation, comprehensive input validation, and production-ready error handling.
## βοΈ IMPORTANT LEGAL DISCLAIMER
**π¨ THIS IS A TECHNICAL TOOL ONLY - NOT LEGAL ADVICE**
This library provides technical functionality for cookie consent implementation but **DOES NOT GUARANTEE GDPR COMPLIANCE**. You are solely responsible for:
- β
**Consulting qualified legal professionals** before implementation
- β
**Ensuring your own legal compliance** with GDPR, CCPA, and other privacy laws
- β
**Proper cookie categorization** and privacy policy creation
- β
**Ongoing compliance** as regulations change
**See [DISCLAIMER.md](DISCLAIMER.md) for complete legal terms.**
## β¨ Features
- π¨ **Headless Architecture** - Bring your own HTML/CSS, no predefined styles
- π·οΈ **Data-Attribute Driven** - No hardcoded IDs or classes, maximum flexibility
- β‘ **Zero Dependencies** - Lightweight (~21KB minified), vanilla JavaScript
- π **Security First** - XSS protection, script validation, and secure cookie implementation
- π‘οΈ **Production Ready** - Comprehensive error handling and robust validation
- π§ **Configurable Categories** - Define analytics, marketing, functional, or custom categories
- π± **Responsive Ready** - Works on all devices and screen sizes
- βΏ **Accessibility First** - Keyboard navigation, ARIA support
- π **CDN Ready** - Single file deployment via jsDelivr
- π― **Webflow Perfect** - Designed specifically for visual builders
- π **Script Management** - Conditional loading/unloading based on consent
- πΎ **Persistent Storage** - Saves preferences with configurable duration
- π **Event Callbacks** - React to consent changes with custom logic
## π Table of Contents
- [Quick Start](#-quick-start)
- [Security Features](#-security-features)
- [Installation](#-installation)
- [Webflow Integration](#-webflow-integration)
- [Configuration](#-configuration)
- [Data Attributes](#-data-attributes)
- [API Reference](#-api-reference)
- [Examples](#-examples)
- [Customization](#-customization)
- [Browser Support](#-browser-support)
- [Troubleshooting](#-troubleshooting)
- [Security Best Practices](#-security-best-practices)
- [Production Deployment](#-production-deployment)
- [Contributing](#-contributing)
## π Quick Start
1. **Add the script to your HTML:**
```html
<script src="https://cdn.jsdelivr.net/npm/gdpr-cookie-consent@1.0.0/main.min.js"></script>
```
2. **Create your HTML structure with data attributes:**
```html
<!-- Cookie Banner -->
<div data-gdpr-banner style="display: none;">
<p>We use cookies to improve your experience.</p>
<button data-gdpr-action="accept-all">Accept All</button>
<button data-gdpr-action="show-preferences">Customize</button>
</div>
<!-- Preferences Modal -->
<div data-gdpr-modal style="display: none;">
<h2>Cookie Preferences</h2>
<div data-gdpr-categories></div>
<button data-gdpr-action="save-preferences">Save</button>
</div>
<!-- Category Template -->
<template data-gdpr-category-template>
<div class="cookie-category">
<h3 data-category-title></h3>
<p data-category-description></p>
<input type="checkbox" data-category-toggle />
</div>
</template>
```
3. **Initialize the library:**
```javascript
GDPRCookies.init({
categories: ['analytics', 'marketing', 'functional'],
onAccept: (preferences) => console.log('Accepted:', preferences),
onDecline: (preferences) => console.log('Declined:', preferences)
});
```
## π Security Features
This library is built with **security-first principles** and includes comprehensive protections for production environments:
### π‘οΈ XSS Protection
- **Script URL Validation**: All script URLs are validated to prevent malicious injections
- **Protocol Filtering**: Only `http:` and `https:` protocols are allowed
- **Safe DOM Manipulation**: Uses `textContent` and `createTextNode` instead of `innerHTML` where possible
- **Input Sanitization**: All user inputs and configurations are validated and sanitized
```javascript
// Example: Script validation prevents malicious URLs
GDPRCookies.addScript('analytics', 'javascript:alert("xss")'); // β Blocked
GDPRCookies.addScript('analytics', 'data:text/javascript,alert("xss")'); // β Blocked
GDPRCookies.addScript('analytics', 'https://trusted-domain.com/script.js'); // β
Allowed
```
### πͺ Secure Cookie Implementation
- **Secure Flag**: Automatically sets `Secure` flag for HTTPS sites
- **SameSite Protection**: Uses `SameSite=Strict` to prevent CSRF attacks
- **Proper Encoding**: All cookie values are safely encoded with `encodeURIComponent`
- **Domain Validation**: Smart domain handling for subdomain support
### π¨ Production-Ready Error Handling
- **Silent Failures**: Errors don't break the user experience
- **Debug Mode**: Detailed logging only in development environments (`localhost`, `127.0.0.1`)
- **Error Sanitization**: Sensitive information is never logged
- **Memory Management**: Error logs are limited to prevent memory leaks
```javascript
// Debug mode automatically detected
if (location.hostname === 'localhost') {
// Detailed console logging enabled
} else {
// Silent operation in production
}
```
### π Content Security Policy (CSP) Friendly
The library is designed to work with strict CSP policies:
```http
Content-Security-Policy:
script-src 'self' https://cdn.jsdelivr.net;
style-src 'self' 'unsafe-inline';
connect-src 'self';
```
### ποΈ Input Validation
- **Configuration Validation**: All init options are validated before use
- **Type Checking**: Strict type validation for all API methods
- **Boundary Checking**: String length limits and object depth validation
- **Graceful Degradation**: Invalid inputs don't crash the system
## π¦ Installation
### CDN (Recommended)
```html
<!-- Latest version -->
<script src="https://cdn.jsdelivr.net/npm/gdpr-cookie-consent@latest/main.min.js"></script>
<!-- Specific version -->
<script src="https://cdn.jsdelivr.net/npm/gdpr-cookie-consent@1.0.0/main.min.js"></script>
```
### NPM
```bash
npm install gdpr-cookie-consent
```
```javascript
import { GDPRCookies } from 'gdpr-cookie-consent';
```
### Direct Download
Download `main.min.js` from the [releases page](https://github.com/CarterOgunsola/gdpr-cookie-consent/releases) and include it in your project.
## π Webflow Integration
This library is specifically designed for Webflow developers. Here's how to integrate it:
### Step 1: Add the Script
In your Webflow project settings, go to **Custom Code** β **Head Code** and add:
```html
<script src="https://cdn.jsdelivr.net/npm/gdpr-cookie-consent@1.0.0/main.min.js"></script>
```
### Step 2: Design Your Components
1. **Create your cookie banner** using Webflow's visual designer
2. **Style it however you want** - the library provides no CSS
3. **Add the data attribute** `data-gdpr-banner` to your banner container
4. **Set initial style** to `display: none` in Webflow
### Step 3: Add Action Buttons
Add buttons to your banner and give them data attributes:
- `data-gdpr-action="accept-all"` - Accept all cookies
- `data-gdpr-action="show-preferences"` - Open preferences modal
- `data-gdpr-action="accept-essential"` - Accept only essential cookies
### Step 4: Create Preferences Modal
1. **Design your modal** in Webflow
2. **Add** `data-gdpr-modal` to the modal container
3. **Add** `data-gdpr-categories` to where category toggles should appear
4. **Set initial style** to `display: none`
### Step 5: Create Category Template
1. **Create a template element** for cookie categories
2. **Wrap it in** `<template data-gdpr-category-template>`
3. **Add data attributes:**
- `data-category-title` - Category title element
- `data-category-description` - Category description element
- `data-category-toggle` - Checkbox input element
### Step 6: Initialize
In **Custom Code** β **Footer Code** (or an embed element):
```html
<script>
document.addEventListener('DOMContentLoaded', function() {
GDPRCookies.init({
categories: ['analytics', 'marketing', 'functional'],
categoryConfig: {
analytics: {
title: "π Analytics Cookies",
description: "Help us understand how visitors interact with our website",
scripts: ["https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"]
},
marketing: {
title: "π― Marketing Cookies",
description: "Used to deliver personalized advertisements",
scripts: ["https://connect.facebook.net/en_US/fbevents.js"]
}
},
onAccept: function(preferences) {
// Initialize your tracking scripts here
if (preferences.analytics) {
// Initialize Google Analytics
gtag('config', 'GA_MEASUREMENT_ID');
}
if (preferences.marketing) {
// Initialize Facebook Pixel
fbq('init', 'PIXEL_ID');
}
}
});
});
</script>
```
### Webflow Pro Tips
1. **Use Webflow Interactions** for custom animations on banner show/hide
2. **Create Components** for reusable cookie banner across projects
3. **Use CMS** for managing cookie category content dynamically
4. **Style States** for hover, focus, and active button states
5. **Responsive Design** - test on all breakpoints in Webflow
## βοΈ Configuration
The `init()` method accepts a configuration object with the following options:
### Basic Configuration
```javascript
GDPRCookies.init({
// Required: Array of cookie categories to manage
categories: ['analytics', 'marketing', 'functional'],
// Cookie settings
cookiePrefix: 'gdpr_', // Prefix for consent cookies
cookieDuration: 365, // Days to store consent (default: 365)
// UI behavior
autoShow: true, // Auto-show banner for new users
showDelay: 1000, // Delay before showing banner (ms)
// Production settings
debug: false, // Enable debug logging (auto-detected in dev)
// Callbacks
onAccept: function(preferences) {}, // Called when user accepts
onDecline: function(preferences) {}, // Called when user declines
onSave: function(preferences) {}, // Called when user saves custom preferences
});
```
### Advanced Configuration
```javascript
GDPRCookies.init({
categories: ['analytics', 'marketing', 'functional'],
categoryConfig: {
analytics: {
title: "π Analytics Cookies",
description: "Help us understand website usage and performance",
scripts: [
"https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID",
{
src: "https://analytics.example.com/script.js",
async: true,
defer: false,
type: "text/javascript"
}
],
onAccept: function(category) {
console.log(`${category} cookies accepted`);
// Initialize analytics
gtag('config', 'GA_MEASUREMENT_ID');
},
onDecline: function(category) {
console.log(`${category} cookies declined`);
// Clean up analytics
}
},
marketing: {
title: "π― Marketing Cookies",
description: "Used for advertising and retargeting campaigns",
scripts: ["https://connect.facebook.net/en_US/fbevents.js"],
onAccept: function(category) {
// Initialize marketing tools
fbq('init', 'PIXEL_ID');
fbq('track', 'PageView');
},
onDecline: function(category) {
// Clean up marketing cookies
}
},
functional: {
title: "βοΈ Functional Cookies",
description: "Enable enhanced functionality and personalization",
onAccept: function(category) {
// Enable functional features
localStorage.setItem('user_preferences_enabled', 'true');
},
onDecline: function(category) {
// Disable functional features
localStorage.removeItem('user_preferences_enabled');
}
}
},
onAccept: function(preferences) {
console.log('User accepted cookies:', preferences);
// Global accept logic
},
onDecline: function(preferences) {
console.log('User declined cookies:', preferences);
// Global decline logic
},
onSave: function(preferences) {
console.log('User saved custom preferences:', preferences);
// Custom preferences logic
}
});
```
## π·οΈ Data Attributes
The library uses data attributes to connect with your HTML elements:
### Container Attributes
| Attribute | Element | Purpose |
|-----------|---------|---------|
| `data-gdpr-banner` | Container | Marks the cookie consent banner |
| `data-gdpr-modal` | Container | Marks the preferences modal/overlay |
| `data-gdpr-categories` | Container | Where category toggles are inserted |
| `data-gdpr-category-template` | `<template>` | Template for category UI generation |
| `data-gdpr-status` | Container | Displays current consent status (optional) |
### Action Attributes
| Attribute Value | Element | Action |
|----------------|---------|--------|
| `data-gdpr-action="show-banner"` | Button | Shows the consent banner |
| `data-gdpr-action="show-preferences"` | Button | Opens the preferences modal |
| `data-gdpr-action="close-modal"` | Button | Closes the preferences modal |
| `data-gdpr-action="accept-all"` | Button | Accepts all cookie categories |
| `data-gdpr-action="accept-essential"` | Button | Accepts only essential cookies |
| `data-gdpr-action="save-preferences"` | Button | Saves custom preferences |
| `data-gdpr-action="clear-all"` | Button | Clears all consent data |
### Category Template Attributes
| Attribute | Element | Purpose |
|-----------|---------|---------|
| `data-category-title` | Text element | Displays category title |
| `data-category-description` | Text element | Displays category description |
| `data-category-toggle` | Checkbox input | Controls category acceptance |
| `data-category` | Container | Applied automatically to identify category |
### Auto-Initialization
You can also configure the library via a data attribute:
```html
<script
src="https://cdn.jsdelivr.net/npm/gdpr-cookie-consent@1.0.0/main.min.js"
data-gdpr-config='{"categories":["analytics","marketing"],"autoShow":true}'
></script>
```
## π API Reference
### Initialization
#### `GDPRCookies.init(options)`
Initializes the cookie consent system.
**Parameters:**
- `options` (Object): Configuration object
**Example:**
```javascript
GDPRCookies.init({
categories: ['analytics', 'marketing'],
autoShow: true,
onAccept: (preferences) => console.log(preferences)
});
```
### Consent Management
#### `GDPRCookies.getConsent()`
Returns the complete consent object including type, timestamp, and preferences.
**Returns:** Object or null
```javascript
{
type: "all" | "essential" | "custom",
timestamp: "2024-01-15T10:30:00.000Z",
preferences: { essential: true, analytics: true, marketing: false }
}
```
#### `GDPRCookies.getPreferences()`
Returns just the preferences object.
**Returns:** Object
```javascript
{ essential: true, analytics: true, marketing: false, functional: true }
```
#### `GDPRCookies.hasConsent(category?)`
Checks if user has given consent for a specific category or any consent at all.
**Parameters:**
- `category` (String, optional): Category to check
**Returns:** Boolean
**Examples:**
```javascript
GDPRCookies.hasConsent(); // true if any consent exists
GDPRCookies.hasConsent('analytics'); // true if analytics is accepted
```
#### `GDPRCookies.updateCategory(category, enabled)`
Programmatically update a specific category consent.
**Parameters:**
- `category` (String): Category name
- `enabled` (Boolean): Whether to enable the category
**Example:**
```javascript
GDPRCookies.updateCategory('analytics', true);
```
### Script Management
#### `GDPRCookies.addScript(category, scriptConfig)`
Dynamically add a script to a category.
**Parameters:**
- `category` (String): Category name
- `scriptConfig` (String|Object): Script URL or configuration object
**Examples:**
```javascript
// Simple URL
GDPRCookies.addScript('analytics', 'https://example.com/script.js');
// Advanced configuration
GDPRCookies.addScript('marketing', {
src: 'https://example.com/pixel.js',
async: true,
defer: false,
type: 'text/javascript'
});
```
### Event Handling
#### `GDPRCookies.onCategoryChange(category, callback)`
Listen for changes to a specific category.
**Parameters:**
- `category` (String): Category name
- `callback` (Function): Callback function `(category, enabled) => {}`
**Example:**
```javascript
GDPRCookies.onCategoryChange('analytics', (category, enabled) => {
if (enabled) {
console.log('Analytics enabled');
// Initialize analytics
} else {
console.log('Analytics disabled');
// Clean up analytics
}
});
```
### UI Control
#### `GDPRCookies.showBanner()`
Programmatically show the consent banner.
#### `GDPRCookies.showPreferences()`
Programmatically open the preferences modal.
#### `GDPRCookies.clearAll()`
Clear all consent data and reset to initial state.
## π‘ Examples
### Basic WordPress Integration
```html
<!-- In your theme's header.php -->
<script src="https://cdn.jsdelivr.net/npm/gdpr-cookie-consent@1.0.0/main.min.js"></script>
<!-- Cookie banner -->
<div data-gdpr-banner class="cookie-banner" style="display: none;">
<div class="container">
<p>We use cookies to improve your experience. <a href="/privacy-policy">Learn more</a></p>
<div class="actions">
<button data-gdpr-action="accept-all" class="btn btn-primary">Accept All</button>
<button data-gdpr-action="show-preferences" class="btn btn-outline">Customize</button>
</div>
</div>
</div>
<!-- In your theme's footer.php -->
<script>
GDPRCookies.init({
categories: ['analytics', 'marketing'],
categoryConfig: {
analytics: {
title: "Analytics",
description: "Help us understand how you use our website",
scripts: ["<?php echo get_template_directory_uri(); ?>/js/analytics.js"]
}
}
});
</script>
```
### E-commerce Integration
```javascript
GDPRCookies.init({
categories: ['analytics', 'marketing', 'functional'],
categoryConfig: {
analytics: {
title: "Analytics Cookies",
description: "Help us understand shopping behavior and improve our store",
onAccept: function(category) {
// Initialize Google Analytics for e-commerce
gtag('config', 'GA_MEASUREMENT_ID', {
custom_map: {'custom_parameter_1': 'ecommerce'}
});
// Track enhanced e-commerce
gtag('config', 'GA_MEASUREMENT_ID', {
enhanced_ecommerce: true
});
}
},
marketing: {
title: "Marketing Cookies",
description: "Show you relevant ads and measure campaign effectiveness",
onAccept: function(category) {
// Initialize Facebook Pixel
fbq('init', 'PIXEL_ID');
fbq('track', 'PageView');
// Initialize Google Ads
gtag('config', 'AW-CONVERSION_ID');
}
},
functional: {
title: "Functional Cookies",
description: "Remember your preferences and shopping cart",
onAccept: function(category) {
// Enable cart persistence
localStorage.setItem('cart_persistence', 'enabled');
// Enable wish list functionality
localStorage.setItem('wishlist_enabled', 'true');
},
onDecline: function(category) {
// Disable enhanced features
localStorage.removeItem('cart_persistence');
localStorage.removeItem('wishlist_enabled');
}
}
},
onAccept: function(preferences) {
// Send consent data to your backend
fetch('/api/consent', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
preferences: preferences,
timestamp: new Date().toISOString(),
user_id: getCurrentUserId() // Your function
})
});
}
});
```
### React Integration
```jsx
import { useEffect, useState } from 'react';
function App() {
const [consentLoaded, setConsentLoaded] = useState(false);
useEffect(() => {
// Load the script dynamically
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/gdpr-cookie-consent@1.0.0/main.min.js';
script.onload = () => {
window.GDPRCookies.init({
categories: ['analytics', 'marketing'],
onAccept: (preferences) => {
setConsentLoaded(true);
// Initialize your tracking
},
onDecline: (preferences) => {
setConsentLoaded(true);
}
});
};
document.head.appendChild(script);
}, []);
const handleShowPreferences = () => {
window.GDPRCookies?.showPreferences();
};
return (
<div className="App">
{/* Your app content */}
<button onClick={handleShowPreferences}>
Cookie Preferences
</button>
{/* Cookie Banner */}
<div data-gdpr-banner style={{ display: 'none' }}>
<p>We value your privacy</p>
<button data-gdpr-action="accept-all">Accept All</button>
<button data-gdpr-action="show-preferences">Customize</button>
</div>
</div>
);
}
```
### Multi-language Support
```javascript
// Simple multi-language configuration
const translations = {
en: { title: "Analytics Cookies", description: "Help us understand website usage" },
de: { title: "Analyse-Cookies", description: "Helfen uns die Website-Nutzung zu verstehen" },
es: { title: "Cookies AnalΓticas", description: "Nos ayudan a entender el uso del sitio web" }
};
const lang = document.documentElement.lang || 'en';
const t = translations[lang] || translations.en;
GDPRCookies.init({
categories: ['analytics'],
categoryConfig: {
analytics: {
title: t.title,
description: t.description
}
}
});
```
## π¨ Customization
### CSS Styling
The library provides no default styles, giving you complete control:
```css
/* Cookie Banner */
[data-gdpr-banner] {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.9);
color: white;
padding: 20px;
transform: translateY(100%);
transition: transform 0.3s ease;
z-index: 9999;
}
[data-gdpr-banner].show {
transform: translateY(0);
}
/* Modal */
[data-gdpr-modal] {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
}
[data-gdpr-modal].show {
opacity: 1;
visibility: visible;
}
/* Category toggles */
[data-category-toggle] {
/* Style your checkboxes/switches */
}
```
### Custom Animations
```css
/* Slide in from bottom */
[data-gdpr-banner] {
transform: translateY(100%);
transition: transform 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}
[data-gdpr-banner].show {
transform: translateY(0);
}
/* Fade in modal */
[data-gdpr-modal] {
opacity: 0;
transition: opacity 0.3s ease;
}
[data-gdpr-modal].show {
opacity: 1;
}
[data-gdpr-modal] .cookie-modal {
transform: scale(0.9);
transition: transform 0.3s ease;
}
[data-gdpr-modal].show .cookie-modal {
transform: scale(1);
}
```
### Custom Category Template
You can create more complex category templates:
```html
<template data-gdpr-category-template>
<div class="cookie-category" data-category="">
<div class="category-header">
<div class="category-info">
<h3 data-category-title class="category-title"></h3>
<p data-category-description class="category-description"></p>
<div class="category-details">
<button type="button" class="details-toggle">Learn More</button>
<div class="details-content" style="display: none;">
<p>Additional information about this category...</p>
<ul>
<li>What data is collected</li>
<li>How it's used</li>
<li>Third-party services involved</li>
</ul>
</div>
</div>
</div>
<div class="category-control">
<label class="toggle-switch">
<input type="checkbox" data-category-toggle>
<span class="toggle-slider"></span>
</label>
</div>
</div>
</div>
</template>
```
## π Browser Support
- **Chrome**: 60+
- **Firefox**: 55+
- **Safari**: 11+
- **Edge**: 79+
- **Internet Explorer**: Not supported
### Polyfills Needed
For older browser support, include these polyfills:
```html
<!-- For IE11 support -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=Object.assign,Promise,fetch"></script>
```
## π Troubleshooting
### Common Issues
#### Banner Not Showing
1. Check console for JavaScript errors
2. Verify `data-gdpr-banner` attribute is present
3. Ensure `autoShow: true` in configuration
4. Check if consent already exists (clear cookies to test)
```javascript
// Debug consent status
console.log('Current consent:', GDPRCookies.getConsent());
console.log('Current preferences:', GDPRCookies.getPreferences());
```
#### Category Toggles Not Working
1. Verify `data-gdpr-category-template` is a `<template>` element
2. Check template structure has required data attributes
3. Ensure categories are properly configured
```javascript
// Debug category rendering
console.log('Categories config:', GDPRCookies.config?.categories);
console.log('Category elements:', document.querySelectorAll('[data-category]'));
```
#### Scripts Not Loading
1. Check browser console for network errors
2. Verify script URLs are accessible
3. Check if category consent is actually granted
```javascript
// Debug script loading
GDPRCookies.onCategoryChange('analytics', (category, enabled) => {
console.log(`${category} ${enabled ? 'enabled' : 'disabled'}`);
if (enabled) {
console.log('Scripts should load now');
}
});
```
#### Webflow Specific Issues
1. **Scripts not loading**: Check that custom code is in the correct location (head vs footer)
2. **Styles not applying**: Ensure CSS is added to the page or site settings
3. **Template not found**: Verify the template is published and data attributes are correct
### Debug Mode
Debug logging is automatically enabled in development environments (`localhost`, `127.0.0.1`):
```javascript
// Automatic debug detection (recommended)
GDPRCookies.init({
// ... your config
// Debug mode automatically enabled for localhost
});
// Manual override (not recommended for production)
GDPRCookies.init({
debug: true, // Force enable debug logging
// ... your config
});
```
### Console Commands
Test functionality in browser console:
```javascript
// Show banner manually
GDPRCookies.showBanner();
// Show preferences
GDPRCookies.showPreferences();
// Check consent status
GDPRCookies.hasConsent('analytics');
// Clear all data (for testing)
GDPRCookies.clearAll();
// Update category programmatically
GDPRCookies.updateCategory('marketing', true);
```
## π Security Best Practices
### Content Security Policy (CSP)
For maximum security, implement a strict CSP policy:
```http
Content-Security-Policy:
default-src 'self';
script-src 'self' https://cdn.jsdelivr.net https://www.googletagmanager.com https://connect.facebook.net;
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
connect-src 'self' https://www.google-analytics.com;
frame-src 'none';
object-src 'none';
base-uri 'self';
form-action 'self';
```
### Domain Whitelist
Only load scripts from trusted domains:
```javascript
GDPRCookies.init({
categories: ['analytics', 'marketing'],
categoryConfig: {
analytics: {
// β
Trusted domains only
scripts: [
'https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID',
'https://www.google-analytics.com/analytics.js'
]
},
marketing: {
// β
Verify all third-party scripts
scripts: [
'https://connect.facebook.net/en_US/fbevents.js'
]
}
}
});
```
### HTTPS Only
Always serve your site over HTTPS to ensure:
- Secure cookie transmission
- Protection against man-in-the-middle attacks
- Required for modern browser features
### Subresource Integrity (SRI)
When using CDN links, add SRI hashes for additional security:
```html
<script
src="https://cdn.jsdelivr.net/npm/gdpr-cookie-consent@1.0.0/main.min.js"
integrity="sha384-[your-sri-hash-here]"
crossorigin="anonymous">
</script>
```
## π Production Deployment
### Pre-Launch Checklist
- [ ] **Security Review**
- [ ] All script URLs are from trusted domains
- [ ] CSP policy is properly configured
- [ ] HTTPS is enforced site-wide
- [ ] SRI hashes are added to CDN scripts
- [ ] **Performance Testing**
- [ ] Library loads without blocking page render
- [ ] Banner shows within acceptable time limits
- [ ] No JavaScript errors in console
- [ ] **Functionality Testing**
- [ ] Cookie banner appears for new users
- [ ] All action buttons work correctly
- [ ] Preferences modal functions properly
- [ ] Consent persists across page loads
- [ ] Scripts load conditionally based on consent
- [ ] **Legal Compliance** β οΈ *Consult legal professionals - this checklist is not comprehensive*
- [ ] Cookie policy page is linked and updated
- [ ] Privacy policy mentions cookie usage
- [ ] Essential cookies are clearly defined
- [ ] Users can withdraw consent easily
- [ ] **Legal review completed by qualified counsel**
### Monitoring and Maintenance
```javascript
// Monitor consent rates and errors
GDPRCookies.init({
categories: ['analytics', 'marketing'],
onAccept: function(preferences) {
// Track consent acceptance rates
analytics.track('Cookie Consent Accepted', {
categories: Object.keys(preferences).filter(k => preferences[k]),
timestamp: new Date().toISOString()
});
},
onDecline: function(preferences) {
// Track consent decline rates
analytics.track('Cookie Consent Declined', {
timestamp: new Date().toISOString()
});
}
});
// Monitor for console errors in development
if (location.hostname === 'localhost') {
// Development environment - errors are logged to console automatically
console.log('GDPR Cookie Consent: Development mode active');
}
```
### Environment Configuration
```javascript
// Different configurations for different environments
const config = {
development: {
debug: true,
autoShow: true,
showDelay: 500,
categories: ['analytics'] // Limited for testing
},
staging: {
debug: false,
autoShow: true,
showDelay: 1000,
categories: ['analytics', 'marketing']
},
production: {
debug: false,
autoShow: true,
showDelay: 1000,
categories: ['analytics', 'marketing', 'functional']
}
};
const env = window.location.hostname.includes('localhost') ? 'development' :
window.location.hostname.includes('staging') ? 'staging' : 'production';
GDPRCookies.init(config[env]);
```
## π€ Contributing
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
### Development Setup
```bash
git clone https://github.com/CarterOgunsola/gdpr-cookie-consent.git
cd gdpr-cookie-consent
npm install
npm run dev
```
### Testing
```bash
npm test # Run unit tests
npm run test:e2e # Run end-to-end tests
npm run test:watch # Watch mode
```
### Building
```bash
npm run build # Build production version
npm run build:dev # Build development version
```
## π License
MIT License - see the [LICENSE](LICENSE) file for details.
## π Acknowledgments
- Inspired by the need for developer-friendly technical tools for cookie consent implementation
- Built with β€οΈ for the Webflow community
- Thanks to all contributors and users
---
## π Support
- **Documentation**: [https://gdpr-cookie-consent.dev](https://gdpr-cookie-consent.dev)
- **Issues**: [GitHub Issues](https://github.com/CarterOgunsola/gdpr-cookie-consent/issues)
- **Discussions**: [GitHub Discussions](https://github.com/CarterOgunsola/gdpr-cookie-consent/discussions)
- **Email**: support@gdpr-cookie-consent.dev
**Made with β€οΈ for developers who need technical tools for cookie consent implementation. Remember: technical tools β legal compliance - always consult legal professionals.**