Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Cookie Consent Bundle Laravel Package

brandbaboon/cookie-consent-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require brandbaboon/cookie-consent-bundle
    

    For Symfony Flex, this auto-enables the bundle. For older setups, add to config/bundles.php:

    BrandBaboon\CookieConsentBundle\CookieConsentBundle::class => ['all' => true],
    
  2. Routing: Add to config/routes.yaml (Symfony 4.4+):

    cookie_consent:
        resource: "@CookieConsentBundle/config/routing.yaml"
    

    For older versions, use config/routing.yml.

  3. First Use Case: Trigger the consent dialog by adding the Twig extension to your base template:

    {{ cookie_consent() }}
    

    This renders the default banner. Customize via config/packages/cookie_consent.yaml (see below).


Key Configuration

Edit config/packages/cookie_consent.yaml:

cookie_consent:
    banner:
        enabled: true
        position: "bottom-right" # top-left, top-right, bottom-left, bottom-right
        auto_hide: false
        close_button: true
    cookies:
        analytics: false # Default to "deny" for analytics cookies
        marketing: false
        statistics: false
        functional: true  # Functional cookies (e.g., CSRF) are often exempt
    storage:
        driver: "cookie" # or "session"
        name: "cookie_consent"
        lifetime: 31536000 # 1 year in seconds

First Integration

  1. Test the Banner: Visit your site. The banner should appear (if enabled: true). Click "Accept All" or toggle individual cookies. Verify cookies are set via browser dev tools (Application > Cookies).

  2. Check Consent Status: In Twig, display consent status:

    {% if cookie_consent('analytics') %}
        {# Load analytics script #}
        <script src="analytics.js"></script>
    {% endif %}
    

Implementation Patterns

Workflow: Handling Consent in Controllers

Use the CookieConsentService to check consent dynamically:

use BrandBaboon\CookieConsentBundle\Service\CookieConsentService;

class AnalyticsController extends AbstractController
{
    public function trackEvent(CookieConsentService $consent): Response
    {
        if (!$consent->isAllowed('analytics')) {
            return $this->json(['error' => 'Analytics disabled'], 403);
        }
        // Proceed with tracking
    }
}

Workflow: Customizing the Banner

Extend the default Twig template:

  1. Copy vendor/brandbaboon/cookie-consent-bundle/Resources/views/banner.html.twig to templates/cookie_consent/banner.html.twig.
  2. Modify the template to match your theme:
    <div class="custom-consent-banner">
        <p>{{ banner.text }}</p>
        <button class="accept-all">{{ banner.accept_all }}</button>
    </div>
    

Workflow: Dynamic Cookie Groups

Define custom cookie groups in config:

cookie_consent:
    cookies:
        custom_group:
            label: "Custom Features"
            description: "Enable for personalized content"
            default: false

Access in Twig:

{% if cookie_consent('custom_group') %}
    {# Load custom scripts #}
{% endif %}

Integration with Third-Party Services

  1. Google Analytics: Use a Twig include to conditionally load scripts:

    {% if cookie_consent('analytics') %}
        {% include 'google_analytics.html.twig' %}
    {% endif %}
    
  2. API Requests: Pass consent status via headers or query params:

    $response = $client->request('GET', '/api/data', [
        'headers' => [
            'X-Consent-Analytics' => $consent->isAllowed('analytics') ? '1' : '0',
        ],
    ]);
    

Asynchronous Consent

For SPAs or AJAX-heavy apps, use the CookieConsentService in JavaScript:

// Fetch consent status via API
fetch('/api/cookie-consent-status')
    .then(response => response.json())
    .then(data => {
        if (data.analytics) {
            loadAnalytics();
        }
    });

Create a controller endpoint:

#[Route('/api/cookie-consent-status', name: 'api_cookie_consent_status')]
public function getConsentStatus(CookieConsentService $consent): JsonResponse
{
    return $this->json([
        'analytics' => $consent->isAllowed('analytics'),
        'marketing' => $consent->isAllowed('marketing'),
    ]);
}

Gotchas and Tips

Pitfalls

  1. Cookie Lifetime:

    • Default lifetime: 31536000 (1 year) may conflict with GDPR’s "right to erasure." Shorten for stricter compliance:
      lifetime: 2592000 # 30 days
      
  2. Storage Driver:

    • session storage resets on session expiry. Use cookie for persistence across devices/browsers.
    • Gotcha: Session storage won’t work for mobile apps or if users clear cookies.
  3. Default Values:

    • Setting default: true for any cookie group automatically accepts it. Avoid for sensitive cookies like analytics.
  4. Caching:

    • If using Varnish or HTTP caching, ensure consent headers (e.g., X-Consent-Analytics) are respected. Add to varnish.vcl:
      if (req.http.X-Consent-Analytics == "0") {
          return (pass);
      }
      

Debugging

  1. Banner Not Showing:

    • Check enabled: true in config.
    • Verify Twig extension is loaded (add {{ dump(cookie_consent) }} to a template).
  2. Consent Not Persisting:

    • Ensure storage.driver is set to cookie or session.
    • Check browser dev tools (Application > Cookies) for cookie_consent cookie.
  3. CSRF Token Issues:

    • If using Symfony’s CSRF protection, ensure functional cookies are allowed by default:
      cookies:
          functional: true
      

Tips

  1. Localization: Customize banner text per locale in translations/messages.en.yaml:

    cookie_consent:
        banner:
            text: "We use cookies to improve your experience."
            accept_all: "Accept All"
            customize: "Customize"
    
  2. Conditional Loading: Lazy-load non-critical scripts after consent:

    document.addEventListener('DOMContentLoaded', function() {
        if (getCookieConsent('analytics')) {
            loadScript('analytics.js');
        }
    });
    
  3. Extension Points:

    • Events: Listen for consent changes via cookie_consent.save event:
      $eventDispatcher->addListener('cookie_consent.save', function (CookieConsentEvent $event) {
          // Log consent changes or sync to a database
      });
      
    • Custom Storage: Implement BrandBaboon\CookieConsentBundle\Storage\StorageInterface for database storage.
  4. Testing:

    • Use browser dev tools to delete the cookie_consent cookie and verify the banner reappears.
    • Test with auto_hide: true to ensure the banner disappears after user interaction.
  5. Performance:

    • Defer non-critical cookie scripts (e.g., ads) until consent is given:
      {% if cookie_consent('marketing') %}
          <script src="ads.js" defer></script>
      {% endif %}
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui