@darmiuskz/cookie-consent-manager

1.0.1 • Public • Published

🍪 cookie-consent-kit

A flexible, customizable, framework-friendly cookie consent manager.
Supports both React and Vanilla JS usage.
Works with modals, banners, and page-based preference management.


✨ Features

  • ✅ Drop-in <Banner /> and <Modal /> components for React
  • ✅ Plain showBanner() + modal for HTML/JS
  • ✅ Support for custom categories (analytics, marketing, etc.)
  • ✅ Backend syncing with token & API endpoint
  • ✅ Automatically enables analytics (e.g. GA4) if consented
  • ✅ One-time setup with full reusability across projects

🚀 Installation

NPM

npm install @darmiuskz/cookie-consent-manager

⚙️ setupCookieConsent(options)

Options

Option Type Description
serverMode boolean Enable syncing with backend. If true, fetches and stores consent via API.
apiUrl string URL of your consent API (used when serverMode: true).
userToken string Token to identify the current user (e.g. JWT or session ID).
categories object List of cookie categories the user can consent to (see below).

🍪 Category Object

analytics: {
  label: 'Analytics',                    // Display name for the category
  description: 'Track user behavior',    // Optional longer explanation
  customizable: true,                    // Whether user can toggle it
  scripts: [                             // Optional scripts to inject
    {
      src: 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX',
      name: 'Google Tag Manager'
    }
  ]
}

Banner Options

  • message — Text to show at the top of the banner
  • buttons.customize — Text for the customize button
  • buttons.showCustomize — Boolean to show/hide the customize button
  • customizeMode'modal' or 'page'; defines what happens when user clicks Customize. By default, it is 'modal'
  • customizePageUrl — URL to redirect to if customizeMode: 'page'

🔧 Setup (React or JS)

React (TypeScript)

import { setupCookieConsent, Banner, Modal } from '@darmiuskz/cookie-consent-kit/react';

setupCookieConsent({
  serverMode: true,
  apiUrl: 'https://your-api.com/consent',
  userToken: 'abc123',
  categories: {
    label: 'Analytics',
      description: 'Helps us understand user behavior.',
      customizable: true,
      scripts: [
        {
          src: 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX',
          name: 'Google Tag Manager'
        }
      ],
    },
    marketing: {
      label: 'Marketing',
      description: 'Tracks ads and conversions.',
      customizable: true,
      scripts: [
        {
          inline: `
            !function(f,b,e,v,n,t,s)
            {if(f.fbq)return;n=f.fbq=function(){n.callMethod ?
            n.callMethod.apply(n,arguments):n.queue.push(arguments)};
            if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
            n.queue=[];t=b.createElement(e);t.async=!0;
            t.src=v;s=b.getElementsByTagName(e)[0];
            s.parentNode.insertBefore(t,s)}(window, document,'script',
            'https://connect.facebook.net/en_US/fbevents.js');
            fbq('init', 'YOUR_PIXEL_ID'); 
            fbq('track', 'PageView');
          `,
          name: 'Facebook Pixel'
        }
      ]
    }
  }
});

Then in your layout

<Banner
  message="We use cookies 🍪 to improve your experience."
  buttons={{ customize: "Customize" }}
  customizeMode="modal"
/>

<Modal>
  <YourPreferenceComponent /> {/* use useConsentCategories() hook here */}
</Modal>

Vanilla JS / HTML

<script>
  import { setupCookieConsent, showBanner } from '@darmiuskz/cookie-consent-manager';
  window.CookieConsent.setupCookieConsent({
    serverMode: false,
    categories: {
      analytics: {
        label: 'Analytics',
        description: 'Tracks how users interact with the site',
        customizable: true,
        scripts: [
          {
            src: 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX',
            name: 'Google Tag Manager'
          },
        ]
      }
    }
  });

  window.CookieConsent.showBanner({
    message: "We use cookies 🍪",
    buttons: {
      customize: "Customize"
    },
    customizeMode: "page",
    customizePageUrl: "/cookie-settings"
  });
</script>

🛠️ Custom Modals in Native JS

<script>
import { injectCustomModal, getConsentHelpers, getConsentCategories } from 'cookie-consent-manager';
  const categories = getConsentCategories();

  const html = `
    <div class="my-cookie-modal">
      <h2>Cookie Preferences</h2>
      ${categories.map(cat => `
        <label>
          <input type="checkbox" name="${cat.key}" ${cat.checked ? 'checked' : ''} />
          ${cat.label}
        </label>
      `).join('')}
      <button onclick="saveMyConsent()">Save</button>
      <button onclick="window.CookieConsent.getConsentHelpers().rejectAll()">Reject All</button>
    </div>
  `;

  function saveMyConsent() {
    const selected = Array.from(document.querySelectorAll('input[type=checkbox]:checked')).map(i => i.name);
    getConsentHelpers().save(selected);
    document.querySelector('.my-cookie-modal')?.remove();
  }

  injectCustomModal(html);
</script>

Package Sidebar

Install

npm i @darmiuskz/cookie-consent-manager

Weekly Downloads

3

Version

1.0.1

License

MIT

Unpacked Size

23.6 kB

Total Files

17

Last publish

Collaborators

  • darmiuskz