### Install Dependencies Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/README.md Installs the necessary dependencies for the project. ```bash npm install ``` -------------------------------- ### Reactivity Chain Example Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/architecture.md Illustrates the flow of state updates within the module, starting from cookie changes to the re-evaluation of computed properties and component re-renders. ```plaintext Cookie Changes ↓ preferencesCookie.value updated ↓ Watchers detect change ↓ state.value updated (useState) ↓ preferences (exposed Ref) updated ↓ hasUserMadeChoice computed re-evaluated ↓ Components watching preferences re-render ``` -------------------------------- ### Module Setup and Runtime Config Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/architecture.md The module's setup function receives options and the Nuxt instance, making the provided options available in the public runtime configuration for access within the application. ```typescript // module.ts setup() setup(options, nuxt) { nuxt.options.runtimeConfig.public.cookieConsent = options } ``` -------------------------------- ### Develop with Playground Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/README.md Starts the development server with the playground environment for live development. ```bash npm run dev ``` -------------------------------- ### Inject Scripts Example Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/api-reference/utilities.md Demonstrates how `injectScripts` is called within `updatePreferences` to add scripts based on user consent. It also shows its usage during plugin setup. ```typescript // Inside updatePreferences() removeScripts(updated); injectScripts( config.scripts, updated, config.gtmConsentMapping, config?.debug || false ); // And later: if (config.gtmConsentMapping) { setTimeout(() => { sendConsentToGTM(updated, config.gtmConsentMapping, !!config.debug) }, 300) // 300ms delay for GTM script to load } ``` ```typescript // In plugin setup if (hasUserMadeChoice) { injectScripts( config.scripts, acceptedCategories, config.gtmConsentMapping, config?.debug || false ); } ``` -------------------------------- ### Complete Cookie Consent Configuration Example Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/configuration.md This example demonstrates a comprehensive configuration including category definitions, script injections, cookie options, and GTM integration. ```typescript export default defineNuxtConfig({ modules: ['nuxt-simple-cookie-consent'], cookieConsent: { // Category definitions categories: { essential: { label: 'Essential Cookies', description: 'Required for core site functionality', required: true // Users cannot opt-out }, analytics: { label: 'Analytics', description: 'Help us understand how you use the site', required: false }, marketing: { label: 'Marketing', description: 'Show you relevant ads and content', required: false }, personalization: { label: 'Personalization', description: 'Remember your preferences', required: false } }, // Scripts to conditionally inject scripts: [ { id: 'gtag', src: 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX', async: true, categories: ['analytics'] }, { id: 'gtag-config', customContent: ` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-XXXXXXXXXX'); `, categories: ['analytics'] }, { id: 'facebook-pixel', src: 'https://connect.facebook.net/en_US/fbevents.js', async: true, categories: ['marketing'] }, { id: 'facebook-pixel-config', customContent: ` fbq('init', 'YOUR_FB_PIXEL_ID'); fbq('track', 'PageView'); `, categories: ['marketing'] } ], // Cookie options cookieName: 'user_consent_prefs', expiresInDays: 365, consentVersion: '1.0.0', // GTM integration gtmConsentMapping: { analytics: 'analytics_storage', marketing: 'ad_storage', personalization: 'personalization_storage' }, // Development aid debug: process.env.DEBUG === 'true' } }) ``` -------------------------------- ### Install nuxt-simple-cookie-consent Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/README.md Install the module to your Nuxt application using nuxi. ```bash npx nuxi@latest module add nuxt-simple-cookie-consent ``` -------------------------------- ### Full Module Configuration with GTM Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/api-reference/index.md An extensive configuration example demonstrating how to set up categories, scripts, and Google Tag Manager consent mapping for comprehensive cookie consent management. ```typescript cookieConsent: { categories: { analytics: { label: 'Analytics', required: false }, essential: { label: 'Essential', required: true } }, scripts: [ { id: 'gtag', src: 'https://www.googletagmanager.com/gtag/js?id=GA_ID', categories: ['analytics'] } ], expiresInDays: 365, consentVersion: '1.0', gtmConsentMapping: { analytics: 'analytics_storage' }, debug: false } ``` -------------------------------- ### Debug Log Example Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/errors.md Example of debug output that may appear in the console when debug mode is enabled. ```log [DEBUG] Sending GTM consent update: { analytics_storage: "granted" } ``` -------------------------------- ### Documentation Navigation Structure Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/MANIFEST.md This structure outlines the organization of the documentation files for the Nuxt Simple Cookie Consent module, guiding users through setup, API, architecture, and troubleshooting. ```markdown README.md (Start here) ├── configuration.md (Setup & options) ├── types.md (Type reference) ├── api-reference/ │ ├── index.md (API overview) │ ├── useCookieConsent.md (Main composable) │ ├── events.md (Event system) │ └── utilities.md (Internal functions) ├── architecture.md (System design) └── errors.md (Troubleshooting) ``` -------------------------------- ### Cookie Persistence Serialization Example Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/architecture.md Demonstrates how user preferences, timestamp, and version are serialized for storage in cookies. ```javascript // Preferences stored as JSON { "analytics": true, "ads": false } // Timestamp as milliseconds 1234567890123 // Version as string "1.0.0" ``` -------------------------------- ### Complete Cookie Consent Management Example Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/api-reference/useCookieConsent.md A comprehensive example demonstrating the integration of useCookieConsent composable in a Vue.js application. It includes setting up event listeners, managing user preferences, and rendering a cookie consent banner with category selection. ```vue ``` -------------------------------- ### GTM Consent Update Example Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/configuration.md Demonstrates how the GTM consent object is updated based on user preferences and the defined mapping. This example shows 'analytics_storage' granted and 'ad_storage' denied. ```javascript window.gtag('consent', 'update', { 'analytics_storage': 'granted', 'ad_storage': 'denied' }) ``` -------------------------------- ### GTM Script Setup - Immediate Load Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/configuration.md Configures the GTM script to load immediately upon initialization, regardless of user consent. This is achieved by assigning an empty array to the categories property. ```typescript scripts: [ { id: 'gtag', src: 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX', categories: [] // Loads immediately regardless of consent } ] ``` -------------------------------- ### GTM Script Setup - With Category Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/configuration.md Sets up the GTM script to be loaded only when the user accepts the specified category, typically 'analytics'. Ensure this script is listed first in the scripts array. ```typescript scripts: [ { id: 'gtag', src: 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX', categories: ['analytics'] // or include in all }, // Other scripts... ] ``` -------------------------------- ### Overriding Configuration at Runtime (Not Recommended) Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/architecture.md While possible, directly overriding the runtime configuration is not recommended. Use the module's options in nuxt.config.ts for initial setup. ```typescript // Override at runtime const config = useRuntimeConfig().public.cookieConsent config.categories = newCategories // NOT RECOMMENDED ``` -------------------------------- ### CookieScript Usage Examples Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/types.md Demonstrates how to define an array of CookieScript objects for loading external scripts, injecting inline JavaScript, or embedding raw HTML like pixels and iframes. Ensure at least one of `src` or `customContent` is provided. ```typescript const scripts = [ // External script { id: 'ga', src: 'https://www.googletagmanager.com/gtag/js?id=GA_ID', async: true, categories: ['analytics'] }, // Inline script { id: 'ga-init', customContent: ' window.dataLayer = window.dataLayer || []; gtag(\'config\', \'GA_ID\'); ', categories: ['analytics'] }, // Pixel/iframe { id: 'facebook-pixel', customHTML: '', categories: ['ads'] }, // Multi-category script { id: 'universal-pixel', src: 'https://tracking.example.com/pixel.js', categories: ['analytics', 'ads'] } ]; ``` -------------------------------- ### User Preferences Example Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/README.md This JavaScript object represents a user's cookie consent preferences, where keys are category names and values indicate acceptance (true) or rejection (false). Essential categories are always true. ```javascript { analytics: true, // User accepted analytics ads: false, // User rejected ads essential: true // Required, always true } ``` -------------------------------- ### Nuxt Module Definition Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/architecture.md Defines the core Nuxt module, including metadata, default options, and setup logic. This file is primarily for configuration and does not contain core functionality. ```typescript export default defineNuxtModule({ meta: { name: 'nuxt-simple-cookie-consent', configKey: 'cookieConsent' }, defaults: { categories: {}, scripts: [], cookieName: 'cookie_consent' }, setup(options, nuxt) { // Store config in public runtime config // Add plugin // Add auto-imports for composables } }) ``` -------------------------------- ### GTM Consent Mapping Example Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/types.md Illustrates mapping custom cookie consent categories to Google Tag Manager consent fields. This mapping is crucial for correctly configuring the `gtag` consent updates based on user choices. ```typescript // Map cookie consent categories to GTM consent fields const gtmConsentMapping = { ads: 'ad_storage', analytics: 'analytics_storage', personalization: 'personalization_storage' }; // This mapping is passed to useCookieConsent config // When user accepts 'ads', GTM receives: gtag('consent', 'update', { ad_storage: 'granted' }) ``` -------------------------------- ### Custom Banner Component with Nuxt Composables Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/api-reference/index.md Example of a custom cookie banner component using the `useCookieConsent` composable to manage user preferences and actions like accepting or denying all cookies. ```vue ``` -------------------------------- ### Build Playground Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/README.md Builds the playground environment for deployment or testing. ```bash npm run dev:build ``` -------------------------------- ### Post-Consent Initialization with Nuxt Plugin Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/api-reference/index.md Demonstrates how to use Nuxt plugin to initialize tracking scripts based on user consent events like full acceptance or category acceptance. ```typescript import { onConsentAccepted, onCategoryAccepted } from 'nuxt-simple-cookie-consent'; export default defineNuxtPlugin(() => { onConsentAccepted(() => { // Initialize all tracking initializeAnalytics(); initializeAdvertising(); }); onCategoryAccepted((category) => { if (category === 'analytics') { initializeAnalytics(); } }); }); ``` -------------------------------- ### App Initialization Data Flow Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/architecture.md Diagram outlining the process during application startup, including reading cookies, initializing state, and injecting scripts based on stored user preferences. ```mermaid App Starts ↓ Plugin Runs ↓ ├─ Read stored cookies ├─ Parse JSON preferences ├─ Check expiration & version ├─ Initialize state │ └─ Required categories: true │ └─ Other categories: stored value or null ├─ hasUserMadeChoice computed ├─ If user chose & client: │ └─ injectScripts() │ └─ Inject for accepted categories │ └─ Emit 'categoryAccepted' events ↓ App Ready ↓ Component can call useCookieConsent() ``` -------------------------------- ### Standalone Cookie Categories Object Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/types.md Example of creating a TypeScript object that conforms to the CookieConsentCategory type. This can be used for defining categories outside of the nuxt.config.ts. ```typescript const categories = { analytics: { label: 'Analytics', description: 'Used to improve your browsing experience', required: false }, essential: { label: 'Essential Cookies', description: 'Required for site functionality', required: true } }; ``` -------------------------------- ### Run Vitest Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/README.md Runs the test suite using Vitest. ```bash npm run test ``` -------------------------------- ### Run ESLint Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/README.md Executes ESLint to check code for style and potential errors. ```bash npm run lint ``` -------------------------------- ### Multi-Category Script Configuration Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/configuration.md Configures a script to load if the user accepts any of the specified categories. This allows a single script to serve multiple purposes, like analytics and marketing. ```typescript { id: 'universal-tracking', src: 'https://tracking.example.com/script.js', categories: ['analytics', 'marketing'] } ``` -------------------------------- ### Post-Consent Script Initialization Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/architecture.md Extend the module's functionality by executing custom code after a user accepts the cookie consent. This is useful for initializing third-party tracking scripts or analytics. ```typescript onConsentAccepted(() => { // Initialize custom tracking }) ``` -------------------------------- ### Listening for Full Consent Acceptance Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/api-reference/events.md Use this shortcut to execute a callback function specifically when the user accepts all cookie categories. This is ideal for initializing tracking scripts. ```typescript import { onConsentAccepted } from 'nuxt-simple-cookie-consent'; onConsentAccepted(() => { console.log('User has given full consent'); // Initialize all tracking gtag('config', 'GA_ID'); fbq('track', 'PageView'); }); ``` -------------------------------- ### Release New Version Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/README.md Automates the process of releasing a new version of the package. ```bash npm run release ``` -------------------------------- ### Minimal Module Configuration Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/api-reference/index.md This snippet shows the most basic configuration for the cookie consent module, defining only the necessary categories. ```typescript cookieConsent: { categories: { analytics: { label: 'Analytics' } }, scripts: [] } ``` -------------------------------- ### Run Vitest in Watch Mode Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/README.md Runs the test suite using Vitest and watches for file changes to re-run tests. ```bash npm run test:watch ``` -------------------------------- ### Properties & Methods Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/MANIFEST.md This section outlines the reactive properties and methods exposed by the main composable, allowing you to interact with and control the cookie consent state within your Nuxt application. ```APIDOC ## Properties & Methods ### Description Exposed properties and methods from the main composable for managing cookie consent. ### Properties - **preferences** (`Ref`) - A reactive reference to the user's current cookie preferences. - **categories** (`array`) - An array representing the current state of all cookie categories. - **categoryMeta** (`object`) - Metadata associated with each cookie category. - **scripts** (`array`) - An array of scripts managed by the module. - **hasUserMadeChoice** (`computed`) - A computed property indicating if the user has made any consent choice. - **consentTimestamp** (`Ref`) - A reactive reference to the timestamp of the user's consent. - **isConsentExpired** (`computed`) - A computed property indicating if the current consent has expired. ### Methods - **acceptAll()** - Accepts all available cookie categories. - **denyAll()** - Denies all available cookie categories. - **acceptCategories()** - Accepts a specified set of cookie categories. - **updatePreferences()** - Updates the user's cookie preferences based on provided settings. - **resetPreferences()** - Resets all cookie consent preferences to their default state. ``` -------------------------------- ### Reactive UI Updates with Composables Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/api-reference/index.md Shows how to use computed properties with `useCookieConsent` to reactively update the UI based on user preferences and consent status, such as enabling analytics or displaying a banner. ```typescript const { preferences, isConsentExpired } = useCookieConsent(); const isAnalyticsEnabled = computed( () => preferences.value.analytics === true ); const showBanner = computed( () => !hasUserMadeChoice.value || isConsentExpired.value ); ``` -------------------------------- ### Import All Type Exports Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/types.md Import all available type definitions from the package for comprehensive type checking and autocompletion. ```typescript import type { ModuleOptions, CookieConsentCategory, CookieScript, GTMConsentField } from 'nuxt-simple-cookie-consent' ``` -------------------------------- ### Listening for Consent Denial Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/api-reference/events.md This function allows you to register a callback that runs when a user denies all non-essential cookies, either by explicitly denying or resetting preferences. Use this to clean up analytics or ad scripts. ```typescript import { onConsentDenied } from 'nuxt-simple-cookie-consent'; onConsentDenied(() => { console.log('User has rejected non-essential cookies'); // Clean up analytics, ads }); ``` -------------------------------- ### User Updates Preferences Data Flow Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/architecture.md Diagram illustrating the sequence of operations when a user updates their preferences, from clicking 'Accept All' to injecting scripts and sending consent to GTM. ```mermaid User clicks "Accept All" ↓ useCookieConsent().acceptAll() ↓ updatePreferences() called ↓ ├─ Update reactive state ├─ Save to cookies (preferences, timestamp, version) ├─ removeScripts(updated) │ └─ Remove denied category scripts │ └─ Emit 'scriptsRemoved' events ├─ injectScripts(config.scripts, updated) │ └─ Inject accepted category scripts │ └─ Emit 'categoryAccepted' events │ └─ After 300ms: sendConsentToGTM() ├─ Emit 'consentAccepted' event ↓ Listeners notified ↓ Done ``` -------------------------------- ### Generate Type Stubs Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/README.md Generates type stubs for the project, typically required before development. ```bash npm run dev:prepare ``` -------------------------------- ### Configuration Options Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/MANIFEST.md These are the options available for configuring the Nuxt Simple Cookie Consent module. They control various aspects of its behavior, such as cookie management, script execution, and integration with other services. ```APIDOC ## Configuration Options ### Description Configuration options to customize the behavior of the cookie consent module. ### Options - **categories** (`Record`) - Defines the available cookie categories. - **scripts** (`CookieScript[]`) - An array of scripts to manage based on consent. - **cookieName** (`string`) - The name of the cookie used to store consent preferences. - **expiresInDays** (`number`) - The number of days until the consent cookie expires. - **consentVersion** (`string`) - A version identifier for the consent. - **gtmConsentMapping** (`Record`) - Maps consent states to Google Tag Manager consent states. - **debug** (`boolean`) - Enables or disables debug mode for the module. ``` -------------------------------- ### Configure Cookie Consent with TypeScript Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/configuration.md Utilize TypeScript for type-safe configuration of `nuxt-simple-cookie-consent`. Import `ModuleOptions` for type checking and IDE autocomplete. ```typescript import type { ModuleOptions } from 'nuxt-simple-cookie-consent' const config: ModuleOptions = { categories: { /* ... */ }, scripts: [ /* ... */ ] } export default defineNuxtConfig({ cookieConsent: config }) ``` -------------------------------- ### Inline Script Configuration Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/configuration.md Creates an inline script tag with custom JavaScript content. Useful for initialization scripts or direct commands. The src property should be omitted or empty. ```typescript { id: 'ga-init', src: '', // Empty or omit customContent: ' window.dataLayer = window.dataLayer || []; gtag(\'config\', \'GA_ID\'); ', categories: ['analytics'] } ``` -------------------------------- ### Configure Cookie Consent for Development Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/configuration.md Enable debug mode and set a short cookie expiry for development environments. Uses `process.env.NODE_ENV` to determine the environment. ```typescript const isDev = process.env.NODE_ENV === 'development'; export default defineNuxtConfig({ cookieConsent: { debug: isDev, expiresInDays: isDev ? 1 : 180 // Short expiry in dev } }) ``` -------------------------------- ### useCookieConsent API Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/README.md The main composable provides access to cookie consent preferences, categories, and methods to manage user consent. It also exposes computed properties for consent status and event listeners for consent changes. ```APIDOC ## useCookieConsent ### Description Provides reactive access to cookie consent state and management functions. This composable is the primary interface for interacting with the cookie consent module in your Nuxt application. ### Method Signature ```typescript const { preferences, categories, categoryMeta, acceptAll, denyAll, acceptCategories, updatePreferences, hasUserMadeChoice, isConsentExpired, onConsentAccepted, onConsentDenied, onCategoryAccepted, onScriptsInjected, onScriptsRemoved } = useCookieConsent(); ``` ### Properties - **preferences** (Ref>) - Reactive object holding the user's cookie preferences for each category. - **categories** (string[]) - An array of all available cookie category names. - **categoryMeta** (Record) - An object containing metadata for each cookie category. - **hasUserMadeChoice** (ComputedRef) - A computed property that is true if the user has made a choice regarding consent. - **isConsentExpired** (ComputedRef) - A computed property that is true if the user's consent has expired. ### Methods - **acceptAll** - () => void - Accepts all available cookie categories. - **denyAll** - () => void - Denies all available cookie categories. - **acceptCategories** - (categories: string[]) => void - Accepts a specific list of cookie categories. - **updatePreferences** - (prefs: Record) => void - Updates the user's preferences with a new set of category states. - **onConsentAccepted** - (cb: () => void) => void - Registers a callback function to be executed when the user accepts consent. - **onConsentDenied** - (cb: () => void) => void - Registers a callback function to be executed when the user denies consent. - **onCategoryAccepted** - (cb: (cat: string) => void) => void - Registers a callback function to be executed when a specific category is accepted. - **onScriptsInjected** - (cb: (cat: string) => void) => void - Registers a callback function to be executed after scripts for a category are injected. - **onScriptsRemoved** - (cb: (cat: string) => void) => void - Registers a callback function to be executed after scripts for a category are removed. ``` -------------------------------- ### Utility Functions Source: https://github.com/criting/nuxt-simple-cookie-consent/blob/master/_autodocs/MANIFEST.md Utility functions for managing script injection, removal, and Google Tag Manager consent integration. ```APIDOC ## Utility Functions ### `injectScripts(scripts: Array)` #### Description Injects an array of script objects into the DOM. Each script object should contain details like URL, attributes, and placement. #### Parameters - **`scripts`** (Array) - An array of script objects to inject. Each object may include `src`, `async`, `defer`, `id`, `type`, `data-gtm-ignore` etc. #### Behavior - Creates `