Privacy & Consent Components

2 Components

GDPR and CCPA compliant UI components for cookie consent and privacy preferences. Built-in support for consent categories, audit trails, and regulatory compliance.

GDPR Ready

Both components are designed for GDPR, CCPA, and ePrivacy compliance. They automatically handle consent storage, audit trails, and respect Global Privacy Control (GPC) signals.
Installation
import {
  CookieBanner,
  ConsentPreferences,
} from '@sylphx/platform-sdk/react'

CookieBanner

A fully customizable cookie consent banner that appears on first visit. Supports multiple positions, themes, and consent granularity. Automatically stores consent decisions and respects GPC signals.

GDPR Compliant
GPC Support
Themeable
Basic Usage
import { CookieBanner } from '@sylphx/platform-sdk/react'

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <CookieBanner
          onAcceptAll={() => {
            console.log('All cookies accepted')
            // Initialize analytics, marketing scripts, etc.
          }}
          onDecline={() => {
            console.log('Optional cookies declined')
          }}
          onPreferencesChange={(consents) => {
            console.log('Consent preferences:', consents)
          }}
        />
      </body>
    </html>
  )
}

Props

PropertyTypeDescription
onAcceptAll() => voidCallback fired when user accepts all cookies
onDecline() => voidCallback fired when user declines optional cookies
onPreferencesChange(consents: ConsentState) => voidCallback fired when consent preferences change
onBannerShow() => voidCallback fired when banner is displayed
onBannerHide() => voidCallback fired when banner is hidden
categoriesConsentCategory[]Custom consent categories to display
position"bottom" | "top" | "bottom-left" | "bottom-right" | "center"= "bottom"Banner position on screen
variant"bar" | "modal" | "floating"= "bar"Banner visual style
showPreferencesButtonboolean= trueShow button to open detailed preferences
showDeclineButtonboolean= trueShow decline/reject button
respectGPCboolean= trueAutomatically respect Global Privacy Control signal
respectDNTboolean= falseRespect Do Not Track browser setting
forceShowboolean= falseForce banner to show (for testing)
cookieNamestring= "sylphx_consent"Name of consent storage cookie
cookieExpirynumber= 365Consent cookie expiry in days
privacyPolicyUrlstring= "/privacy"Link to privacy policy
titlestring= "Cookie Preferences"Banner title text
descriptionstring | ReactNodeBanner description text
acceptAllLabelstring= "Accept All"Accept all button text
declineLabelstring= "Decline Optional"Decline button text
preferencesLabelstring= "Manage Preferences"Preferences button text
themeThemeVariablesCustom theme overrides
classNamestringAdditional CSS classes

ConsentCategory Type

PropertyTypeDescription
idrequiredstringUnique category identifier
namerequiredstringDisplay name for the category
descriptionrequiredstringExplanation of what this category covers
requiredboolean= falseWhether consent is mandatory (always enabled)
defaultboolean= falseDefault state if user has not chosen
cookiesstring[]List of cookie names in this category
scriptsstring[]Third-party script domains in this category

Advanced Examples

<CookieBanner
  categories={[
    {
      id: 'necessary',
      name: 'Essential',
      description: 'Required for the website to function properly',
      required: true,
      default: true,
      cookies: ['session', 'csrf_token', 'sylphx_consent'],
    },
    {
      id: 'analytics',
      name: 'Analytics',
      description: 'Help us understand how visitors use our site',
      required: false,
      default: false,
      cookies: ['_ga', '_gid', '_gat'],
      scripts: ['google-analytics.com', 'plausible.io'],
    },
    {
      id: 'marketing',
      name: 'Marketing & Advertising',
      description: 'Used for targeted advertising and retargeting',
      required: false,
      default: false,
      cookies: ['_fbp', '_gcl_au'],
      scripts: ['facebook.com', 'doubleclick.net'],
    },
    {
      id: 'preferences',
      name: 'Preferences',
      description: 'Remember your settings and preferences',
      required: false,
      default: true,
      cookies: ['theme', 'language', 'timezone'],
    },
  ]}
/>

GDPR Requirements

Under GDPR, non-essential cookies must be opt-in by default. Set default: false for analytics, marketing, and targeting categories. The banner should be shown before any non-essential cookies are set.

ConsentPreferences

A detailed consent preferences panel for users to manage their privacy choices at any time. Can be embedded in settings pages or shown as a modal. Includes granular controls for each consent category.

Granular Control
Audit Trail
Cookie List
Basic Usage
import { ConsentPreferences } from '@sylphx/platform-sdk/react'

