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

react-consent-shield

v0.9.2

Published

A comprehensive React library for GDPR, CCPA, and LGPD cookie consent management with real script blocking, geo-detection, and Google Consent Mode v2 support

Readme

react-consent-shield

A React library for cookie consent management that blocks tracking scripts until users give consent. Unlike banners that only show a popup, this library intercepts script loading at the DOM level, preventing analytics, marketing, and tracking scripts from executing before the user makes a choice.

Includes automatic geo-detection for 52 privacy laws worldwide (GDPR, CCPA, LGPD, POPIA, PDPA, and regional variations), 274 pre-configured service presets, and Google Consent Mode v2 integration.

npm version License: PolyForm Noncommercial Test Coverage Tests

React 18 React 19 Next.js 14 Next.js 15 TypeScript Node.js

Current release: v0.9.2

Live demo: react-consent-shield.onrender.com

npm: npmjs.com/package/react-consent-shield

GitHub: github.com/686f6c61/react-consent-shield


Features

The library provides everything needed to implement cookie consent in a React application. Each feature is designed to work independently or together with others, so you can start simple and add complexity as needed.

  • Real script blocking - Actually blocks tracking scripts until consent is given
  • Geographic detection - Automatically applies the correct privacy law based on user location (headers by default)
  • 274 service presets - Google Analytics, Meta Pixel, Hotjar, TikTok, regional services (Yandex, Baidu, Naver...), and many more
  • Google Consent Mode v2 - Full integration with automatic consent signal updates
  • Cookie scanner - Detects undeclared cookies for compliance auditing
  • Audit logging - Hash-verified, tamper-evident consent records
  • Compliance reports - Generate JSON/HTML reports for privacy audits
  • Consent versioning - Auto-detect service changes and prompt re-consent
  • Subdomain sharing - Share consent across subdomains automatically
  • 10 languages - English, Spanish, German, French, Portuguese, Italian, Dutch, Polish, Japanese, Chinese
  • WCAG 2.2 AA accessible - Full keyboard navigation, screen reader support, focus trap, high contrast mode
  • 8 banner variants - Default, fullwidth, modal, floating, card, minimal, corner, sidebar
  • 3 popup theme presets - corporate, minimal, high-contrast with ready-to-use styles
  • Age verification - COPPA/GDPR-K compliance with checkbox, year, birthdate, or age-gate verification
  • TypeScript - Full type definitions included
  • Works everywhere - Next.js, Vite, Create React App, plain HTML

Use Cases

These examples show common scenarios where the library helps manage consent. Each example includes working code that you can copy and adapt to your project.

E-commerce site with analytics

An online store typically needs conversion tracking for marketing campaigns, heat maps to understand user behavior, and compliance with multiple privacy laws depending on where customers are located. This configuration handles all three requirements by enabling geo-detection, which automatically determines whether to show opt-in (GDPR) or opt-out (CCPA) consent flows.

<ConsentProvider
  config={{
    services: [googleAnalytics, metaPixel, hotjar],
    geoDetection: 'headers',
    geoFallback: 'strictest',
  }}
>

SaaS application with multiple tracking services

A SaaS product often uses multiple analytics tools for different purposes: product analytics (Mixpanel, Amplitude), customer data platforms (Segment), and session recording for debugging (Clarity, FullStory). Users can choose category/service preferences with the built-in preferences flow, giving them more control while still allowing you to collect the data you need from users who opt in.

<ConsentProvider
  config={{
    services: [
      mixpanel,
      amplitude,
      segment,
      microsoftClarity,
      fullstory,
    ],
    showPreferencesButton: true,
  }}
>

Multi-region compliance

When your application serves users from multiple countries, you need to handle different consent requirements. The library detects the user's location and applies the appropriate law automatically. The geoFallback option ensures that if geo-detection fails, the strictest rules apply by default, keeping you compliant even in edge cases.

