React Cookie Manager

repository·main·Indexed 42 days ago

https://github.com/cookiekit-io/react-cookie-manager

A privacy-first cookie consent library for React applications (v5.4.1) featuring automated tracking prevention, smart iframe blocking for embedded content, and built-in support for Google Consent Mode v2. It includes twelve visual themes, a useCookieConsent hook, and a floating cookie button for managing user preferences.

Tokens
18.5K
Snippets
67
Records
73
Agent score
51%

What's inside React Cookie Manager

  1. Customize styles with classNames

    main

    You can override the default styling of any element in the cookie consent UI using the classNames prop. This prop accepts an object where keys correspond to specific UI elements. It is compatible with any CSS framework, including Tailwind CSS and Bootstrap.

    Element Groups:

    • Button Elements: acceptButton, declineButton, manageButton, manageCancelButton, manageSaveButton.
    • Container Elements: bannerContainer, popupContainer, modalContainer, manageCookieContainer.
    • Content Elements: bannerContent, popupContent, modalContent, bannerTitle, popupTitle, modalTitle, bannerMessage, popupMessage, modalMessage.
    • Manage Cookie UI Elements: manageCookieTitle, manageCookieMessage, manageCookieCategory, manageCookieCategoryTitle, manageCookieCategorySubtitle, manageCookieStatusText, manageCookieToggle, manageCookieToggleChecked.
    • Other Elements: privacyPolicyLink, floatingButton, floatingButtonCloseButton.
    <CookieManager
      classNames={{
        acceptButton: "bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded-lg",
        declineButton: "bg-red-500 hover:bg-red-600 text-white font-bold py-2 px-4 rounded-lg",
        manageButton: "border-2 border-blue-500 text-blue-500 font-bold py-2 px-4 rounded-lg hover:bg-blue-50",
        // ... other class names
      }}
    >
      {children}
    </CookieManager>
  2. How automatic tracking and content blocking works

    main

    React Cookie Manager provides two main automated privacy features:

    1. Automatic Tracking Prevention: It automatically disables tracking for services like Google Analytics and Facebook Pixel by blocking their tracking scripts from loading until consent is granted.
    2. Embedded Content Blocking: It automatically blocks iframes that load cookies without consent (e.g., YouTube, Vimeo, Google Maps, social media embeds). When blocked, these are replaced with user-friendly placeholders that explain why the content is blocked and provide a button to manage cookie settings.
  3. Integrate with Next.js (App Router)

    main

    In Next.js App Router, render CookieManager inside a client-side Providers component at the root of your application. This allows you to use the library throughout your app while maintaining the App Router structure.

    // app/components/Providers.tsx
    "use client";
    
    import { CookieManager } from "react-cookie-manager";
    
    export function Providers({ children }: { children: React.ReactNode }) {
      return (
        <CookieManager
          showManageButton
          enableFloatingButton
          displayType="popup"
          theme="light"
        >
          {children}
        </CookieManager>
      );
    }
    
    // app/layout.tsx
    import { Providers } from "@/components/Providers";
    
    export default function RootLayout({ children }: { children: React.ReactNode }) {
      return (
        <html lang="en">
          <body>
            <Providers>{children}</Providers>
          </body>
        </html>
      );
    }
  4. Configure eslint-plugin-react

    main

    To improve React-specific linting, install eslint-plugin-react and update your eslint.config.js. You must specify the React version in settings and include the recommended rules and jsx-runtime rules in the rules object.

    // eslint.config.js
    import react from 'eslint-plugin-react'
    
    export default tseslint.config({
      // Set the react version
      settings: { react: { version: '18.3' } },
      plugins: {
        // Add the react plugin
        react,
      },
      rules: {
        // other rules...
        // Enable its recommended rules
        ...react.configs.recommended.rules,
        ...react.configs['jsx-runtime'].rules,
      },
    })
  5. Quick Start with CookieManager

    main

    To use the library, wrap your entire application with the CookieManager component. This ensures consent is managed across all components and pages. Styles are automatically injected, so no manual CSS imports are required.

    import { CookieManager } from "react-cookie-manager";
    
    createRoot(document.getElementById("root")).render(
      <StrictMode>
        <CookieManager>
          <App />
        </CookieManager>
      </StrictMode>
    );
  6. Enable type-aware lint rules in ESLint

    main

    For production applications, it is recommended to enable type-aware linting by configuring parserOptions and upgrading your recommended configurations. This allows ESLint to use TypeScript type information for more accurate linting.

    1. Configure parserOptions in your ESLint configuration to point to your tsconfig files.
    2. Replace tseslint.configs.recommended with tseslint.configs.recommendedTypeChecked or tseslint.configs.strictTypeChecked.
    3. (Optional) Add ...tseslint.configs.stylisticTypeChecked.
    export default tseslint.config({
      languageOptions: {
        // other options...
        parserOptions: {
          project: ['./tsconfig.node.json', './tsconfig.app.json'],
          tsconfigRootDir: import.meta.dirname,
        },
      },
    })
  7. Ensure strict ordering for Google Consent Mode

    main

    To ensure the default consent command runs before the Google tag loads (which is preferred), call the setGoogleConsentDefault helper in your HTML <head> before your gtag.js snippet. You should still keep the googleConsentMode prop on the CookieManager component to handle subsequent updates.

    <script>
      // before the gtag.js snippet
    </script>
    <script type="module">
      import { setGoogleConsentDefault } from "react-cookie-manager";
      setGoogleConsentDefault();
    </script>
  8. Configure translations and i18next support

    main

    You can customize the text used in the consent banner and management modal by passing a translations object to CookieManager.

    For i18next integration, pass the translation function to the translations prop and specify the translationI18NextPrefix to match your JSON structure. Ensure your translation files include all required keys (e.g., title, message, buttonText, etc.) under that prefix.

    import { useTranslation } from "react-i18next";
    
    function App() {
      const { t } = useTranslation();
    
      return (
        <CookieManager translations={t} translationI18NextPrefix="cookies.">
          <YourApp />
        </CookieManager>
      );
    }
  9. Enable the Floating Cookie Button

    main

    The floating cookie button is a persistent, accessible icon (appearing in the bottom-left) that allows users to reopen their cookie preferences after their initial choice.

    Behavior:

    1. Appears automatically after the user provides initial consent.
    2. Hovering reveals a close button to dismiss it.
    3. Clicking the button opens the cookie preferences modal.
    4. If dismissed via the close button, it remains hidden until the page is refreshed.
    5. It maintains its position during scrolling.

    Accessibility: It includes proper ARIA labels, keyboard navigation, focus management, and high contrast ratios.

    <CookieManager
      enableFloatingButton={true}
      theme="midnight"
      // ... other props
    >
      <YourApp />
    </CookieManager>
  10. Enable Google Consent Mode v2

    main

    You can enable Google Consent Mode v2 by passing the googleConsentMode prop to CookieManager. When enabled, the library:

    1. Emits a denied default state on mount.
    2. Automatically pushes gtag('consent', 'update', ...) whenever the user's consent changes.
    3. Maps categories to Google signals:
      • Analytics $\rightarrow$ analytics_storage
      • Advertising $\rightarrow$ ad_storage, ad_user_data, and ad_personalization
      • Social $\rightarrow$ personalization_storage

    You can pass a boolean true for default behavior or a GoogleConsentModeOptions object to customize settings like wait_for_update, url_passthrough, or ads_data_redaction.

    <CookieManager googleConsentMode={{ wait_for_update: true }}>
      <App />
    </CookieManager>
  11. Understand Cookie Categories and Consent Status

    main

    The library manages consent through two primary data structures:

    1. CookieCategories: A map of category IDs to boolean values representing whether consent has been granted for that category (e.g., { Analytics: true, Social: false }).
    2. DetailedCookieConsent: A more granular view that includes a ConsentStatus for every category. Each ConsentStatus contains:
      • consented: A boolean indicating if consent was given.
      • timestamp: A string representing when the decision was made.

    This structure allows you to track not just what was consented to, but when the user made the choice.