export default function PrivacySettingsPage() {
  return (
    <div className="max-w-2xl mx-auto py-8">
      <h1 className="text-2xl font-bold mb-6">Privacy Settings</h1>
      <ConsentPreferences
        onSave={(consents) => {
          console.log('Saved preferences:', consents)
          toast.success('Privacy preferences saved!')
        }}
        onChange={(category, enabled) => {
          console.log(`${category} is now ${enabled ? 'enabled' : 'disabled'}`)
        }}
      />
    </div>
  )
}

Props

PropertyTypeDescription
onSave(consents: ConsentState) => voidCallback fired when user saves preferences
onChange(category: string, enabled: boolean) => voidCallback fired when a category toggle changes
onClose() => voidCallback fired when panel is closed (modal mode)
categoriesConsentCategory[]Custom consent categories to display
layout"card" | "flat" | "accordion"= "card"Visual layout style
showCookieListboolean= trueShow list of cookies per category
showScriptListboolean= trueShow list of third-party scripts per category
showAcceptAllboolean= trueShow "Accept All" button
showDeclineAllboolean= trueShow "Decline All" button
showSaveButtonboolean= trueShow save button (vs auto-save)
autoSaveboolean= falseAuto-save on toggle change
showConsentHistoryboolean= falseShow consent change history
showGPCStatusboolean= trueShow Global Privacy Control status
showLastUpdatedboolean= trueShow when consent was last updated
titlestring= "Privacy Preferences"Panel title
descriptionstring | ReactNodePanel description text
saveLabelstring= "Save Preferences"Save button text
acceptAllLabelstring= "Accept All"Accept all button text
declineAllLabelstring= "Decline All"Decline all button text
privacyPolicyUrlstring= "/privacy"Link to privacy policy
cookiePolicyUrlstring= "/cookies"Link to cookie policy
themeThemeVariablesCustom theme overrides
classNamestringAdditional CSS classes

ConsentState Type

Types
interface ConsentState {
  necessary: boolean   // Always true (required)
  analytics: boolean
  marketing: boolean
  functional: boolean
  targeting: boolean
  [key: string]: boolean // Custom categories
}

interface ConsentRecord {
  timestamp: string      // ISO timestamp
  action: 'grant' | 'revoke' | 'update'
  categories: string[]   // Affected categories
  source: 'banner' | 'preferences' | 'api'
  gpcEnabled?: boolean   // GPC signal at time of consent
}

Advanced Examples

<ConsentPreferences
  layout="accordion"
  showCookieList={true}
  showScriptList={true}
  categories={[
    {
      id: 'necessary',
      name: 'Strictly Necessary',
      description: 'These cookies are essential for the website to function and cannot be disabled.',
      required: true,
      default: true,
      cookies: [
        'session - Maintains your logged-in session',
        'csrf_token - Protects against cross-site attacks',
        'sylphx_consent - Stores your cookie preferences',
      ],
    },
    {
      id: 'analytics',
      name: 'Analytics & Performance',
      description: 'These cookies help us understand how visitors interact with our website.',
      required: false,
      default: false,
      cookies: [
        '_ga - Google Analytics visitor ID',
        '_gid - Google Analytics session ID',
        '_gat - Google Analytics rate limiter',
      ],
      scripts: [
        'google-analytics.com',
        'googletagmanager.com',
      ],
    },
    {
      id: 'marketing',
      name: 'Marketing & Advertising',
      description: 'These cookies are used to deliver personalized advertisements.',
      required: false,
      default: false,
      cookies: [
        '_fbp - Facebook Pixel',
        '_gcl_au - Google Ads conversion tracking',
      ],
      scripts: [
        'facebook.com',
        'doubleclick.net',
        'adsrvr.org',
      ],
    },
  ]}
/>

Consent Audit Trail

The ConsentPreferences component automatically logs all consent changes with timestamps, user agent, and source. Use showConsentHistory={true} to display this history to users.

Integration with Analytics

Use the consent state to conditionally load analytics and marketing scripts.

Conditional Script Loading
'use client'

import { useConsent } from '@sylphx/platform-sdk/react'
import Script from 'next/script'

