docusaurus-plugin-cookie-consent
v5.0.0
Published
A cookie consent modal/toast component for Docusaurus sites with configurable text, links, and preference management.
Maintainers
Readme
Docusaurus Plugin Cookie Consent

A cookie consent modal or toast for Docusaurus sites, with configurable text, links, preference management, and Google Consent Mode support. It provides the consent UI and state; your site remains responsible for blocking optional scripts and meeting applicable privacy requirements.
Features
- ✅ Configurable text (markdown compatible)
- ✅ Configurable links to privacy policy, cookie policy, etc.
- ✅ Clear consent options: Accept all or reject optional cookies
- ✅ Helper context/hooks for respecting user preferences
- ✅ Local storage tracking of user preferences
- ✅ Optional consent expiry with automatic re-prompting
- ✅ Modal or toast mode (centered modal or bottom toast)
- ✅ Cookie categories (Necessary, Analytics, Marketing, Functional)
- ✅ Google Consent Mode v2 integration for GTM/GA4
- ✅ TypeScript support with full type definitions
Compatibility
| Plugin version | Docusaurus | React |
| -------------- | -------------------------------- | ---------------------- |
| >= 4.5.2 | ^3.0.0 (tested up to 3.10.1) | ^18.2.0 \|\| ^19.0.0 |
| <= 4.5.1 | ^3.0.0 (tested up to 3.10.1) | ^18.2.0 |
Installation
npm install docusaurus-plugin-cookie-consentQuick 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 configThat's it! The cookie consent banner will automatically appear on your site.
See API reference for the complete public API and migration guide when upgrading.
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
}>
// Optional site-owned page for detailed category management
preferencesHref?: string
preferencesLinkText?: string // default: 'Manage preferences'
// Button text customization
acceptAllText?: string // default: 'Accept all'
rejectText?: string // default: 'Reject optional'
// Local storage key for preferences (default: 'cookie-consent-preferences')
storageKey?: string
// Re-prompt after this many days. Omit to keep consent until reset.
consentExpiryDays?: number
// Show as toast (bottom of screen) instead of centered modal (default: false)
toastMode?: boolean
// Use the existing card or a full-width bottom banner (default: 'vertical')
orientation?: 'vertical' | 'horizontal'
}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
}
}
}Google Consent Mode v2 Integration
Integrate with Google Tag Manager, Google Analytics 4, and Google Ads using Google Consent Mode v2:
{
// ... other options ...
googleConsentMode: {
// Enable Google Consent Mode integration
enabled: true,
// Time to wait for consent before loading tags (default: 500ms)
waitForUpdate: 500,
// Redact ad click identifiers when ad_storage is denied (default: true)
adsDataRedaction: true,
// Pass ad click info through URL parameters when cookies denied (default: false)
urlPassthrough: false,
},
}How it works:
- Before GTM loads: Default consent is set to
deniedfor all categories - On page load: If stored consent exists, it's applied immediately
- When user consents: Google Consent Mode is updated with
gtag('consent', 'update', ...)
This ensures tracking tags configured for Consent Mode wait for user approval before firing.
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',
rejectText: 'Essential only',
toastMode: true, // Show as bottom toast instead of modal
orientation: 'horizontal', // Stretch the consent UI across the viewport
storageKey: 'my-site-cookie-consent',
consentExpiryDays: 180,
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 configUsing 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 } = useCookieConsent()
React.useEffect(() => {
if (!hasCategoryConsent('analytics')) return
// Initialize Google Analytics, etc.
console.log('Analytics enabled')
}, [hasCategoryConsent])
return null
}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, keeping necessary cookies enabled
rejectOptional: () => void
// Backward-compatible alias for rejectOptional
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 saved to localStorage using storageKey (default: 'cookie-consent-preferences'). Stored records include an internal schema version. Set consentExpiryDays to remove expired records and show the banner again.
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 and toast use stable cookie-consent-* CSS classes. The default stylesheet 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, inspect the banner and override its cookie-consent-* classes in your site's CSS. For example, target .cookie-consent-modal, .cookie-consent-button-primary, or .cookie-consent-toast.
TypeScript Support
Full TypeScript definitions are included. Import types as needed:
import type {
CookieConsentOptions,
CookieCategory,
CookieConsentLink,
CookiePreferences,
ConsentState,
GoogleConsentModeConfig,
} 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
# Tests with coverage thresholds
npm run test:coverageTesting 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-*.tgzThen 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)
Using with Google Tag Manager
When using this plugin with @docusaurus/plugin-google-gtag or @docusaurus/plugin-google-tag-manager, enable Google Consent Mode to ensure tracking respects user consent:
// docusaurus.config.ts
const config: Config = {
plugins: [
// This plugin MUST be listed BEFORE google-gtag/google-tag-manager
[
'docusaurus-plugin-cookie-consent',
{
googleConsentMode: {
enabled: true,
},
// ... other options
},
],
// Google plugins load after consent defaults are set
[
'@docusaurus/plugin-google-gtag',
{
trackingID: 'G-XXXXXXXXXX',
},
],
],
}GTM Tag Configuration
For tags in Google Tag Manager to respect consent:
- Go to your GTM container
- Navigate to Admin > Container Settings
- Enable "Enable consent overview"
- For each tag, set the appropriate consent requirement:
- Analytics tags: Require
analytics_storage - Ads/Marketing tags: Require
ad_storage
- Analytics tags: Require
Tags configured this way will only fire after the user grants consent.
Consent Mode Mapping
| Plugin Category | Google Consent Signal |
| --------------- | -------------------------------------------------- |
| analytics | analytics_storage |
| marketing | ad_storage, ad_user_data, ad_personalization |
| functional | functionality_storage, personalization_storage |
| necessary | security_storage (always granted) |
Custom Analytics Integration (PostHog, Plausible, etc.)
For analytics tools that don't support Google Consent Mode, use the browser subscription API. It reports the current stored choice, same-page changes, and changes made in other tabs.
The cookieConsentChange Event
The plugin automatically dispatches a cookieConsentChange event on the window object whenever consent preferences change:
window.addEventListener('cookieConsentChange', (event: CustomEvent) => {
const consent = event.detail
// consent = { necessary: true, analytics: boolean, marketing: boolean, functional: boolean }
if (consent.analytics) {
// Initialize your analytics
initAnalytics()
} else {
// Shutdown/disable analytics
shutdownAnalytics()
}
})Example: PostHog Integration
Create a client module that listens for consent changes:
// src/clientModules/posthog.js
import posthog from 'posthog-js'
import { subscribeToCookieConsent } from 'docusaurus-plugin-cookie-consent/client'
let initialized = false
function initPosthog() {
if (initialized) return
posthog.init('YOUR_PROJECT_KEY', { api_host: 'https://app.posthog.com' })
initialized = true
}
function shutdownPosthog() {
if (!initialized) return
posthog.opt_out_capturing()
initialized = false
}
subscribeToCookieConsent(
(consent) => {
if (consent?.analytics) {
initPosthog()
} else {
shutdownPosthog()
}
},
{ storageKey: 'cookie-consent-preferences' }
)Register the client module in a custom plugin:
// src/plugins/posthog-plugin.js
module.exports = function posthogPlugin() {
return {
name: 'posthog-plugin',
getClientModules() {
return [require.resolve('../clientModules/posthog')]
},
}
}Example: Plausible Analytics
Plausible is privacy-friendly and doesn't use cookies, so you may not need consent. But if you want to respect user preferences anyway:
window.addEventListener('cookieConsentChange', (event) => {
if (event.detail.analytics) {
// Enable Plausible tracking
delete window.plausible?.q // Clear any queued events
window.plausible =
window.plausible ||
function () {
;(window.plausible.q = window.plausible.q || []).push(arguments)
}
} else {
// Disable tracking
window.plausible = () => {} // No-op function
}
})Privacy responsibilities
This plugin supplies building blocks commonly needed by consent implementations:
- ✅ Collecting a choice before your code enables 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
It doesn't provide legal advice or automatically block third-party scripts. 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
- Confirming that your implementation meets the requirements that apply to your users
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
