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 🙏

© 2025 – Pkg Stats / Ryan Hefner

docusaurus-plugin-cookie-consent

v4.0.1

Published

A cookie consent modal/toast component for Docusaurus sites with configurable text, links, and preference management.

Downloads

706

Readme

Docusaurus Plugin Cookie Consent

npm version CI

A cookie consent modal/toast component for Docusaurus sites with configurable text, links, and preference management. Automatically inserts a GDPR-compliant cookie consent banner into your Docusaurus site.

Features

  • Configurable text (markdown compatible)
  • Configurable links to privacy policy, cookie policy, etc.
  • Multiple consent options: Accept All, Reject Optional, Reject All
  • Helper context/hooks to ensure compliance with user preferences
  • Local storage tracking of user preferences
  • Modal or toast mode (centered modal or bottom toast)
  • Cookie categories (Necessary, Analytics, Marketing, Functional)
  • TypeScript support with full type definitions

Compatibility

  • Docusaurus ^3.0.0
  • React ^18.2.0

Installation

npm install docusaurus-plugin-cookie-consent

Quick Start

Add the plugin to your docusaurus.config.ts (or .js) configuration:

// docusaurus.config.ts
import type { Config } from '@docusaurus/types'

const config: Config = {
  // ... existing config ...
  plugins: [
    [
      'docusaurus-plugin-cookie-consent',
      {
        title: 'Cookie Consent',
        description: 'We use cookies to enhance your browsing experience and analyze our traffic.',
        links: [
          { label: 'Privacy Policy', href: '/privacy' },
          { label: 'Cookie Policy', href: '/cookies' },
        ],
      },
    ],
  ],
}

export default config

That's it! The cookie consent banner will automatically appear on your site.

Configuration Options

Basic Configuration

{
  // Enable or disable the plugin (default: true)
  enabled?: boolean

  // Main title/heading text (default: 'Cookie Consent')
  title?: string

  // Main description text - supports markdown links [text](url) (default: 'We use cookies...')
  description?: string

  // Links to privacy policy, cookie policy, etc.
  links?: Array<{
    label: string
    href: string
  }>

  // Button text customization
  acceptAllText?: string        // default: 'Accept All'
  rejectOptionalText?: string  // default: 'Reject Optional'
  rejectAllText?: string       // default: 'Reject All'

  // Local storage key for preferences (default: 'cookie-consent-preferences')
  storageKey?: string

  // Show as toast (bottom of screen) instead of centered modal (default: false)
  toastMode?: boolean
}

Advanced Configuration with Categories

{
  // ... basic options ...

  categories?: {
    necessary?: {
      label: string
      description?: string
      enabled?: boolean  // Hide this category
    }
    analytics?: {
      label: string
      description?: string
      enabled?: boolean
    }
    marketing?: {
      label: string
      description?: string
      enabled?: boolean
    }
    functional?: {
      label: string
      description?: string
      enabled?: boolean
    }
  }
}

Complete Example

// docusaurus.config.ts
import type { Config } from '@docusaurus/types'

const config: Config = {
  plugins: [
    [
      'docusaurus-plugin-cookie-consent',
      {
        title: 'We Value Your Privacy',
        description:
          'We use cookies to improve your experience, analyze site traffic, and personalize content. By clicking "Accept All", you consent to our use of cookies. You can also [manage your preferences](/cookie-preferences) or read our [Privacy Policy](/privacy).',
        links: [
          { label: 'Privacy Policy', href: '/privacy' },
          { label: 'Cookie Policy', href: '/cookies' },
          { label: 'Terms of Service', href: '/terms' },
        ],
        acceptAllText: 'Accept All Cookies',
        rejectOptionalText: 'Essential Only',
        rejectAllText: 'Reject All',
        toastMode: true, // Show as bottom toast instead of modal
        storageKey: 'my-site-cookie-consent',
        categories: {
          necessary: {
            label: 'Essential Cookies',
            description: 'Required for the website to function properly. These cannot be disabled.',
          },
          analytics: {
            label: 'Analytics Cookies',
            description: 'Help us understand how visitors interact with our website.',
          },
          marketing: {
            label: 'Marketing Cookies',
            description:
              'Used to deliver personalized advertisements and track campaign performance.',
          },
          functional: {
            label: 'Functional Cookies',
            description: 'Enable enhanced functionality and personalization.',
          },
        },
      },
    ],
  ],
}

export default config

Using the Cookie Consent Hook

The plugin provides a React hook that you can use in your components to check cookie preferences and ensure compliance.

Basic Usage

import React from 'react'
import { useCookieConsent } from 'docusaurus-plugin-cookie-consent'

export default function AnalyticsComponent() {
  const { hasCategoryConsent, hasConsent } = useCookieConsent()

  // Only load analytics if user has consented
  if (!hasCategoryConsent('analytics')) {
    return null
  }

  // Load your analytics script here
  React.useEffect(() => {
    // Initialize Google Analytics, etc.
    console.log('Analytics enabled')
  }, [])

  return <div>Analytics content</div>
}