export function AnalyticsProvider({ children }) {
  const { hasConsent, isLoading } = useConsent()

  // Don't render scripts until consent state is loaded
  if (isLoading) return <>{children}</>

  return (
    <>
      {/* Only load Google Analytics if user consented */}
      {hasConsent('analytics') && (
        <>
          <Script
            src="https://www.googletagmanager.com/gtag/js?id=G-XXXXX"
            strategy="afterInteractive"
          />
          <Script id="google-analytics" strategy="afterInteractive">
            {`
              window.dataLayer = window.dataLayer || [];
              function gtag(){dataLayer.push(arguments);}
              gtag('js', new Date());
              gtag('config', 'G-XXXXX');
            `}
          </Script>
        </>
      )}

      {/* Only load Facebook Pixel if user consented to marketing */}
      {hasConsent('marketing') && (
        <Script id="facebook-pixel" strategy="afterInteractive">
          {`
            !function(f,b,e,v,n,t,s)
            {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
            n.callMethod.apply(n,arguments):n.queue.push(arguments)};
            // ... pixel code
          `}
        </Script>
      )}

      {children}
    </>
  )
}

useConsent Hook

Access consent state and methods from anywhere in your app.

Hook Usage
import { useConsent } from '@sylphx/platform-sdk/react'

function MyComponent() {
  const {
    // State
    consents,           // Current consent state object
    hasResponded,       // Whether user has made a choice
    isLoading,          // Loading state
    gpcEnabled,         // Global Privacy Control signal detected
    lastUpdated,        // Timestamp of last consent update

    // Methods
    hasConsent,         // Check single category: hasConsent('analytics')
    setConsent,         // Set single: setConsent('analytics', true)
    setConsents,        // Set multiple: setConsents({ analytics: true, marketing: false })
    acceptAll,          // Accept all categories
    declineOptional,    // Decline all non-required categories
    resetConsent,       // Clear all consent (re-show banner)
    showBanner,         // Programmatically show banner
    showPreferences,    // Programmatically show preferences modal

    // History
    consentHistory,     // Array of ConsentRecord
  } = useConsent()

  const handleAnalyticsAction = () => {
    if (hasConsent('analytics')) {
      // Track the event
      analytics.track('button_clicked')
    } else {
      // Prompt for consent
      showPreferences()
    }
  }

  return (
    <button onClick={handleAnalyticsAction}>
      Track Me
    </button>
  )
}
PropertyTypeDescription
consentsConsentStateCurrent consent state for all categories
hasRespondedbooleanWhether user has made any consent choice
isLoadingbooleanTrue while loading consent state from storage
gpcEnabledbooleanTrue if Global Privacy Control signal is detected
lastUpdatedDate | nullWhen consent was last updated
consentHistoryConsentRecord[]Array of consent change records
hasConsent(id)(id: string) => booleanCheck if specific category is consented
setConsent(id, value)(id: string, value: boolean) => voidSet consent for a single category
setConsents(consents)(consents: Partial<ConsentState>) => voidSet multiple consents at once
acceptAll()() => voidAccept all consent categories
declineOptional()() => voidDecline all non-required categories
resetConsent()() => voidClear all consent data (triggers banner)
showBanner()() => voidProgrammatically show the cookie banner
showPreferences()() => voidProgrammatically show preferences panel

Theming

Both components support theming via the theme prop. Customize colors, fonts, and border radius to match your brand.

Custom Theme
import { CookieBanner, ConsentPreferences, type ThemeVariables } from '@sylphx/platform-sdk/react'

const privacyTheme: ThemeVariables = {
  colorPrimary: '#10b981',
  colorPrimaryHover: '#059669',
  colorBackground: '#ffffff',
  colorForeground: '#1f2937',
  colorMuted: '#f3f4f6',
  colorMutedForeground: '#6b7280',
  colorBorder: '#e5e7eb',
  colorDestructive: '#ef4444',
  colorSuccess: '#22c55e',
  fontFamily: 'Inter, sans-serif',
  fontSize: '14px',
  borderRadius: '0.75rem',
}

// Apply to both components
<CookieBanner theme={privacyTheme} />
<ConsentPreferences theme={privacyTheme} />

Best Practices

Show Before Tracking

Display the consent banner before loading any non-essential cookies or tracking scripts.

Default to Opt-Out

For GDPR compliance, non-essential cookies should be disabled by default.

Respect GPC Signals

Enable respectGPC to automatically honor Global Privacy Control browser settings.

Provide Granular Control

Let users choose specific categories rather than just accept/reject all.

Maintain Audit Trails

Log consent changes with timestamps for regulatory compliance.

Easy Access to Settings

Make it easy for users to change their preferences at any time from settings or footer links.

Need server-side consent checking?

Use the consent API to check consent status server-side before sending marketing emails or tracking events.