<ConsentProvider
  config={{
    services: [googleAnalytics],
    geoDetection: 'api',
    geoFallback: 'strictest', // Default to strictest
  }}
>

Age-gated content and child protection

If your site is aimed at or accessible to minors, regulations like COPPA (USA, under 13) and GDPR-K (EU, under 16) require parental consent or age verification before collecting any personal data. The library supports four verification methods: checkbox declaration, year of birth, full birthdate input, or an explicit age-gate choice. When a user doesn't meet the minimum age, tracking scripts remain blocked regardless of other consent choices.

<ConsentProvider
  config={{
    services: [googleAnalytics, metaPixel],
    ageVerification: {
      enabled: true,
      method: 'age-gate', // 'checkbox' | 'year' | 'birthdate' | 'age-gate'
      minimumAge: 16, // GDPR-K requirement
      parentalConsentRequired: true,
    },
  }}
>

Blog or content site with minimal tracking

Not every site needs complex analytics. For a personal blog or documentation site, you might only want basic page views without user profiling. Privacy-focused analytics like Plausible or Fathom don't use cookies and may not require consent in some jurisdictions, but showing a banner still demonstrates transparency and builds trust with readers.

<ConsentProvider
  config={{
    services: [plausible],
    position: 'bottom-right',
  }}
>
  <ConsentBanner variant="minimal" />

Quick Start

Getting started takes less than a minute. Install the package, wrap your app with the provider, and add the banner component. The library handles persistence, UI, and script blocking automatically.

npm install react-consent-shield
import {
  ConsentProvider,
  ConsentBanner,
  ConsentModal,
  googleAnalytics,
  metaPixel,
} from 'react-consent-shield';

function App() {
  return (
    <ConsentProvider
      config={{
        services: [googleAnalytics, metaPixel],
      }}
    >
      <YourApp />
      <ConsentBanner />
      <ConsentModal />
    </ConsentProvider>
  );
}

That's it! Users will see a consent banner, and their preferences are saved automatically.


Popup Theme Presets

If you want a polished banner quickly, use the built-in presets:

import {
  ConsentProvider,
  ConsentBanner,
  ConsentModal,
  getPopupThemePreset,
  googleAnalytics,
} from 'react-consent-shield';

const uiPreset = getPopupThemePreset('corporate');

function App() {
  return (
    <ConsentProvider
      config={{
        services: [googleAnalytics],
        ...uiPreset.provider,
      }}
    >
      <ConsentBanner {...uiPreset.banner} />
      <ConsentModal {...uiPreset.modal} />
    </ConsentProvider>
  );
}

Available presets:

  • corporate: professional card style for product/SaaS sites
  • minimal: low-noise bottom bar for content-first websites
  • high-contrast: accessibility-first visual style (WCAG-oriented)

Screenshots

Configuration Panel

The demo includes a full control panel for testing all features:

Configuration Panel

Banner Styles

The library includes 8 banner variants that can be customized with themes and positions:

| Bottom Bar | Corner Popup | Sidebar Panel | |------------|--------------|---------------| | Bottom Bar Light | Corner Popup | Sidebar Panel | | Bottom Bar Dark | Corner Dark | Sidebar Dark |

Compliance Report

Generate detailed compliance reports for privacy audits:

| Blocked Services | Audit Log | Law Configuration | |------------------|-----------|-------------------| | Blocked Services | Audit Log | Law Config |


Documentation

The documentation covers everything from basic setup to advanced customization. Each topic includes code examples and explanations of the underlying concepts. For interactive examples, check out the live demo linked below.

For detailed documentation, see the docs folder:

| Topic | Description | View online | |-------|-------------|-------------| | Getting Started | Installation and basic setup | - | | Configuration | All provider, banner, and modal options | View online | | Components | ConsentProvider, ConsentBanner, ConsentModal, ConsentScript | View online | | Hooks | useConsent, useConsentCategory, useConsentService, useGeoDetection | View online | | Service Presets | 274 pre-configured services and how to create custom ones | View online | | Script Blocking | Block scripts until consent is given | View online | | Granular Consent | Category-level and service-level consent | View online | | Google Consent Mode | Integration with Google Consent Mode v2 | View online | | Geographic Detection | Automatic law detection and 52 supported laws | View online | | Cookie Scanner | Detect undeclared cookies for compliance | View online | | Audit Logging | Hash-verified, tamper-evident consent records | View online | | Compliance Report | Generate technical reports for privacy audits | View online | | Consent Versioning | Auto-detect service changes and re-consent | View online | | Subdomain Sharing | Share consent across subdomains | View online | | Internationalization | 10 languages and custom translations | View online | | Accessibility | WCAG 2.2 AA compliance and keyboard navigation | View online | | Troubleshooting | Common issues and FAQ | - | | Styling | CSS variables and customization examples | View online | | Framework Integration | Next.js, Vite, plain HTML examples | - |


Interactive Demo

The live demo lets you experiment with all features without writing any code. You can change banner positions, switch themes, simulate different geographic locations, and see how consent signals are sent to Google. All changes happen in real-time so you can quickly find the configuration that works for your project.

Try the live demo:

| Section | What you can try | |---------|------------------| | Banner Configuration | Position, theme, variants, blocking mode | | Geographic Detection | Auto-detect location and applicable law | | Consent Status | View current consent state per category | | Granular Consent | Toggle individual services with cookie simulation | | Cookie Scanner | Detect undeclared cookies | | Google Consent Mode | See consent signals sent to Google | | Script Blocking | Conditional script loading demo | | Audit Logs | Consent history with hash verification | | Compliance Report | Generate technical implementation reports | | i18n | Switch between 10 languages |


Testing

Every feature is covered by automated tests, including unit tests for individual functions and integration tests for component interactions. The test suite validates all 274 service presets and all 10 language translations to ensure nothing breaks between releases.

This library is thoroughly tested with 100% code coverage.

| Metric | Coverage | |--------|----------| | Statements | 100% | | Branches | 100% | | Functions | 100% | | Lines | 100% |

435+ tests covering:

  • Unit tests (Vitest + React Testing Library)
  • All 274 service presets validated
  • All 10 languages tested
npm run test           # Run unit tests
npm run test:watch     # Run tests in watch mode
npm run test:coverage  # Run with coverage report

Coverage output is generated in coverage/ (open coverage/index.html for the HTML report).


TypeScript

The entire codebase is written in TypeScript with strict type checking enabled. All public APIs export their types, so you get autocomplete and compile-time validation when using the library. This helps catch configuration errors before runtime and makes it easier to explore the available options.

import type {
  ConsentState,
  ConsentConfig,
  ServicePreset,
  ConsentCategory,
} from 'react-consent-shield';

Browser Support

The library works in all modern browsers that support ES2020 features. Older browsers like IE11 are not supported. If you need to support older browsers, you may need to add polyfills for features like Promise.allSettled and optional chaining.

  • Chrome 80+
  • Firefox 75+
  • Safari 13+
  • Edge 80+

License

This library uses a dual licensing model. Non-commercial use is free under the PolyForm Noncommercial License, which covers personal projects, education, non-profits, and open source development. Commercial use requires a separate license.

This software is licensed under the PolyForm Noncommercial License 1.0.0.

Free for:

  • Personal projects
  • Learning and education
  • Non-profit organizations
  • Open source projects

Commercial use requires a license. This includes websites with ads, SaaS products, e-commerce sites, and any for-profit use.

Contact: GitHub

See LICENSE for complete terms.


Contributing

Bug reports, feature requests, and pull requests are welcome. Before submitting a large change, please open an issue first to discuss the approach. All contributions must pass the existing test suite and maintain 100% coverage.

Contributions are welcome! Please see the CONTRIBUTING guide.