{"id":13876209,"url":"https://github.com/segmentio/consent-manager","last_synced_at":"2025-07-16T10:33:20.980Z","repository":{"id":37927976,"uuid":"128473938","full_name":"segmentio/consent-manager","owner":"segmentio","description":"Drop-in consent management plugin for analytics.js","archived":true,"fork":false,"pushed_at":"2024-04-03T16:10:34.000Z","size":6603,"stargazers_count":342,"open_issues_count":36,"forks_count":144,"subscribers_count":17,"default_branch":"master","last_synced_at":"2025-07-09T03:46:28.253Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://segmentio.github.io/consent-manager/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/segmentio.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-04-06T21:51:22.000Z","updated_at":"2025-03-13T14:38:53.000Z","dependencies_parsed_at":"2024-04-03T17:42:05.380Z","dependency_job_id":null,"html_url":"https://github.com/segmentio/consent-manager","commit_stats":{"total_commits":285,"total_committers":39,"mean_commits":"7.3076923076923075","dds":0.5614035087719298,"last_synced_commit":"f9d5166679b3c928b394b8ad50d517fdf43654b1"},"previous_names":[],"tags_count":18,"template":false,"template_full_name":null,"purl":"pkg:github/segmentio/consent-manager","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/segmentio%2Fconsent-manager","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/segmentio%2Fconsent-manager/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/segmentio%2Fconsent-manager/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/segmentio%2Fconsent-manager/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/segmentio","download_url":"https://codeload.github.com/segmentio/consent-manager/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/segmentio%2Fconsent-manager/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265076960,"owners_count":23707596,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-06T06:01:09.352Z","updated_at":"2025-07-16T10:33:20.634Z","avatar_url":"https://github.com/segmentio.png","language":"TypeScript","funding_links":[],"categories":["TypeScript","others"],"sub_categories":[],"readme":"# consent-manager [![build status](https://circleci.com/gh/segmentio/consent-manager.svg?style=svg\u0026circle-token=d3a9e0da7a07fb443f1b4e558ad9c60a55dca223)](https://circleci.com/gh/segmentio/consent-manager)\n\n\n ## ⚠️ Community ⚠️\nThis library is community supported. Segment does not manage or update this library. We suggest forking the repo if changes are needed for your project.\n\nWe highly recommend using [OneTrust](https://www.onetrust.com/) and Segment's [Consent Manager Wrapper](https://segment.com/docs/privacy/consent-management/consent-in-segment-connections/) to benefit from feature enhancements and ongoing support.\n\n\n\u003e Drop-in consent management plugin for analytics.js\n\n[StoryBook](https://segmentio.github.io/consent-manager/index.html)\n\n- [Segment Consent Manager](#segment-consent-manager)\n- [Features](#features)\n- [Usage](#usage)\n  - [Standalone Script](#standalone-script)\n    - [Options](#options)\n    - [Globals](#globals)\n    - [Callback Function](#callback-function)\n  - [ConsentManager](#consentmanager)\n    - [Install](#install)\n    - [Example](#example)\n    - [Example in Next.js](#example-in-nextjs)\n    - [ConsentManager Props](#consentmanager-props)\n  - [ConsentManagerBuilder](#consentmanagerbuilder)\n    - [Install](#install-1)\n    - [Example](#example-1)\n    - [ConsentManagerBuilder Props](#consentmanagerbuilder-props)\n    - [ConsentManagerBuilder Render Props](#consentmanagerbuilder-render-props)\n  - [Utility functions](#utility-functions)\n  - [Setting Custom Anonymous ID](#setting-custom-anonymous-id)\n- [Development](#development)\n- [Publishing New Version](#publishing-new-version)\n- [License](#license)\n\n## Segment Consent Manager\n\nThe Segment Consent Manager is an analytics.js add-on with support to consent management.\n\nAt its core, the Consent Manager empowers your visitors to control and customize their tracking preferences on a website. They can opt out entirely of being tracked, or selectively opt out of tools in which they don’t want their information stored.\n\nIt works by taking control of the analytics.js load process to only load destinations that the user has consented to and not loading analytics.js at all if the user has opted out of everything. The user's tracking preferences are saved to a cookie and sent as an identify trait (if they haven't opted out of everything) so that you can also access them on the server-side and from destinations (warehouse).\n\n_Segment works to ensure the Consent Manager Tech Demo works with most of our product pipeline. We cannot ensure it works in your specific implementation or website. Please contact our Professional Services team for implementation support. Please see the License.txt included._\n\n_Please note, Consent Manager is not currently compatible with [Personas](https://segment.com/docs/personas/). Personas may send user data to destinations the user has explicitly opted out of for data collection._\n\n### Features\n\n- Give users the ability to opt-in or opt-out to tracking.\n- Fine grained control of tools or categories used for tracking.\n- 30s setup with a drop in script tag.\n- Or fully customizable UI/UX through React components.\n- EU traffic detection through [@segment/in-eu][ineu].\n- Ability for visitors to reconsent and change preferences.\n- Automatically updates to reflect the destinations you have enabled in Segment.\n- **5.0.0**: Consent Manager will add consent metadata to the context of all track calls:\n\nTrack call message payloads will be extended to include Consent metadata in the `context` object:\n\n```js\n{\n  \"context\": {\n    \"campaign\": {},\n    \"consent\": {\n      \"categoryPreferences\": {\n        \"Amplitude\": true,\n        \"Customer.io\": true,\n        \"Google Analytics\": true,\n        \"Webhooks\": true\n      },\n      \"defaultDestinationBehavior\": \"disable\",\n      \"destinationPreferences\": {\n        \"Amplitude\": true,\n        \"Customer.io\": true,\n        \"Google Analytics\": true,\n        \"Webhooks\": true\n      }\n    }\n  },\n  \"event\": \"Send Track Event Clicked\",\n  \"integrations\": {\n    \"All\": false,\n    \"Amplitude\": true,\n    \"HubSpot\": false,\n    \"Salesforce\": false,\n    \"Segment.io\": true\n  }\n}\n```\n\n**Breaking Changes:** Version 5.0.0 and above require that your analytics.js snippet include the method `addSourceMiddleware` in the `analytics.methods` array:\n\n```js\nanalytics.methods = [\n  'trackSubmit',\n  'trackClick',\n  'trackLink',\n  'trackForm',\n  'pageview',\n  'identify',\n  'reset',\n  'group',\n  'track',\n  'ready',\n  'alias',\n  'debug',\n  'page',\n  'once',\n  'off',\n  'on',\n  'addSourceMiddleware' // This method is necessary for Consent Manager to forward consent metadata.\n]\n```\n\n## Usage\n\nThe Segment Consent Manager can be used in several ways, depending on how custom you want your visitor's experience to be.\n\nTo get started, make sure you're using the latest version of the [analytics.js snippet][] (4.1.0 or above) and remove the `analytics.load(\"YOUR_WRITE_KEY\");` call (so the consent manager can manage the loading process). Then continue onto one of the implementation methods below.\n\n### Standalone Script\n\nThe standalone script is a prebuilt bundle that uses the [ConsentManager][] React component with [Preact][] (a lightweight React alternative). It's best for if you want to get up and running quickly or you don't have a preexisting React setup.\n\nInclude the consent manager script tag after your analytic.js snippet and add your own custom copy. The standalone script can be configured in one of two ways, via data attributes for simple usage or via a global callback function for advanced usage. Both methods allow the consent manager script to be loaded async.\n\n#### Options\n\nAll of the [ConsentManager][] options are supported with the addition of these options:\n\n##### container\n\n**Type**: `string`\n\n[CSS selector][] to the DOM element that will host the consent banner. It should be an empty DOM element (usually a `\u003cdiv\u003e`) because the consent manager will replace any existing DOM elements inside it. The element must also exist on the page before the script is executed.\n\nYou can also control the positioning of the consent banner by applying styles to the container element (optional). E.g:\n\n```css\n#target-container {\n  position: fixed;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  z-index: 100;\n}\n```\n\n```html\n\u003cdiv id=\"target-container\"\u003e\u003c/div\u003e\n```\n\n#### Globals\n\nThe following global variables are also exposed:\n\n- `consentManager.version` - Version of the consent manager.\n- `consentManager.openConsentManager()` - Opens the consent manager preferences dialog.\n- `consentManager.doNotTrack()` - Utility function that returns the user's Do Not Track preference (normalises the cross browser API differences). Returns `true`, `false` or `null` (no preference specified).\n- `consentManager.inEU()` - The [@segment/in-eu][ineu] `inEU()` function.\n- `consentManager.preferences` - Returns an instance of `PreferencesManager` with the following helper functions:\n  - `loadPreferences` - returns the cookie value for consent preferences\n  - `savePreferences` - allows for managing the consent cookie programatically (useful if you want to re-hydrate consent from your own database or prefill consent options)\n  - `onPreferencesSaved(callback)` - allows for subscribing to changes in preferences.\n\n#### Callback Function\n\nAll the options are supported. The callback function also receives these exports:\n\n- `React` - Reference to the [Preact][] library (the API is React compatible). Useful for if you need to use virtual DOM in your content.\n- `version` - Version of the consent manager.\n- `openConsentManager()` - Opens the consent manager preferences dialog.\n- `doNotTrack()` - Utility function that returns the user's Do Not Track preference (normalises the cross browser API differences). Returns `true`, `false` or `null` (no preference specified).\n- `inEU()` - The [@segment/in-eu][ineu] `inEU()` function.\n- `consentManager.preferences` - Returns an instance of `PreferencesManager` with the following helper functions:\n  - `loadPreferences` - returns the cookie value for consent preferences\n  - `savePreferences` - allows for managing the consent cookie programatically (useful if you want to re-hydrate consent from your own database or prefill consent options)\n  - `onPreferencesSaved(callback)` - allows for subscribing to changes in preferences.\n\n```html\n\u003cscript\u003e\n  window.consentManagerConfig = function(exports) {\n    var React = exports.React\n    var inEU = exports.inEU\n\n    var bannerContent = React.createElement(\n      'span',\n      null,\n      'We use cookies (and other similar technologies) to collect data to improve your experience on our site. By using our website, you՚re agreeing to the collection of data as described in our',\n      ' ',\n      React.createElement(\n        'a',\n        { href: '/docs/legal/website-data-collection-policy/', target: '_blank' },\n        'Website Data Collection Policy'\n      ),\n      '.'\n    )\n    var bannerSubContent = 'You can change your preferences at any time.'\n    var preferencesDialogTitle = 'Website Data Collection Preferences'\n    var preferencesDialogContent =\n      'We use data collected by cookies and JavaScript libraries to improve your browsing experience, analyze site traffic, deliver personalized advertisements, and increase the overall performance of our site.'\n    var cancelDialogTitle = 'Are you sure you want to cancel?'\n    var cancelDialogContent =\n      'Your preferences have not been saved. By continuing to use our website, you՚re agreeing to our Website Data Collection Policy.'\n\n    return {\n      container: '#target-container',\n      writeKey: '\u003cyour-segment-write-key\u003e',\n      shouldRequireConsent: inEU,\n      bannerContent: bannerContent,\n      bannerSubContent: bannerSubContent,\n      preferencesDialogTitle: preferencesDialogTitle,\n      preferencesDialogContent: preferencesDialogContent,\n      cancelDialogTitle: cancelDialogTitle,\n      cancelDialogContent: cancelDialogContent\n    }\n  }\n\u003c/script\u003e\n\n\u003cscript\n  src=\"https://unpkg.com/@segment/consent-manager@5.3.0/standalone/consent-manager.js\"\n  defer\n\u003e\u003c/script\u003e\n```\n\n### ConsentManager\n\nThe `ConsentManager` React component is a prebuilt consent manager UI (it's the one we use on https://segment.com) that uses the [ConsentManagerBuilder][] component under the hood. To use it, just mount the component where you want the consent banner to appear and pass in your own custom copy.\n\n_Note: Consent Manager is React-based so is not currently compatible with other frameworks such as Vue.js or Angular. In case you want to use it in another framework that is not React, you should use the Standalone implementation._\n\n#### Install\n\nUsing npm:\n\n```\nnpm install @segment/consent-manager\n```\n\nUsing yarn:\n\n```\nyarn add @segment/consent-manager\n```\n\n#### Example\n\n```javascript\nimport React from 'react'\nimport { ConsentManager, openConsentManager } from '@segment/consent-manager'\nimport inEU from '@segment/in-eu'\n\nexport default function() {\n  const bannerContent = (\n    \u003cspan\u003e\n      We use cookies (and other similar technologies) to collect data to improve your experience on\n      our site. By using our website, you’re agreeing to the collection of data as described in our{' '}\n      \u003ca href=\"/docs/legal/website-data-collection-policy/\" target=\"_blank\"\u003e\n        Website Data Collection Policy\n      \u003c/a\u003e\n      .\n    \u003c/span\u003e\n  )\n  const bannerSubContent = 'You can change your preferences at any time.'\n  const preferencesDialogTitle = 'Website Data Collection Preferences'\n  const preferencesDialogContent =\n    'We use data collected by cookies and JavaScript libraries to improve your browsing experience, analyze site traffic, deliver personalized advertisements, and increase the overall performance of our site.'\n  const cancelDialogTitle = 'Are you sure you want to cancel?'\n  const cancelDialogContent =\n    'Your preferences have not been saved. By continuing to use our website, you՚re agreeing to our Website Data Collection Policy.'\n\n  return (\n    \u003cdiv\u003e\n      \u003cConsentManager\n        writeKey=\"\u003cyour-segment-write-key\u003e\"\n        shouldRequireConsent={inEU}\n        bannerContent={bannerContent}\n        bannerSubContent={bannerSubContent}\n        preferencesDialogTitle={preferencesDialogTitle}\n        preferencesDialogContent={preferencesDialogContent}\n        cancelDialogTitle={cancelDialogTitle}\n        cancelDialogContent={cancelDialogContent}\n      /\u003e\n\n      \u003cbutton type=\"button\" onClick={openConsentManager}\u003e\n        Website Data Collection Preferences\n      \u003c/button\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n#### Example in Next.js\n\nIn Next.js we do not have an html file where to inject the script. Here we will use the Script component to inject the snippet provided by Segment.\n\n```javascript\nimport React from 'react'\nimport Script from 'next/script'\nimport { ConsentManager, openConsentManager } from '@segment/consent-manager'\n\nexport default function Home() {\n  const bannerContent = (\n    \u003cspan\u003e\n      We use cookies (and other similar technologies) to collect data to improve your experience on\n      our site. By using our website, you’re agreeing to the collection of data as described in our{' '}\n      \u003ca href=\"/docs/legal/website-data-collection-policy/\" target=\"_blank\"\u003e\n        Website Data Collection Policy\n      \u003c/a\u003e\n      .\n    \u003c/span\u003e\n  )\n  const bannerSubContent = 'You can change your preferences at any time.'\n  const preferencesDialogTitle = 'Website Data Collection Preferences'\n  const preferencesDialogContent =\n    'We use data collected by cookies and JavaScript libraries to improve your browsing experience, analyze site traffic, deliver personalized advertisements, and increase the overall performance of our site.'\n  const cancelDialogTitle = 'Are you sure you want to cancel?'\n  const cancelDialogContent =\n    'Your preferences have not been saved. By continuing to use our website, you՚re agreeing to our Website Data Collection Policy.'\n\n  return (\n    \u003cdiv\u003e\n      \u003cScript\n        id=\"show-banner\"\n        dangerouslySetInnerHTML={{\n          __html: `!function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console\u0026\u0026console.error\u0026\u0026console.error(\"Segment snippet included twice.\");else{analytics.invoked=!0;analytics.methods=[\"trackSubmit\",\"trackClick\",\"trackLink\",\"trackForm\",\"pageview\",\"identify\",\"reset\",\"group\",\"track\",\"ready\",\"alias\",\"debug\",\"page\",\"once\",\"off\",\"on\",\"addSourceMiddleware\",\"addIntegrationMiddleware\",\"setAnonymousId\",\"addDestinationMiddleware\"];analytics.factory=function(e){return function(){var t=Array.prototype.slice.call(arguments);t.unshift(e);analytics.push(t);return analytics}};for(var e=0;e\u003canalytics.methods.length;e++){var key=analytics.methods[e];analytics[key]=analytics.factory(key)}analytics.load=function(key,e){var t=document.createElement(\"script\");t.type=\"text/javascript\";t.async=!0;t.src=\"https://cdn.segment.com/analytics.js/v1/\" + key + \"/analytics.min.js\";var n=document.getElementsByTagName(\"script\")[0];n.parentNode.insertBefore(t,n);analytics._loadOptions=e};;analytics.SNIPPET_VERSION=\"4.13.2\";\n          analytics.page();\n          }}();`\n        }}\n      /\u003e\n\n      \u003cmain\u003e\n        \u003cConsentManager\n          writeKey=\"5V8KznnIFIDh1ejQLbmX7ikfSRa6r8bF\"\n          bannerContent={bannerContent}\n          bannerSubContent={bannerSubContent}\n          preferencesDialogTitle={preferencesDialogTitle}\n          preferencesDialogContent={preferencesDialogContent}\n          cancelDialogTitle={cancelDialogTitle}\n          cancelDialogContent={cancelDialogContent}\n          bannerActionsBlock={true}\n        /\u003e\n\n        \u003cbutton type=\"button\" onClick={openConsentManager}\u003e\n          Website Data Collection Preferences\n        \u003c/button\u003e\n      \u003c/main\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n#### ConsentManager Props\n\nThis section lists the configurable props you can change when\nloading the out of the box Consent Manager. In [this demo](https://codepen.io/samuelkahr/pen/eYYrobB), these are all the props you can pass into the returned preferences object.\n\n\u003c!-- TOC depthFrom:5 depthTo:5 withLinks:1 updateOnSave:1 orderedList:0 --\u003e\n\n- [writeKey](#writekey)\n- [otherWriteKeys](#otherwritekeys)\n- [shouldRequireConsent](#shouldrequireconsent)\n- [initialPreferences](#initialpreferences)\n- [closeBehavior](#closebehavior)\n- [implyConsentOnInteraction](#implyconsentoninteraction)\n- [defaultDestinationBehavior](#defaultdestinationbehavior)\n- [cookieDomain](#cookiedomain)\n- [bannerContent](#bannercontent)\n- [bannerSubContent](#bannersubcontent)\n- [bannerTextColor](#bannertextcolor)\n- [bannerBackgroundColor](#bannerbackgroundcolor)\n- [bannerActionsBlock](#banneractionsblock)\n- [bannerHideCloseButton](#bannerhideclosebutton)\n- [bannerAsModal](#bannerasmodal)\n- [preferencesDialogTitle](#preferencesdialogtitle)\n- [preferencesDialogContent](#preferencesdialogcontent)\n- [cancelDialogTitle](#canceldialogtitle)\n- [cancelDialogContent](#canceldialogcontent)\n- [customCategories](#customcategories)\n- [preferencesDialogTemplate](#preferencesdialogtemplate)\n\n\u003c!-- /TOC --\u003e\n\n##### writeKey\n\n**Type**: `string`\n**Default**: none\n\nThe write key analytics.js should be loaded with.\n\nYou can find more information here.\nhttps://segment.com/docs/connections/find-writekey\n\n##### otherWriteKeys\n\n**Type**: `array\u003cstring\u003e`\n**Default**: `[]`\n\n[Write keys](https://share.getcloudapp.com/jkunGzrw) for other sources so you can include destinations they use in the Consent Manager tool list. This only displays destinations that are not connected to the primary writeKey.\n\nThe user’s consent preferences for these tools are not sent to these additional sources, but they are added to the `identify` call the Consent Manager sends to Segment. The user’s preferences can then be added to a raw data destination (like a data warehouse) or to a user profile in Personas.\n\n##### shouldRequireConsent\n\n**Type**: `function`\n**Default**: `() =\u003e true`\n\nCallback function that determines if consent is required before tracking begins. Set to `true` to show the consent banner, otherwise return `false` to not show consent banner and start tracking immediately.\n\nThe function can return a `Promise` that resolves to a boolean.\n\n##### initialPreferences\n\n**Type**: object\n**Default**: {}\n\nObject that opts into users into tracking for the different tracking categories. For example `{‘Functional’:true}`\n\n##### closeBehavior\n\n**Type**: `string` or `function`\n**Default**: `dismiss`\n\nThis option sets the default behavior for the x (close) button on the Consent Manager banner. Available options:\n\n- “dismiss” - dismisses the banner, but doesn't save or change any preferences. Analytics.js won’t load until consent is given.\n- “accept”- assume consent across every category.\n- ”deny” - denies consent across every category.\n\n`closeBehavior` can also be customized - i.e. don't load some categories, but load everything else. For example, if you wanted to load everything _except_ advertising, you could pass the following as `closeBehavior`:\n\n```js\ncloseBehavior={\n  (categories) =\u003e ({\n    ...categories,\n    advertising: false\n  })\n}\n```\n\n##### implyConsentOnInteraction\n\n**_Breaking Change_** (versions \u003c 3.0.0 will default this option `true`)\n\n**Type**: `boolean`\n**Default**: `false` (as of 3.0.0)\n\nDetermines whether or not consent should be implied if the user interacts with the website by clicking anywhere outside the Consent Manager banner.\n\n##### defaultDestinationBehavior\n\n**Type**: `string`\n**Default**: `disable`\n\nDetermines what the Consent Manager does if the user has already made consent selections and it detects new destination tools. (This is determined by checking if the user already has a cookie set on their browser.)\n\nThis is relevant when you've added a connected a new destination to any of the sources managed by Consent Manager.\n\nOptions:\n\n- `disable` (default) - When you add new destinations, they are set to “disabled” unless a user updates their consent selections by default.\n- `enable` - When you add new destinations, they are set to “enabled” unless a user updates their consent selections.\n- `imply` - When you add new destinations, they are enabled or disabled based on the category to which they belong and the user's previous consent to that category.\n  For example, if a user already consented to the `marketingAndAnalytics` category, and you add a new destination which is in the `Analytics` category, that destination will be enabled until the user updates their consent selections.\n- `ask` - When you add new destinations, the Consent Manager automatically opens the preferences dialog on initialization, and asks the user for their consent again.\n\n##### cookieDomain\n\n**Type**: `string`\n**Default**: the top most domain and all sub domains\n\nThe domain the `tracking-preferences` cookie should be scoped to.\n\n##### bannerContent\n\n**Type**: `PropTypes.node`\n\nThe content of the [consent banner](https://share.getcloudapp.com/Apurj6zv).\n\n##### bannerSubContent\n\n**Type**: `string`\n\nThe [call to action](https://share.getcloudapp.com/z8uXxpkZ) under the primary text in the Consent Manager banner.\n\n##### bannerActionsBlock\n\nType: `function(object) | boolean`\n\nThe flag or function to render the actions block. If `true` value is passed - will render the default buttons block with `Accept all` and `Deny all` (required for the GDPR compliance). if the function is passed - will render the passed function into a actions block placeholder.\n\nFunction props:\n\n- `acceptAll: () =\u003e void` - accept all cookies and close the banner\n- `denyAll: () =\u003e void` - deny all cookies and close the banner\n- `changePreferences: () =\u003e void` - open the dialog\n\n##### bannerTextColor\n\n**Type**: `string`\n**Default**: `#fff`\n\nThe color of the consent banner text.\n\n##### bannerBackgroundColor\n\nType: `string`\u003cbr\u003e\nDefault: `#1f4160`\n\nThe color of the consent banner background.\n\n##### bannerHideCloseButton\n\nType: `boolean`\u003cbr\u003e\nDefault: `false`\n\nHide the close button of the consent banner.\n\n##### bannerAsModal\n\nType: `boolean`\u003cbr\u003e\nDefault: `false`\n\nShow the consent banner as a modal, blocking the interaction while it is not accepted/rejected.\n\n##### preferencesDialogTitle\n\n**Type**: `PropTypes.node`\n**Default**: `Website Data Collection Preferences`\n\nThe [title of the preferences dialog](https://share.getcloudapp.com/jkuKlrAw).\n\n##### preferencesDialogContent\n\n**Type**: `PropTypes.node`\n\nThe top [descriptive content](https://share.getcloudapp.com/z8uXxJAQ) of the preferences dialog.\n\n##### cancelDialogTitle\n\n**Type**: `PropTypes.node`\n**Default**: `Are you sure you want to cancel?`\n\n[The title](https://share.getcloudapp.com/v1urD6R6) of the cancel dialog.\n\n##### cancelDialogContent\n\n**Type**: `PropTypes.node`\n\nThe text displayed in the cancel dialog box.\n\n##### customCategories\n\n**Type**: `PropTypes.object`\n**Default**: `undefined`\n\nAn object that represents custom consent categories, and which tools are included in these categories. For example, for CCPA compliance, you could create a custom “Do Not Sell” category and list relevant destinations to it.\n\n_Note: Calling the `customCategories` object will overwrite the prebuilt categories (Analytics, Functional, Targeting and Advertising) provided by Consent Manager. Those categories will need to be redeclared inside `customCategories`. You can find examples [here](https://gist.github.com/samuelkahr/343350ad0a466ded566f0d0c8167e800) and [here](https://codepen.io/samuelkahr/pen/JjdNqzr)._\n\n```javascript\nconst customCategories = {\n  'New Category': {\n    purpose: 'A new consent category to capture more granular consent groupings',\n    integrations: ['Google Adwords (Classic)', 'Amplitude', 'Slack']\n  }\n}\n```\n\nThe values for `integrations` should be an integration's creationName (`integration.creationName`). You can find examples of that by going to `https://cdn.segment.com/v1/projects/\u003cwriteKey\u003e/integrations`\n\n##### preferencesDialogTemplate\n\n**Type**: `PropTypes.object`\n**Default**:\n\n```javascript\n{\n  headings: {\n    allowValue: 'Allow',\n    categoryValue: 'Category',\n    purposeValue: 'Purpose',\n    toolsValue: 'Tools'\n  },\n  checkboxes: {\n    noValue: 'No',\n    yesValue: 'Yes'\n  },\n  actionButtons: {\n    cancelValue: 'Cancel',\n    saveValue: 'Save'\n  },\n  cancelDialogButtons: {\n    cancelValue: 'Yes, Cancel',\n    backValue: 'Go Back'\n  },\n  categories: [\n    {\n      key: 'functional',\n      name: 'Functional',\n      description:\n        'To monitor the performance of our site and to enhance your browsing experience.',\n      example: 'For example, these tools enable you to communicate with us via live chat.'\n    },\n    {\n      key: 'marketing',\n      name: 'Marketing and Analytics',\n      description:\n        'To understand user behavior in order to provide you with a more relevant browsing experience or personalize the content on our site.',\n      example:\n        'For example, we collect information about which pages you visit to help us present more relevant information.'\n    },\n    {\n      key: 'advertising',\n      name: 'Advertising',\n      description:\n        'To personalize and measure the effectiveness of advertising on our site and other websites.',\n      example:\n        'For example, we may serve you a personalized ad based on the pages you visit on our site.'\n    },\n    {\n      key: 'essential',\n      name: 'Essential',\n      description: 'We use browser cookies that are necessary for the site to work as intended.',\n      example:\n        'For example, we store your website data collection preferences so we can honor them if you return to our site. You can disable these cookies in your browser settings but if you do the site may not work as intended.'\n    }\n  ]\n}\n```\n\nAn object that represents the text fields of the preferences dialog and allows customizing them.\nWe recommend copying the default object and changing the fields as necessary.\n\n_Note: All fields are optional. If they are not included in the template (object) the default fields will be used._\n\n_Note 2: For categories, you need to provide the key in order to map all the values properly._\n\n### ConsentManagerBuilder\n\nThe `ConsentManagerBuilder` React component is a low level render props component for building your own consent manager UI. It abstracts away all the logic for fetching destinations, checking/saving consent and loading analytics.js.\n\n_Note: ConsentManagerBuilder is React-based so is not currently compatible with other frameworks such as Vue.js or Angular. In case you want to use it in another framework that is not React, you should use the Standalone implementation._\n\n#### Install\n\nUsing npm:\n\n```\nnpm install @segment/consent-manager\n```\n\nUsing yarn:\n\n```\nyarn add @segment/consent-manager\n```\n\n#### Example\n\nFor a more detailed/advanced example, checkout the [ConsentManager implementation][].\n\n```javascript\nimport React from 'react'\nimport { ConsentManagerBuilder } from '@segment/consent-manager'\n\nexport default function() {\n  return (\n    \u003cConsentManagerBuilder writeKey=\"\u003cyour-segment-write-key\u003e\"\u003e\n      {({ destinations, preferences, setPreferences, saveConsent }) =\u003e (\n        \u003cdiv\u003e\n          \u003ch2\u003eTracking tools\u003c/h2\u003e\n          \u003cul\u003e\n            {destinations.map(destination =\u003e (\n              \u003cli key={destination.id}\u003e\n                \u003clabel\u003e\n                  \u003cinput\n                    type=\"checkbox\"\n                    checked={Boolean(preferences[destination.id])}\n                    onChange={() =\u003e\n                      setPreferences({\n                        [destination.id]: !preferences[destination.id]\n                      })\n                    }\n                  /\u003e\n                  {destination.name}\n                \u003c/label\u003e\n              \u003c/li\u003e\n            ))}\n          \u003c/ul\u003e\n\n          \u003cbutton type=\"button\" onClick={() =\u003e saveConsent()}\u003e\n            Save\n          \u003c/button\u003e\n          \u003cbutton type=\"button\" onClick={() =\u003e saveConsent(true)}\u003e\n            Allow all\n          \u003c/button\u003e\n          \u003cbutton type=\"button\" onClick={() =\u003e saveConsent(false)}\u003e\n            Deny all\n          \u003c/button\u003e\n        \u003c/div\u003e\n      )}\n    \u003c/ConsentManagerBuilder\u003e\n  )\n}\n```\n\n#### ConsentManagerBuilder Props\n\n- [children](#children)\n- [writeKey](#writekey-1)\n- [otherWriteKeys](#otherwritekeys-1)\n- [shouldRequireConsent](#shouldrequireconsent-1)\n- [initialPreferences](#initialpreferences-1)\n- [defaultDestinationBehavior](#defaultdestinationbehavior-1)\n- [mapCustomPreferences](#mapcustompreferences)\n- [cookieDomain](#cookiedomain-1)\n- [shouldReload](#shouldReload-1)\n- [devMode](#devMode-1)\n- [useDefaultCategories](#useDefaultCategories-1)\n\n##### children\n\n**Type**: `function`\n\nThe render props function that returns your UI.\n\n##### writeKey\n\n**Type**: `string`\n\nThe write key analytics.js should be loaded with.\n\n##### otherWriteKeys\n\n**Type**: `array\u003cstring\u003e`\n**Default**: `[]`\n\nOther write keys that you want to load destination information for. This is useful for including your server-side destinations in the consent manager, so that you can easily apply the user's tracking preferences to your server-side analytics too. _No data will be sent to these write keys._\n\n##### shouldRequireConsent\n\n**Type**: `function`\n**Default**: `() =\u003e true`\n\nCallback function that determines if consent is required before tracking can begin. Return `true` to show the consent banner and wait for consent (if no consent has been given yet). Return `false` to not show the consent banner and start tracking immediately (unless the user has opted out). The function can return a `Promise` that resolves to a boolean.\n\n##### initialPreferences\n\n**Type**: `object`\n**Default**: `{}`\n\nThe initial value of the preferences. By default it should be an object map of `{destinationId: true|false|'N/A'}`. If you're using [mapCustomPreferences][] it should be an object map of your custom preferences' default values.\n\n##### defaultDestinationBehavior\n\n**Type**: `string`\n**Default**: `disable`\n\nDetermines what the Consent Manager does if the user has already made consent selections and it detects new destination tools. (This is determined by checking if the user already has a cookie set on their browser.)\n\nThis is relevant when you've added a connected a new destination to any of the sources managed by Consent Manager.\n\nOptions:\n\n- `disable` (default) - When you add new destinations, they are set to “disabled” unless a user updates their consent selections by default.\n- `enable` - When you add new destinations, they are set to “enabled” unless a user updates their consent selections.\n- `imply` - When you add new destinations, they are enabled or disabled based on the category to which they belong and the user's previous consent to that category.\n  For example, if a user already consented to the `marketingAndAnalytics` category, and you add a new destination which is in the `Analytics` category, that destination will be enabled until the user updates their consent selections.\n- `ask` - When you add new destinations, the Consent Manager automatically opens the preferences dialog on initialization, and asks the user for their consent again.\n\nThis setting also also affects [Replays](https://segment.com/docs/guides/what-is-replay/) to new destinations. Only `disable` and `enable` apply to these replays. If you set `defaultDestinationBehavior` to `imply`, Segment interprets this as `enable` during a replay.\n\n##### mapCustomPreferences\n\n**Type**: `function`\n**Default**: `undefined`\n\nCallback function allows you to use a custom preferences format (e.g: categories) instead of the default destination based one. The function gets called during the consent saving process and gets passed `(destinations, preferences)`. The function should return `{destinationPreferences, customPreferences}` where `destinationPreferences` is your custom preferences mapped to the destinations format (`{destiantionId: true|false}`) and `customPreferences` is your custom preferences if you changed them in the callback (optional).\n\n##### cookieDomain\n\n**Type**: `string`\n**Default**: the [top most domain][top-domain] and all sub domains\n\nThe domain the `tracking-preferences` cookie should be scoped to.\n\n##### shouldReload\n\n**Type**: `boolean`\n**Default**: `true`\n\nReload the page if the trackers have already been initialized so that the user's new preferences can take effect.\n\n##### devMode\n\n**Type**: `boolean`\n**Default**: `false`\n\nDisable the analitics.load to make local testing.\n\n##### useDefaultCategories\n\n**Type**: `boolean`\n**Default**: `false`\n\nUse default categories set by Consent Manager instead of detinations.\n\n#### ConsentManagerBuilder Render Props\n\n- [destinations](#destinations)\n- [newDestinations](#newdestinations)\n- [preferences](#preferences)\n- [destinationPreferences](#destinationpreferences)\n- [havePreferencesChanged](#havepreferenceschanged)\n- [isConsentRequired](#isconsentrequired)\n- [workspaceAddedNewDestinations](#workspaceaddednewdestinations)\n- [setPreferences](#setpreferences)\n- [resetPreferences](#resetpreferences)\n- [saveConsent](#saveconsent)\n- [onError](#onError)\n\n##### destinations\n\n**Type**: `array\u003cobject\u003e`\n**Default**: `[]`\n\nDestinations enabled for the provided write keys. Each destination contains these properties:\n\n```\n{\n  id,\n  name,\n  description,\n  website,\n  category\n}\n```\n\n##### newDestinations\n\n**Type**: `array\u003cobject\u003e`\n**Default**: `[]`\n\nNew destinations that have been enabled since the user last gave consent.\n\n##### preferences\n\n**Type**: `object`\n**Default**: `{}`\n\nThe current preferences in state. By default if should be in the format of `{destinationId: true|false}`, but if you're using [mapCustomPreferences][] the object map can be in any format you want. _Note: this isn't the saved preferences._\n\n##### destinationPreferences\n\n**Type**: `object`\n**Default**: `{}`\n\nThe current _destination specific_ preferences, i.e. `{Amplitude: true}`.\n\n##### havePreferencesChanged\n\n**Type**: `boolean`\n**Default**: `false`\n\nA boolean value representing whether or not the user has changed their preferences since opening the preferences modal. Will be set to `true` if the user interacts with the preferences modal by selecting \"Yes\" or \"No\" on any of the consent categories.\n\nThis is used to not reload the page if no preferences have changed, as to not create a disruptive user experience.\n\n##### isConsentRequired\n\n**Type**: `boolean`\n**Default**: `true`\n\nThe result of [shouldRequireConsent][].\n\n##### workspaceAddedNewDestinations\n\n**Type**: `boolean`\n**Default**: `false`\n\nA boolean value representing whether or not there have been new destinations connected to the source(s) managed by Consent Manager, compared to the destinations set on the existing cookie.\n\n##### setPreferences\n\n**Type**: `function(object|boolean)`\n\nSets a preference to a new value in state. By default it takes an object map in the format of `{destinationId: true|false}`, but if you're using [mapCustomPreferences][] the object map can be in any format you want. It behaves like `setState()` in that you can set one or more preferences at a time and they get merged with what's currently in state. You can also pass a boolean to set all destination preferences to `true` or `false` (you shouldn't do this if you're using [mapCustomPreferences][]).\n\n##### resetPreferences\n\n**Type**: `function`\n\nResets the [preferences][] state to the value saved in the cookie. Useful for resetting the state when the preferences dialog is closed without saving for example.\n\n##### saveConsent\n\n**Type**: `function(object|boolean)`\n\nSaves the preferences currently in state to a cookie called `tracking-preferences`, triggers an identify call with `destinationTrackingPreferences` and `customTrackingPreferences` traits and then reloads analytics.js using the new preferences. It can also be passed preferences like [setPreferences][] to do a final update before saving.\n\n##### onError\n\n**Type**: `function(object)`\n\nAllows you to manually handle if there is an error when initializing - e.g. if there is an ad blocker that prevented fetching the destinations. This will prevent an uncaught error e.g. `Failed to fetch`.\n\n### Utility functions\n\n- `openConsentManager()` - Opens the [ConsentManager][] preferences dialog.\n- `doNotTrack()` - Returns the user's Do Not Track preference (normalises the cross browser API differences). Returns `true`, `false` or `null` (no preference specified).\n\n### Setting Custom Anonymous ID\n\nAnalytics.js generates a universally unique ID (UUID) for the viewer during the library’s initialization phase, and sets this as anonymousId for each new visitor to your site. This happens before Analytics.js loads any device-mode destinations, and so before these destination-libraries can generate their own user IDs.\n\nExample\n\n```javascript\najs_anonymous_id=%2239ee7ea5-b6d8-4174-b612-04e1ef3fa952\n```\n\nYou can override the default-generated anonymousID from the Segment snippet.\n\n```javascript\nanalytics.SNIPPET_VERSION = '4.13.2'\nanalytics.page()\nanalytics.setAnonymousId('YOUR_CUSTOM_ID')\n```\n\n_Note: Keep in mind that setting the anonymousId in Analytics.js does not overwrite the anonymous tracking IDs for any destinations you’re using._\n\n_There are other ways to override the anonymousID, you can find more information [here][]._\n\n## Development\n\nTo run our storybook locally, simply do:\n\n```\n$ yarn dev\n```\n\nand the storybook should be opened in your browser. We recommend adding a new story for new features, and testing against existing stories when making bug fixes.\n\n## Styles\n\nThe file GUIDESTYLES.md contains the list of all components you can use this id to change de styles on Consent Manager.\n\n### Publishing New Version\n\nThis package follows semantic versioning. To publish a new version:\n\n```\n$ npm version \u003cnew-version\u003e\n$ npm publish\n```\n\n## License\n\nconsent-manager is released under the MIT license.\n\nCopyright © 2021, Segment.io, Inc.\n\n[analytics.js snippet]: https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/quickstart/#step-2-copy-the-segment-snippet\n[preact]: https://preactjs.com\n[currentscript]: https://caniuse.com/#feat=document-currentscript\n[ineu]: https://github.com/segmentio/in-eu\n[consentmanager]: #consentmanager\n[consentmanagerbuilder]: #consentmanagerbuilder\n[top-domain]: https://github.com/segmentio/top-domain\n[mapcustompreferences]: #mapcustompreferences\n[shouldrequireconsent]: #shouldrequireconsent-1\n[preferences]: #preferences\n[setpreferences]: #setpreferences\n[consentmanager implementation]: src/consent-manager\n[css selector]: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector\n[here]: https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/identity/\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsegmentio%2Fconsent-manager","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsegmentio%2Fconsent-manager","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsegmentio%2Fconsent-manager/lists"}