Available Hook Methods

const {
  // Check if user has given any consent
  hasConsent: () => boolean

  // Check if user has consented to a specific category
  hasCategoryConsent: (category: 'necessary' | 'analytics' | 'marketing' | 'functional') => boolean

  // Get current preferences
  preferences: CookiePreferences | null

  // Programmatically accept all cookies
  acceptAll: () => void

  // Reject optional cookies (keep only necessary)
  rejectOptional: () => void

  // Reject all cookies (except necessary)
  rejectAll: () => void

  // Update specific preferences
  updatePreferences: (prefs: Partial<CookiePreferences>) => void

  // Reset consent (show banner again)
  resetConsent: () => void
} = useCookieConsent()

Cookie Preferences Type

type CookiePreferences = {
  necessary: boolean // Always true (cannot be disabled)
  analytics: boolean
  marketing: boolean
  functional: boolean
  consentGiven: boolean
  timestamp?: number // When consent was given
}

Example: Conditional Script Loading

import React, { useEffect } from 'react'
import { useCookieConsent } from 'docusaurus-plugin-cookie-consent'

export default function ConditionalAnalytics() {
  const { hasCategoryConsent } = useCookieConsent()

  useEffect(() => {
    if (hasCategoryConsent('analytics')) {
      // Load Google Analytics
      const script = document.createElement('script')
      script.src = 'https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID'
      script.async = true
      document.head.appendChild(script)

      // Initialize gtag
      window.dataLayer = window.dataLayer || []
      function gtag(...args: any[]) {
        window.dataLayer.push(args)
      }
      gtag('js', new Date())
      gtag('config', 'GA_MEASUREMENT_ID')
    }
  }, [hasCategoryConsent])

  return null
}

Example: Show Different Content Based on Consent

import React from 'react'
import { useCookieConsent } from 'docusaurus-plugin-cookie-consent'

export default function PersonalizedContent() {
  const { hasCategoryConsent } = useCookieConsent()

  if (hasCategoryConsent('marketing')) {
    return <div>Personalized recommendations based on your interests</div>
  }

  return <div>Default content</div>
}

Markdown Support in Description

The description field supports markdown-style links:

{
  description: 'Read our [Privacy Policy](/privacy) and [Cookie Policy](/cookies) for more information.'
}

Links will be automatically converted to clickable <a> tags.

Local Storage

User preferences are automatically saved to localStorage using the key specified in storageKey (default: 'cookie-consent-preferences'). The preferences persist across page reloads and browser sessions.

To reset consent and show the banner again:

import { useCookieConsent } from 'docusaurus-plugin-cookie-consent'

function ResetButton() {
  const { resetConsent } = useCookieConsent()

  return <button onClick={resetConsent}>Reset Cookie Preferences</button>
}

Styling

The modal/toast uses inline styles for maximum compatibility. The default styling includes:

  • White background with rounded corners
  • Shadow for depth
  • Responsive design (adapts to screen size)
  • Accessible color contrast
  • Hover effects on buttons

To customize the appearance, you can:

  1. Override with CSS: Add custom CSS to your Docusaurus site that targets the cookie consent elements
  2. Use browser dev tools: Inspect the elements and add custom styles via your site's CSS

Because the plugin renders without static IDs or classes, target elements using attribute selectors (for example, [role="dialog"]) or wrap the banner in your own container for easier styling.

TypeScript Support

Full TypeScript definitions are included. Import types as needed:

import type {
  CookieConsentOptions,
  CookieCategory,
  CookieConsentLink,
  CookiePreferences,
} from 'docusaurus-plugin-cookie-consent'

Development

# Install dependencies
npm install

# Build the plugin
npm run build

# Watch mode for development
npm run dev

# Type checking
npm run typecheck

Testing Locally

To test the plugin in a local Docusaurus site:

# From your Docusaurus site directory
npm install ../path/to/docusaurus-plugin-cookie-consent

# Or create a tarball
cd ../path/to/docusaurus-plugin-cookie-consent
npm pack
cd ../../your-docusaurus-site
npm install ../path/to/docusaurus-plugin-cookie-consent/docusaurus-plugin-cookie-consent-*.tgz

Then add the plugin to your docusaurus.config.js as shown above.

Browser Support

  • Modern browsers (Chrome, Firefox, Safari, Edge)
  • Requires JavaScript enabled
  • Uses localStorage (available in all modern browsers)

GDPR Compliance

This plugin helps you comply with GDPR requirements by:

  • ✅ Obtaining explicit consent before setting non-essential cookies
  • ✅ Providing clear information about cookie usage
  • ✅ Allowing users to reject non-essential cookies
  • ✅ Storing consent preferences
  • ✅ Providing hooks to conditionally load scripts based on consent

Note: This plugin provides the UI and preference management. You are responsible for:

  • Actually respecting the preferences in your code (using the hooks)
  • Not loading analytics/marketing scripts until consent is given
  • Providing accurate privacy and cookie policy pages
  • Ensuring your implementation meets your jurisdiction's specific requirements

License

MIT

Contributing

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