Reading Consent State
Relevant source files
The following files were used as context for generating this wiki page:Reading the consent state is the process of determining which categories of cookies or services a user has granted permission for. This is a core function of the consent-manager library, primarily handled by the ConsentManager class upon instantiation. The state is initialized by parsing a browser cookie and is then made available to other parts of an application, such as the DOMConnector and GrantsInterface modules, to dynamically adapt the user experience based on their preferences.
The consent state is exposed through direct properties and an event-based system. This allows for both immediate checks of permissions and reactive updates when the user changes their consent settings. The state is persisted in a cookie to remember user choices across sessions.
Core Mechanism: ConsentManager Initialization
The process of reading the consent state begins when a new ConsentManager instance is created. The constructor orchestrates the reading and parsing of the consent cookie to establish the initial state.
Sources: src/modules/ConsentManager.ts:85-91
Cookie Parsing and State Hydration
The parseCookie method is called internally by the ConsentManager constructor. It is responsible for reading the cookie, validating its contents, and populating the grants and isCustomized properties.
The logic follows these steps:
- Establish Default Grants: It first iterates through the
categoriesprovided in the configuration. For each category, it sets a default grant status. A category is granted by default if it is marked asrequired: trueordefault: true. Otherwise, it defaults tofalse. - Read Cookie: It uses the
js-cookielibrary to read the cookie specified byconfig.cookieName(defaulting to "consent-manager"). - Validate Cookie: The retrieved cookie value (a JSON string) is parsed and passed to the
validateCookiefunction. This function ensures the cookie data has the correct structure ({ version: string, grants: object }) and types. - Version Check: If the cookie is valid, its
versionis compared against theversionin the currentConsentManagerconfiguration. - Apply User Preferences: If the versions match, it signifies that the user's preferences are up-to-date. The
isCustomizedflag is set totrue, and the grant statuses from the cookie override the default values for all non-required categories. - Finalize State: The resulting grant statuses are stored in the
this.grantsproperty.
Sources: src/modules/ConsentManager.ts:93-125, package.json:45
The following diagram illustrates the parseCookie data flow.
This flowchart shows the logic within the parseCookie method for initializing consent state.
Sources: src/modules/ConsentManager.ts:93-125
Cookie Structure and Validation
For the consent state to be read correctly from a cookie, the cookie's value must be a JSON string that parses into an object with a specific structure. The validateCookie function enforces this structure.
| Field | Type | Description |
|---|---|---|
version | string | The configuration version the grants relate to. |
grants | object | A key-value map of category IDs to boolean status. |
Sources: src/modules/ConsentManager.ts:47-50
The validation process is as follows:
This diagram shows the validation checks performed by the validateCookie function.
Sources: src/modules/ConsentManager.ts:8-41
Accessing the Consent State
Once the ConsentManager is initialized, the consent state can be read in two primary ways: through direct property access or by listening for events.
Direct Property Access
The ConsentManager instance exposes public properties that provide a snapshot of the current consent state.
| Property | Type | Description |
|---|---|---|
grants | Record<string, boolean> | An object where keys are category IDs and values are booleans indicating if the category is granted. |
isCustomized | boolean | true if the user has actively saved their preferences and the cookie version matches the config version. false otherwise. |
Sources: src/modules/ConsentManager.ts:87-88, README.md:65-79
Example of accessing these properties:
// Example from README.md
const consentManager = new ConsentManager({ version: '1', categories: [...] });
// { "essential": true, "analytics": false }
const currentGrants = consentManager.grants;
// false
const hasUserMadeChoice = consentManager.isCustomized;
Sources: README.md:65-79
Event-Driven Updates
For applications that need to react to changes in consent, ConsentManager provides an event system. You can subscribe to events using the on() method.
| Event | Callback Argument | Description |
|---|---|---|
grant | categoryId | Fired when a category's status changes to true. |
revoke | categoryId | Fired when a category's status changes to false. |
update | categoryId | Fired on any grant or revoke action. |
Sources: src/modules/ConsentManager.ts:182-188, README.md:104-109
This mechanism is used by DOMConnector to automatically update the DOM when consent changes. The DOMConnector constructor subscribes to the update event and calls its updateDOM method whenever a consent status is changed.
The following sequence diagram shows how a state change triggers an update in a listening module like DOMConnector.
This diagram illustrates how changing a grant via setGrant triggers an update event, which is then handled by a listener like DOMConnector.
Sources: src/modules/ConsentManager.ts:167-171, src/modules/DOMConnector.ts:5-6
Consumers of Consent State
Several modules within the library are designed to consume the consent state read by ConsentManager.
DOMConnector
The DOMConnector reads the consent state to conditionally modify DOM elements.
- In its constructor, it subscribes to the
updateevent to react to changes. - The
isElementGrantedmethod checksthis.client.grantsagainst the categories listed in an element'sdata-cm-categoriesattribute to determine if the element should be "enabled".
Sources: src/modules/DOMConnector.ts:4-6, 18-21
GrantsInterface
The GrantsInterface uses the consent state to render and manage the UI components (banner and modal).
- The constructor checks
client.isCustomized. Iffalse, it automatically callsshowBanner()(whenautoShow: true). - The
generateConsentTablemethod readsthis.client.grantsandthis.client.config.categoriesto build an HTML table with checkboxes reflecting the current consent status for each category.
Sources: src/modules/GrantsInterface.ts:45-47, 120-123
Summary
Reading the consent state in consent-manager is a robust process centered around the ConsentManager class. It begins with a clear initialization flow that safely parses a persisted cookie, falling back to sensible defaults. The resulting state is then made accessible through simple properties (grants, isCustomized) for immediate checks and a powerful event system (on, off) for building reactive features. This architecture allows modules like DOMConnector and GrantsInterface to seamlessly integrate and reflect user consent choices in real-time.