Comprehensive Rules for implementing region-aware, audit-ready consent management across web applications using TypeScript/JavaScript, React/Next.js and Node.js, aligned with Google Consent Mode v2 and IAB TCF v2.2.
You know the drill. Another privacy law update lands in your inbox. Your legal team is asking for granular consent tracking across 15 different jurisdictions. Marketing wants Google Analytics running immediately, but only after proper consent. Your CMP integration is breaking in Safari private mode. And somehow, you need to make "Accept All" and "Reject All" buttons equally prominent while your stakeholders keep pushing for dark patterns.
Sound familiar? You're spending more time debugging consent workflows than building actual features.
These Advanced Consent Management Rules transform Cursor into your privacy compliance co-pilot. Instead of manually wrestling with IAB TCF strings, Google Consent Mode configurations, and jurisdiction-specific consent requirements, you get:
Automated Region-Aware Consent Logic: Cursor automatically generates TypeScript code that detects user jurisdiction and maps to appropriate consent purposes. No more hardcoded consent flows that break when you expand to new markets.
CMP-Agnostic Integration Patterns: Whether you're using Usercentrics, OneTrust, or Cookiebot, the rules generate consistent wrapper patterns that prevent vendor lock-in and make switching CMPs trivial.
Audit-Ready Data Structures: Every generated consent record includes proper versioning, timestamps, and immutable audit trails that satisfy compliance officers and regulators.
Instead of researching consent frameworks and debugging storage edge cases, Cursor generates production-ready consent management code with proper error handling, accessibility, and performance optimization built-in.
The rules enforce equal button prominence, clear language validation, and opt-out defaults automatically. Your consent banners pass regulatory scrutiny without manual review cycles.
Generate consistent consent patterns whether you're using React, Next.js, or vanilla TypeScript. Switch between CMPs without rewriting core logic.
Automatic audit logging, consent refresh scheduling, and privacy-safe error reporting mean you're always ready for compliance audits.
// Your typical consent integration nightmare
useEffect(() => {
// Wait, do I check localStorage or cookies first?
const consent = localStorage.getItem('consent');
if (consent) {
// This breaks in Safari private mode...
gtag('consent', 'update', { analytics_storage: 'granted' });
}
// Missing error handling, accessibility, audit trail...
}, []);
When you type "implement consent management", Cursor generates:
export const useConsentManager = (): ConsentManagerResult => {
const { consent, updateConsent } = useContext(ConsentContext);
const { region } = useRegionDetection();
const grantConsent = useCallback(async (
purposes: ConsentPurpose[],
auditInfo: ConsentAuditInfo
): Promise<ConsentRecord> => {
const record = await saveConsentWithAudit({
purposes,
region,
auditInfo,
timestamp: new Date().toISOString(),
version: CURRENT_BANNER_VERSION
});
// Auto-sync with Google Consent Mode
updateGoogleConsentMode(record);
return record;
}, [region]);
return { consent, grantConsent, isLoading: consent === null };
};
Before: 30 minutes of research, manual consent checking, debugging Safari issues After: Type your requirement, get compliant implementation in 30 seconds
// Cursor auto-generates this when you describe your tracking needs
export const ConditionalScript: React.FC<{
src: string;
purpose: ConsentPurpose;
children?: React.ReactNode;
}> = ({ src, purpose, children }) => {
const { hasConsent } = useConsent();
if (!hasConsent(purpose)) return null;
return (
<Script
src={src}
strategy="afterInteractive"
onLoad={() => logConsentAction('script_loaded', { src, purpose })}
>
{children}
</Script>
);
};
Copy the Cursor Rules into your .cursorrules file. The rules automatically configure TypeScript strict mode and set up the proper project structure.
Ask Cursor: "Set up a consent management system for [your CMP] with EU/US-CA compliance"
Cursor generates:
Request: "Integrate with [Usercentrics/OneTrust/Cookiebot] and map to Google Consent Mode"
You get vendor-specific wrapper code that handles:
The rules include testing patterns, security configurations, and performance budgets. Your consent implementation is audit-ready from day one.
A typical e-commerce site implementing these patterns saw:
The rules work immediately with your existing TypeScript/React setup. No additional dependencies required - just copy the rules and start building privacy-compliant features at the speed of thought.
Your next privacy compliance deadline doesn't have to be a sprint. With these Cursor Rules, it's just another Tuesday.
Ready to transform your privacy development workflow? Copy these rules into your .cursorrules file and watch Cursor become your consent management expert.
You are an expert in TypeScript (5.x), JavaScript (ES2023), Node.js (18+), React 18+, Next.js 14, Google Consent Mode v2, IAB Transparency & Consent Framework v2.2, and leading CMP SDKs (Usercentrics, OneTrust, Cookiebot, Didomi).
Key Principles
- Privacy-by-default: do not collect or transmit personal data until consent is stored as “granted.”
- Region & purpose awareness: always resolve the user’s jurisdiction and map it to required consent purposes before loading vendors.
- Granular control: store consent at the smallest practical scope—purpose & vendor—using clear, human-readable keys (e.g., marketing.email, analytics.google_ua).
- No dark patterns: "Accept" and "Reject" actions must be equally prominent; default selections must be opt-out for non-essential processing.
- Auditability: every consent change must be time-stamped (ISO-8601), versioned, and linked to the UI text that was displayed.
- Idempotent operations: reading or writing consent must be repeatable with no side-effects when the stored state is unchanged.
- Accessibility first: banners/modals meet WCAG 2.2 AA (focus traps, ARIA-labels, keyboard escape, screen-reader flow).
TypeScript / JavaScript
- All code in .ts / .tsx files with strict type-checking and “exactOptionalPropertyTypes” enabled.
- Declare ConsentPurpose and ConsentStatus enums; never use raw strings in business logic.
- Use discriminated unions for consent events (Granted | Denied | Withdrawn | RefreshRequired).
- Never disable ESLint rules related to safety: no-implicit-any, no-unsafe-any, no-floating-promises.
- Prefer async/await; always annotate async return types (Promise<ConsentRecord>).
Bad: `async function save(c){...}`
Good:
```ts
export const saveConsent = async (
record: ConsentRecord,
): Promise<ConsentRecord> => { ... }
```
- Structure:
src/
├─ components/ # React UI
├─ hooks/ # useConsent(), useRegion()
├─ lib/ # CMP wrappers, helpers
├─ pages/ api/consent # Edge API routes (Next.js)
└─ types/consent.ts # shared types
Error Handling and Validation
- Validate browser capabilities (localStorage, cookies, CMP API availability) before prompting; fall back to server-side consent cookies if unavailable.
- Catch & classify errors early:
• ValidationError – malformed consent object
• StorageError – quota exceeded / blocked
• FrameworkError – CMP SDK failure
• ComplianceError – attempted vendor load without legal basis
- Use early returns; never nest >2 levels of if/try.
- Pipe all errors to a central Logger with privacy safe fields (no PII). Mask user IDs except last 4 chars.
- Implement circuit breaker: after 3 consecutive storage failures, fallback to session memory and show warning toast.
React / Next.js (Framework-Specific Rules)
- Always render <ConsentBanner /> at _app.tsx level; ensure hydration-safe by reading consent from cookies in getServerSideProps and passing as initial prop.
- Delay loading of tracking scripts via next/script strategy="afterInteractive" unless consent.analytics === "granted".
- Use Context API: <ConsentProvider consent={initial} onChange={saveConsent}> … </ConsentProvider>.
- Map consent status to Google Consent Mode:
```ts
import { setConsent } from 'lib/gcm';
useEffect(() => {
setConsent({ ad_storage: consent.ads, analytics_storage: consent.analytics });
}, [consent]);
```
- When using IAB TCF, surface TCString using CMP’s event listener and store in httpOnly cookie “euconsent-v2.” Attach to all outbound ad/analytics requests.
Node.js API Layer
- Persist consent records in compliant store (e.g., Postgres + row-level encryption or DynamoDB w/ KMS). Schema example:
id (uuid PK), user_id, region, tc_string, payload JSONB, banner_version, created_at, updated_at.
- Expose REST/GraphQL endpoints: GET /consent/:userId, PUT /consent. Require JWT auth or signed cookies.
- All writes must log previous payload to consent_history table for immutable audit trail.
Testing
- Unit: jest + @testing-library/react – mock CMP SDKs, assert banner renders equal weight buttons.
- Integration: Cypress e2e with geolocation stubs (EU, US-CA, BR) to verify jurisdiction-specific purposes.
- Accessibility: axe-core automated + manual screen-reader.
- Security: run OWASP ZAP against /api/consent; ensure no sensitive data leakage.
Performance
- Banner CSS/JS ≤ 40 KB gzip to reduce FCP delay.
- Lazy-load CMP SDKs with import() only when banner becomes visible.
- Debounce consent writes to 200 ms to avoid excessive I/O on rapid toggle.
Security
- Encrypt consent cookies (AES-GCM) & set SameSite=Lax.
- Use Content-Security-Policy to block inline scripts except CMP nonce.
- Rotate encryption keys every 180 days; re-encrypt stored payloads via background job.
Accessibility & UX
- Provide plain-language explanations at 8th-grade reading level; test with Hemingway ≤ Grade 8.
- Must support high-contrast mode; verify via prefers-contrast.
Documentation
- README must include: supported regions ➜ data purposes matrix, banner versioning strategy, steps to retrieve audit logs.
DevOps
- CI pipeline blocks merge if Lighthouse score < 90 (Performance & Accessibility) or ESLint errors.
- Deploy new banner text via feature flag “consent_banner_vX” and track in consent_text_versions table.
Common Pitfalls & Avoidance
- ❌ Loading Google Analytics before consent check – detected via performance trace.
✅ Only load after consent.analytics === "granted".
- ❌ Storing consent in localStorage only – blocked in Safari private mode.
✅ Mirror to cookie & server.
- ❌ Single global consent flag – non-compliant.
✅ Purpose + vendor granularity.