npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

gdpr-cookie-solution

v1.0.0

Published

Self-hosted GDPR-compliant cookie consent solution

Readme

GDPR-Compliant Cookie Solution

A comprehensive self-hosted solution for managing cookies and ensuring GDPR compliance in your web applications.

Features

  • 🍪 Complete Cookie Management: Control cookies across your entire site
  • 🛡️ GDPR, CCPA, and ePrivacy Compliant: Meets all major privacy regulations
  • 🔍 Cookie Scanner: Automatically detects and categorizes cookies
  • 🚫 Script Blocker: Prevents tracking scripts from loading until consent is given
  • 🌐 Multi-language Support: Easily translate to any language
  • 🎨 Fully Customizable UI: Match your brand and design system
  • 📊 Consent Logging: Record consent for compliance requirements
  • 📱 Responsive Design: Works on all devices
  • Lightweight: Under 20KB gzipped
  • 🔄 Framework Agnostic: Works with React, Next.js, Vue, and more

Installation

npm install gdpr-cookie-solution
# or
yarn add gdpr-cookie-solution
# or
pnpm add gdpr-cookie-solution

Quick Start

import React from "react";
import { CookieConsent, DEFAULT_CONFIG } from "gdpr-cookie-solution";

function App() {
  return (
    <div className="App">
      {/* Your app content */}

      <CookieConsent config={DEFAULT_CONFIG} />
    </div>
  );
}

export default App;

Configuration

The solution is highly configurable. Here's an example configuration:

const config = {
  storageMethod: "cookie", // 'cookie' or 'localStorage'
  cookieName: "gdpr_consent",
  cookieExpiry: 365, // Days
  privacyPolicyUrl: "/privacy-policy",
  companyName: "Your Company Name",
  contactEmail: "[email protected]",
  blockedContentMessage: "Please accept cookies to view this content",
  autoBlockCookies: true,
  regionBased: true, // Only show banner for users in regions requiring consent
  requireConsentInEU: true,
  euCountryCodes: [
    "AT",
    "BE",
    "BG",
    "HR",
    "CY",
    "CZ",
    "DK",
    "EE",
    "FI",
    "FR",
    "DE" /* ... */,
  ],
  consentExpiryDays: 365,
  defaultConsent: {
    necessary: true, // Always true
    functional: false,
    analytics: false,
    advertising: false,
    uncategorized: false,
  },
  logConsent: true, // Keep records of consent
  bannerConfig: {
    position: "bottom", // 'top', 'bottom', 'top-left', 'top-right', 'bottom-left', 'bottom-right'
    layout: "bar", // 'bar', 'box', 'floating'
    rejectButtonEnabled: true,
    settingsButtonEnabled: true,
    acceptAllButtonLabel: "Accept All",
    rejectAllButtonLabel: "Reject All",
    settingsButtonLabel: "Preferences",
    bannerHeading: "We Value Your Privacy",
    bannerDescription:
      "This website uses cookies to ensure you get the best experience on our website.",
    showPoweredBy: true,
  },
  customStyles: {
    bannerBackgroundColor: "#ffffff",
    bannerTextColor: "#333333",
    primaryButtonColor: "#0070f3",
    primaryButtonTextColor: "#ffffff",
    secondaryButtonColor: "transparent",
    secondaryButtonTextColor: "#0070f3",
    switchActiveColor: "#0070f3",
    linkColor: "#0070f3",
    borderRadius: "8px",
    fontFamily: "inherit",
    darkMode: false,
  },
  language: "en", // Default language
  translations: {
    en: {
      // English translations
      consentTitle: "Cookie Consent",
      // ... more translations
    },
    fr: {
      // French translations
      consentTitle: "Consentement des cookies",
      // ... more translations
    },
    // Add more languages as needed
  },
};

Components

CookieConsent

The main banner component that appears when a user visits your site.

import { CookieConsent } from "gdpr-cookie-solution";

