CookieFast

React Integration

Integrate CookieFast into your React application with proper TypeScript support.

Quick Start

Using React Helmet

Install React Helmet:

npm install react-helmet

Add to your root component (App.tsx or App.jsx):

import { Helmet } from 'react-helmet';
function App() {
return (
<>
<Helmet>
<script
async
src="https://cdn.cookiefa.st/cookiefast.js"
data-api-key={import.meta.env.VITE_COOKIEFAST_API_KEY}
/>
</Helmet>
{/* Your app content */}
<Router>
<Routes>
{/* ... */}
</Routes>
</Router>
</>
);
}

Direct Script Injection

In your public/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- CookieFast -->
<script
async
src="https://cdn.cookiefa.st/cookiefast.js"
data-api-key="%REACT_APP_COOKIEFAST_API_KEY%"
></script>
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>

Environment Variables

Create React App

.env:

REACT_APP_COOKIEFAST_API_KEY=your-api-key-here

Vite

.env:

VITE_COOKIEFAST_API_KEY=your-api-key-here

React Hook for Consent

Create a custom hook to manage consent:

// hooks/useCookieConsent.ts
import { useState, useEffect } from 'react';
interface CookieConsent {
analytics: boolean;
marketing: boolean;
essential: boolean;
}
export function useCookieConsent() {
const [consent, setConsent] = useState<CookieConsent | null>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
// Listen for consent changes
const handleConsent = (event: CustomEvent<CookieConsent>) => {
setConsent(event.detail);
setIsLoading(false);
};
window.addEventListener('cookiefast:consent', handleConsent as EventListener);
// Check if consent already exists
if (window.CookieFast) {
const existingConsent = window.CookieFast.getConsent();
if (existingConsent) {
setConsent(existingConsent);
setIsLoading(false);
}
}
return () => {
window.removeEventListener('cookiefast:consent', handleConsent as EventListener);
};
}, []);
const showBanner = () => {
window.CookieFast?.showBanner();
};
return { consent, isLoading, showBanner };
}

Usage in Components

import { useCookieConsent } from './hooks/useCookieConsent';
function AnalyticsComponent() {
const { consent, isLoading } = useCookieConsent();
useEffect(() => {
if (consent?.analytics) {
// Initialize Google Analytics
console.log('Analytics enabled, initializing...');
initializeGA();
}
}, [consent]);
if (isLoading) {
return <div>Loading consent...</div>;
}
return (
<div>
Analytics Status: {consent?.analytics ? 'Enabled' : 'Disabled'}
</div>
);
}

Cookie Settings Button

Create a reusable button component:

// components/CookieSettingsButton.tsx
import { useCookieConsent } from '../hooks/useCookieConsent';
export function CookieSettingsButton() {
const { showBanner } = useCookieConsent();
return (
<button
onClick={showBanner}
className="cookie-settings-btn"
>
Cookie Settings
</button>
);
}

Use it anywhere:

function Footer() {
return (
<footer>
<CookieSettingsButton />
</footer>
);
}

TypeScript Declarations

Add type declarations for window.CookieFast:

// types/cookiefast.d.ts
interface CookieConsentDetail {
analytics: boolean;
marketing: boolean;
essential: boolean;
}
interface CookieFast {
getConsent(): CookieConsentDetail | null;
showBanner(): void;
}
interface Window {
CookieFast?: CookieFast;
}
interface WindowEventMap {
'cookiefast:consent': CustomEvent<CookieConsentDetail>;
}

Conditional Analytics Initialization

// App.tsx
import { useEffect } from 'react';
import { useCookieConsent } from './hooks/useCookieConsent';
function App() {
const { consent } = useCookieConsent();
useEffect(() => {
if (consent?.analytics) {
// Initialize 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);
window.dataLayer = window.dataLayer || [];
function gtag(...args: any[]) {
window.dataLayer.push(args);
}
gtag('js', new Date());
gtag('config', 'GA_MEASUREMENT_ID');
}
}, [consent?.analytics]);
return <div>{/* Your app */}</div>;
}

React Context Provider

Create a context for app-wide consent management:

// contexts/ConsentContext.tsx
import { createContext, useContext, ReactNode } from 'react';
import { useCookieConsent } from '../hooks/useCookieConsent';
const ConsentContext = createContext<ReturnType<typeof useCookieConsent> | null>(null);
export function ConsentProvider({ children }: { children: ReactNode }) {
const consent = useCookieConsent();
return (
<ConsentContext.Provider value={consent}>
{children}
</ConsentContext.Provider>
);
}
export function useConsent() {
const context = useContext(ConsentContext);
if (!context) {
throw new Error('useConsent must be used within ConsentProvider');
}
return context;
}

Use in your app:

// index.tsx
import { ConsentProvider } from './contexts/ConsentContext';
ReactDOM.render(
<ConsentProvider>
<App />
</ConsentProvider>,
document.getElementById('root')
);

Next Steps