A powerful, customizable React component for cookie consent management with built-in tracking prevention. This component provides a modern, user-friendly way to obtain and manage cookie consent from your website visitors.
Get up and running quickly with React Cookie Manager:
npm install react-cookie-manager
# or
yarn add react-cookie-manager
import { CookieManager } from "react-cookie-manager";
import "react-cookie-manager/style.css";
createRoot(document.getElementById("root")).render(
<StrictMode>
<CookieManager>
<App />
</CookieManager>
</StrictMode>
);
The CookieManager component needs to wrap your entire application to properly manage cookie consent across all components and pages.
- Quick Start
- Features
- Try it out
- CookieKit Integration
- Automatically Disable Tracking
- Installation
- Importing Styles
- Basic Usage
- Next.js Usage
- Full Usage
- Advanced Usage with Hook
- Props
- CSS Customization
- Cookie Categories
- Hook API
- i18next support
- Translation Options
- Contributing
- License
- ๐ Multiple display types (banner, popup, modal)
- ๐ก๏ธ Automatic tracking prevention (Google Analytics, etc.)
- ๐ฌ Smart iframe blocking for embedded content (YouTube, Vimeo, etc.)
- ๐ฏ Granular cookie category controls (Analytics, Social, Advertising)
- ๐จ Light and dark theme support
- ๐ฑ Responsive design
- ๐ง Highly customizable UI
- ๐พ Persistent consent storage
- ๐ Privacy-first approach
- ๐ช๐บ GDPR compliance with CookieKit.io integration
- ๐ช Floating cookie button for easy access
Take your GDPR compliance to the next level with CookieKit.io integration!
- ๐ Real-time consent analytics dashboard
- ๐ Automatic consent proof storage
- ๐ Advanced user segmentation
- ๐ Completely free to use!
import { CookieManager } from "react-cookie-manager";
function App() {
return (
<CookieManager
cookieKitId="" // Get this from cookiekit.io
translations={{
title: "Cookie Preferences",
message: "We use cookies to improve your experience.",
}}
>
<YourApp />
</CookieManager>
);
}
When cookieKitId
is provided, React Cookie Manager will automatically:
- Generate and track unique session IDs
- Send consent events to CookieKit.io
- Store consent proofs for GDPR compliance
- Provide analytics data in your CookieKit dashboard
Visit cookiekit.io to get started for free!
See React Cookie Manager in action and explore all its features in our interactive demo.
Unlike other cookie consent managers and React components, this component automatically disables tracking for Google Analytics, Facebook Pixel, and other tracking services. This is done by blocking the tracking scripts from loading. Therefore, you don't need to manually disable tracking, saving you hours of work.
React Cookie Manager automatically blocks embedded iframes that would otherwise load cookies without consent, such as:
- YouTube videos
- Vimeo videos
- Google Maps
- Social media embeds (Twitter, Instagram, etc.)
- Third-party widgets and tools
When a user hasn't consented to the required cookies, these embeds are replaced with user-friendly placeholders that:
- Explain why the content is blocked
- Provide a button to manage cookie settings
- Inform users to refresh the page after accepting cookies
- Maintain the same dimensions as the original content
This ensures your site remains GDPR-compliant while providing a seamless user experience.
npm install react-cookie-manager
# or
yarn add react-cookie-manager
The component requires its CSS file to be imported in your application. Add the following import to your app's entry point (e.g., App.tsx
or index.tsx
):
import "react-cookie-manager/style.css";
import { CookieManager } from "react-cookie-manager";
import "react-cookie-manager/style.css";
function App() {
return (
<CookieManager
translations={{
title: "Cookie Preferences",
message: "We use cookies to improve your experience.",
}}
onManage={(preferences) =>
console.log("Cookie preferences:", preferences)
}
>
<YourApp />
</CookieManager>
);
}
For Next.js applications, you'll need to use dynamic imports to prevent SSR of the cookie manager:
"use client";
import dynamic from "next/dynamic";
const CookieManager = dynamic(
() => import("react-cookie-manager").then((mod) => mod.CookieManager),
{ ssr: false, loading: () => null }
);
// In your Providers component or layout
export function Providers({ children }: { children: React.ReactNode }) {
return (
<CookieManager
showManageButton={true}
translations={{
title: "Cookie Preferences",
message: "We use cookies to improve your experience.",
}}
displayType="banner"
theme="light"
>
{children}
</CookieManager>
);
}
// In your page component
import { useCookieConsent } from "react-cookie-manager";
export default function Home() {
const { showConsentBanner, detailedConsent } = useCookieConsent();
return (
<div>
<button onClick={showConsentBanner}>Manage Cookie Settings</button>
{detailedConsent && (
<div>
Analytics:{" "}
{detailedConsent.Analytics.consented ? "Enabled" : "Disabled"}
Social: {detailedConsent.Social.consented ? "Enabled" : "Disabled"}
Advertising:{" "}
{detailedConsent.Advertising.consented ? "Enabled" : "Disabled"}
</div>
)}
</div>
);
}
import { CookieManager } from "react-cookie-manager";
import "react-cookie-manager/style.css";
function App() {
return (
<CookieManager
translations={{
title: "Would You Like A Cookie? ๐ช",
message:
"We value your privacy. Choose which cookies you want to allow. Essential cookies are always enabled as they are necessary for the website to function properly.",
buttonText: "Accept All",
declineButtonText: "Decline All",
manageButtonText: "Manage Cookies",
privacyPolicyText: "Privacy Policy",
}}
showManageButton={true}
privacyPolicyUrl="https://example.com/privacy"
theme="light"
displayType="popup"
cookieKitId="" // Optional: Enable CookieKit.io integration
onManage={(preferences) => {
if (preferences) {
console.log("Cookie preferences updated:", preferences);
}
}}
onAccept={() => {
console.log("User accepted all cookies");
// Analytics tracking can be initialized here
}}
onDecline={() => {
console.log("User declined all cookies");
// Handle declined state if needed
}}
>
<AppContent />
</CookieManager>
);
}
import { CookieManager, useCookieConsent } from "react-cookie-manager";
function CookieSettings() {
const { showConsentBanner, detailedConsent } = useCookieConsent();
return (
<div>
<button onClick={showConsentBanner}>Manage Cookie Settings</button>
{detailedConsent && (
<div>
Analytics:{" "}
{detailedConsent.Analytics.consented ? "Enabled" : "Disabled"}
Social: {detailedConsent.Social.consented ? "Enabled" : "Disabled"}
Advertising:{" "}
{detailedConsent.Advertising.consented ? "Enabled" : "Disabled"}
</div>
)}
</div>
);
}
The floating cookie button provides a persistent, accessible way for users to manage their cookie preferences after they've made their initial choice. It appears as a small, animated cookie icon in the bottom-left corner of the screen.
<CookieManager
enableFloatingButton={true}
theme="light" // or "dark"
// ... other props
>
<YourApp />
</CookieManager>
- ๐ฏ Automatically appears after initial consent
- ๐จ Matches your theme (light/dark mode)
- ๐ Smooth animations and hover effects
- โ Dismissible with a close button
- ๐ฑ Responsive and mobile-friendly
- ๐๏ธ Easy access to cookie preferences
- The button appears after users make their initial cookie choice
- Hovering reveals a close button to dismiss the floating button
- Clicking opens the cookie preferences modal
- The button remains hidden until page refresh after being closed
- Maintains position during scroll
The floating button automatically adapts to your chosen theme:
// Light theme (default)
<CookieManager
enableFloatingButton={true}
theme="light"
>
<YourApp />
</CookieManager>
// Dark theme
<CookieManager
enableFloatingButton={true}
theme="dark"
>
<YourApp />
</CookieManager>
The button inherits your color scheme:
- Light theme: White background with gray text
- Dark theme: Black background with light gray text
The floating button is fully accessible:
- Proper ARIA labels
- Keyboard navigation support
- Focus management
- High contrast ratios
- Screen reader friendly
Prop | Type | Default | Description |
---|---|---|---|
children |
React.ReactNode | - | Your app components |
translations |
TranslationObject | TranslationFunction | - | Translation object or i18n TFunction |
translationI18NextPrefix |
string | - | i18next key prefix, e.g. "cookies." |
showManageButton |
boolean | false | Whether to show the manage cookies button |
enableFloatingButton |
boolean | false | Enable floating cookie button |
privacyPolicyUrl |
string | - | URL for the privacy policy |
cookieKey |
string | 'cookie-consent' | Name of the cookie to store consent |
cookieExpiration |
number | 365 | Days until cookie expires |
displayType |
'banner' | 'popup' | 'modal' | 'banner' | How the consent UI is displayed |
position |
'top' | 'bottom' | 'bottom' | Position of the banner |
theme |
'light' | 'dark' | 'light' | Color theme |
disableAutomaticBlocking |
boolean | false | Disable automatic tracking prevention |
blockedDomains |
string[] | [] | Additional domains to block |
cookieKitId |
string | undefined | Your CookieKit.io integration ID |
onManage |
(preferences?: CookieCategories) => void | - | Callback when preferences are updated |
onAccept |
() => void | - | Callback when all cookies are accepted |
onDecline |
() => void | - | Callback when all cookies are declined |
classNames |
CookieConsenterClassNames | - | Custom class names for styling |
React Cookie Manager provides extensive styling customization through the classNames
prop. You can override the default styling for each element of the cookie consent UI.
<CookieManager
classNames={{
// Main action buttons
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",
// Banner style (bottom of screen)
bannerContainer:
"bg-white/90 border-2 border-blue-200 shadow-xl rounded-xl",
bannerContent: "p-6 space-y-4",
bannerTitle: "text-lg font-bold text-blue-800",
bannerMessage: "text-sm text-gray-700",
// Popup style (bottom left corner)
popupContainer: "bg-white/90 border-2 border-blue-200 shadow-xl rounded-xl",
popupContent: "p-6 space-y-4",
popupTitle: "text-lg font-bold text-blue-800",
popupMessage: "text-sm text-gray-700",
// Modal style (center of screen)
modalContainer: "bg-black/50 backdrop-blur-sm",
modalContent: "bg-white p-8 rounded-xl max-w-lg mx-auto",
modalTitle: "text-xl font-bold text-gray-900",
modalMessage: "text-gray-600 my-4",
// Floating cookie button (appears after consent is given)
floatingButton: "bg-blue-500 text-white shadow-lg hover:bg-blue-600",
floatingButtonCloseButton: "bg-red-500 text-white",
// Manage Cookie UI elements
manageCookieContainer: "space-y-6",
manageCookieTitle: "text-xl font-bold text-blue-800",
manageCookieMessage: "text-gray-700",
manageCookieCategory: "border-b border-gray-200 pb-4",
manageCookieCategoryTitle: "font-bold text-gray-800",
manageCookieCategorySubtitle: "text-gray-600",
manageCookieStatusText: "text-xs text-gray-500 italic",
manageCookieToggle: "bg-gray-300",
manageCookieToggleChecked: "bg-green-500",
manageCancelButton:
"bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded",
manageSaveButton:
"bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded",
// Other elements
privacyPolicyLink: "text-blue-600 underline hover:text-blue-800",
poweredByLink: "text-gray-400 hover:text-gray-600",
}}
>
{children}
</CookieManager>
The classNames
prop is compatible with any CSS framework. Here are some examples:
<CookieManager
classNames={{
acceptButton:
"bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded",
declineButton:
"bg-red-500 hover:bg-red-600 text-white font-bold py-2 px-4 rounded",
bannerContainer: "bg-white shadow-lg rounded-lg border border-gray-200",
}}
>
{children}
</CookieManager>
<CookieManager
classNames={{
acceptButton: "btn btn-success",
declineButton: "btn btn-danger",
manageButton: "btn btn-outline-primary",
bannerContainer: "card",
bannerContent: "card-body",
bannerTitle: "card-title",
bannerMessage: "card-text",
}}
>
{children}
</CookieManager>
The classNames are organized by component type:
-
acceptButton
: Style for the Accept/Allow cookies button -
declineButton
: Style for the Decline/Reject cookies button -
manageButton
: Style for the Manage Cookies button -
manageCancelButton
: Style for the Cancel button in the manage preferences view -
manageSaveButton
: Style for the Save Preferences button
-
bannerContainer
: Main container for the banner-style consent UI -
popupContainer
: Main container for the popup-style consent UI -
modalContainer
: Main container for the modal-style consent UI -
manageCookieContainer
: Container for the manage preferences UI
-
bannerContent
,popupContent
,modalContent
: Content containers for each display type -
bannerTitle
,popupTitle
,modalTitle
: Title elements for each display type -
bannerMessage
,popupMessage
,modalMessage
: Message elements for each display type
-
manageCookieTitle
: Title for the manage cookie preferences UI -
manageCookieMessage
: Description text in the manage preferences UI -
manageCookieCategory
: Container for each cookie category -
manageCookieCategoryTitle
: Title for each cookie category -
manageCookieCategorySubtitle
: Description for each cookie category -
manageCookieStatusText
: Status text showing consent status and date -
manageCookieToggle
: Toggle switch for cookie categories -
manageCookieToggleChecked
: Style applied to the toggle when checked
-
privacyPolicyLink
: Style for the privacy policy link -
floatingButton
: Style for the floating cookie button -
floatingButtonCloseButton
: Style for the close button on the floating cookie button -
poweredByLink
: Style for the "Powered by CookieKit" link
The component manages three categories of cookies:
interface CookieCategories {
Analytics: boolean;
Social: boolean;
Advertising: boolean;
}
The useCookieConsent
hook provides the following:
interface CookieConsentHook {
hasConsent: boolean | null;
isDeclined: boolean;
detailedConsent: DetailedCookieConsent | null;
showConsentBanner: () => void;
acceptCookies: () => void;
declineCookies: () => void;
updateDetailedConsent: (preferences: CookieCategories) => void;
}
The CookieManager component provides callback props that allow you to respond to user interactions with the consent UI:
Callback | Triggered when | Parameters |
---|---|---|
onAccept |
User accepts all cookies | None |
onDecline |
User declines all cookies | None |
onManage |
User saves custom cookie preferences | preferences?: CookieCategories |
<CookieManager
onAccept={() => {
console.log("All cookies accepted");
// Initialize analytics tools
window.gtag?.("consent", "update", { analytics_storage: "granted" });
}}
onDecline={() => {
console.log("All cookies declined");
// Ensure tracking is disabled
window.gtag?.("consent", "update", { analytics_storage: "denied" });
}}
onManage={(preferences) => {
console.log("Custom preferences saved:", preferences);
// Handle granular consent
if (preferences?.Analytics) {
// Enable analytics
}
if (preferences?.Advertising) {
// Enable ad personalization
}
}}
>
{children}
</CookieManager>
- Analytics Initialization: Only initialize tracking tools after receiving explicit consent
- Ad Personalization: Enable or disable personalized advertising based on user preferences
- Social Media Integration: Load social widgets only when Social cookies are accepted
- Consent Logging: Record user consent choices for compliance purposes
- UI Updates: Update the UI based on user consent status (e.g., showing alternative content)
import { default as i18next } from "i18next";
function App() {
return (
<CookieManager
translations={i18next.t}
translationI18NextPrefix="cookies."
...
/>
)
}
// en.json
{
"cookies": {
"title": "Would You Like A Cookie? ๐ช",
"message": "We value your privacy. Choose which cookies you want to allow. Essential cookies are always enabled as they are necessary for the website to function properly.",
"buttonText": "Accept All",
"declineButtonText": "Decline All",
"manageButtonText": "Manage Cookies",
"privacyPolicyText": "Privacy Policy"
}
//...
}
All available translation keys and their default values:
{
// Main consent banner/popup/modal
title: "", // Optional title
message: "This website uses cookies to enhance your experience.",
buttonText: "Accept",
declineButtonText: "Decline",
manageButtonText: "Manage Cookies",
privacyPolicyText: "Privacy Policy",
// Manage consent modal
manageTitle: "Cookie Preferences",
manageMessage: "Manage your cookie preferences below. Essential cookies are always enabled as they are necessary for the website to function properly.",
// Essential cookies section
manageEssentialTitle: "Essential",
manageEssentialSubtitle: "Required for the website to function properly",
manageEssentialStatus: "Status: Always enabled",
manageEssentialStatusButtonText: "Always On",
// Analytics cookies section
manageAnalyticsTitle: "Analytics",
manageAnalyticsSubtitle: "Help us understand how visitors interact with our website",
// Social cookies section
manageSocialTitle: "Social",
manageSocialSubtitle: "Enable social media features and sharing",
// Advertising cookies section
manageAdvertTitle: "Advertising",
manageAdvertSubtitle: "Personalize advertisements and measure their performance",
// Status messages
manageCookiesStatus: "Status: {{status}} on {{date}}", // Supports variables
manageCookiesStatusConsented: "Consented",
manageCookiesStatusDeclined: "Declined",
// Buttons in manage modal
manageCancelButtonText: "Cancel",
manageSaveButtonText: "Save Preferences"
}
You can override any of these translations by passing them in the translations
prop:
<CookieManager
translations={{
title: "Cookie Settings ๐ช",
message: "We use cookies to improve your experience.",
buttonText: "Allow All",
manageButtonText: "Customize",
// ... override any other translations
}}
>
<App />
</CookieManager>
When using i18next, make sure your translation files include all the keys under your chosen prefix:
{
"cookies": {
"title": "Cookie Settings ๐ช",
"message": "We use cookies to improve your experience.",
"buttonText": "Allow All",
"declineButtonText": "Decline All",
"manageButtonText": "Customize",
"privacyPolicyText": "Privacy Policy",
"manageTitle": "Cookie Preferences",
"manageMessage": "Customize your cookie preferences below...",
"manageEssentialTitle": "Essential Cookies"
// ... include all other translation keys
}
}
Then use it with the i18next translation function:
import { useTranslation } from "react-i18next";
function App() {
const { t } = useTranslation();
return (
<CookieManager translations={t} translationI18NextPrefix="cookies.">
<YourApp />
</CookieManager>
);
}
Contributions are welcome! Please feel free to submit a Pull Request.
MIT ยฉ Hypership