<CookieConsent
  config={config}
  onConsent={(accepted) => console.log("Consent given:", accepted)}
/>;

ConsentModal

A detailed modal that allows users to customize their cookie preferences.

import { ConsentModal } from "gdpr-cookie-solution";

function MyComponent() {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <>
      <button onClick={() => setIsOpen(true)}>Cookie Settings</button>

      <ConsentModal
        config={config}
        open={isOpen}
        onClose={() => setIsOpen(false)}
        onSave={(consent) => console.log("Saved preferences:", consent)}
      />
    </>
  );
}

BlockedContent

A component that only shows its children if the user has consented to the specified category.

import { BlockedContent } from "gdpr-cookie-solution";

<BlockedContent
  category="analytics"
  config={config}
  fallback={<p>Please accept analytics cookies to view this content</p>}
  onAccept={() => console.log("Analytics accepted")}
>
  {/* Analytics script or component that should only load with consent */}
  <script src="https://www.google-analytics.com/analytics.js" />
</BlockedContent>;

Hooks

useConsent

A hook for accessing and managing consent state.

import { useConsent } from "gdpr-cookie-solution";

function CookieManager() {
  const {
    consent, // Current consent state
    bannerVisible, // Is the banner visible
    modalVisible, // Is the modal visible
    loading, // Is consent loading
    acceptAll, // Function to accept all cookies
    rejectAll, // Function to reject all optional cookies
    setSpecificConsent, // Function to set specific consent options
    showPreferences, // Function to show the preferences modal
    closePreferences, // Function to close the preferences modal
    resetConsent, // Function to reset consent (for testing)
  } = useConsent(config);

  // Use these values and functions to build custom UIs
}

useCookieScanner

A hook for scanning and categorizing cookies.

import { useCookieScanner } from "gdpr-cookie-solution";

function CookieScanner() {
  const {
    cookies, // All detected cookies
    loading, // Is scanner loading
    getCookiesByCategory, // Function to filter cookies by category
    addCustomCookie, // Function to add a custom cookie definition
    rescan, // Function to trigger a new scan
  } = useCookieScanner();

  // Display or manage detected cookies
}

Advanced Usage

Manual Services Configuration

For more advanced usage, you can directly use the services:

import {
  CookieScanner,
  CookieBlocker,
  ConsentStorage,
} from "gdpr-cookie-solution";

// Create service instances
const scanner = new CookieScanner();
const blocker = new CookieBlocker();
const storage = new ConsentStorage(config);

// Add custom cookie definitions
scanner.addKnownCookie("_myCustomCookie", "functional", "My Service");

// Add custom blocking rules
blocker.addCategoryRule("uservoice", "functional");

// Initialize the blocker
blocker.init();

// Get existing consent
const savedConsent = storage.getConsent();

// Check if consent is expired
if (savedConsent && !storage.isConsentExpired(savedConsent)) {
  // Apply consent to blocker
  blocker.applyConsent(savedConsent);
}

Server-Side Logic (Next.js Example)

// middleware.ts
import { NextRequest, NextResponse } from "next/server";

export function middleware(req: NextRequest) {
  const response = NextResponse.next();

  // Get consent from cookies
  const consentCookie = req.cookies.get("gdpr_consent");
  let consent = null;

  if (consentCookie) {
    try {
      consent = JSON.parse(consentCookie.value);
    } catch (e) {
      // Invalid consent, do nothing
    }
  }

  // Modify response based on consent
  if (!consent || !consent.analytics) {
    // No analytics consent, disable caching for personalized content
    response.headers.set(
      "Cache-Control",
      "no-store, max-age=0, must-revalidate"
    );
  }

  return response;
}

Browser Support

This solution works on all modern browsers:

  • Chrome/Edge (latest)
  • Firefox (latest)
  • Safari (latest)
  • Opera (latest)
  • Internet Explorer 11 (with polyfills)

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

If you need help with this library, please open an issue on GitHub.


Built with privacy in mind. Happy coding!