The ConsentManager Class
Relevant source files
The following files were used as context for generating this wiki page:The ConsentManager class is the core component of the consent-manager library. It provides a comprehensive and flexible solution for managing user cookie consent. Its primary responsibilities include handling the configuration of consent categories, persisting user preferences in a cookie, managing the state of granted permissions, and providing an event-driven system for other modules to react to consent changes.
This class is designed to be the central authority for consent state. Other modules, such as the GrantsInterface for UI components and the DOMConnector for conditional DOM manipulation, are built to consume an instance of ConsentManager. It uses js-cookie for cookie operations and deepmerge for configuration merging.
Sources: src/modules/ConsentManager.ts, README.md:5-9, package.json:44-46
Architecture and Core Concepts
The ConsentManager operates by taking a configuration object at initialization, which defines the consent categories and cookie behavior. It then either loads existing user preferences from a cookie or establishes a default state. The state is publicly accessible through the grants property and can be modified via the setGrant method. Changes to the consent state are persisted back to the cookie and announced through an event system.
Class Diagram
This diagram illustrates the structure of the ConsentManager class and its relationship with consuming modules.
Initialization and Configuration
An instance of ConsentManager is created by passing a configuration object to its constructor. This configuration is merged with a set of default values.
Sources: src/modules/ConsentManager.ts:72-75
Configuration Options
The ConsentManagerConfig interface defines the structure of the configuration object.
| Option | Type | Default Value | Description |
|---|---|---|---|
version | string | '1' (but required) | A version string for the configuration. If this changes, all existing user consents are disregarded. |
cookieName | string | 'consent-manager' | The name of the cookie used to store consent preferences. |
expires | number | Date | 'session' | 365 (days) | The expiration time for the consent cookie. |
categories | object[] | [] | An array of category objects defining the different types of consent. See Category Object. |
Sources: src/modules/ConsentManager.ts:53-66, README.md:19-32
Category Object
Each object in the categories array defines a toggleable consent group.
| Property | Type | Description |
|---|---|---|
id | string | A unique identifier for the category. |
label | string | A human-readable name for the category. |
description | string | A short explanation of the category's purpose. |
required | boolean | If true, this category cannot be disabled by the user. |
default | boolean | The default consent state for this category if not required. Defaults to false. |
Sources: src/modules/ConsentManager.ts:57-63, README.md:36-70
Initialization Flow
The constructor initializes the manager by merging the provided configuration and then parsing the consent cookie to establish the initial state.
State Management
The core function of the ConsentManager is to manage the consent state, which is stored in the grants property and persisted in a browser cookie.
Properties
| Property | Type | Description |
|---|---|---|
config | ConsentManagerConfig<G> | The final, merged configuration object used by the instance. |
isCustomized | boolean | true if the user has actively made a choice, either by loading a valid cookie or by using setGrant. |
grants | GrantsStatus<G> | A key-value object where keys are category IDs and values are booleans indicating the consent status. |
Sources: src/modules/ConsentManager.ts:69-71, README.md:76-93
Cookie Handling
The manager interacts with a single browser cookie to persist the user's choices.
Cookie Data Structure
The data stored in the cookie is a JSON string with the following structure:
interface CookieData {
version: string;
grants: Record<string, boolean>;
}
Sources: src/modules/ConsentManager.ts:48-51, src/modules/ConsentManager.ts:117-120
Cookie Validation
Before a cookie's contents are used, it is validated to ensure it has the correct structure and data types. The validateCookie function checks that:
- The value is a plain object.
- It contains exactly two keys:
grantsandversion. versionis a string.grantsis a non-empty plain object.- All values within
grantsare booleans.
Sources: src/modules/ConsentManager.ts:5-40
Modifying Consent with setGrant
The setGrant(id, status) method is the primary way to change the consent state.
- If
idis'*', the method recursively calls itself to apply thestatusto all non-required categories. - It will not change the status of a category where
requiredistrue. - Upon a successful change, it updates the
grantsobject, setsisCustomizedtotrue, dispatchesupdateandgrant/revokeevents, and callswriteCookie()to persist the changes.
The following diagram shows the sequence of actions when setGrant is called.
Event System
ConsentManager implements a simple event emitter pattern to allow other parts of the application to react to changes in consent.
Event Types
| Event Name | Payload | Description |
|---|---|---|
grant | string | Fired when a category's status changes to true. |
revoke | string | Fired when a category's status changes to false. |
update | string | Fired for any change (grant or revoke). |
Sources: src/modules/ConsentManager.ts:53, src/modules/ConsentManager.ts:153-155, README.md:108-112
Methods
on(eventName, callback): Registers a callback function to be executed when a specific event is dispatched.off(eventName, callback): Removes a previously registered event listener. The exact same function reference must be passed.dispatch(eventName, grant): (Private) Executes all registered callbacks for a given event.
This system is used by DOMConnector to listen for update events and re-evaluate the DOM, and by GrantsInterface to hide the consent banner once a choice is made.
Sources: src/modules/ConsentManager.ts:162-192, src/modules/DOMConnector.ts:5-6, src/modules/GrantsInterface.ts:107-111
Module Exports and Bundling
The ConsentManager class is the default export of the package. The DOMConnector and GrantsInterface classes are available as named exports. This allows for flexible integration, whether using ES modules or a browser bundle.
- ESM/CJS:
import ConsentManager, { DOMConnector } from 'consent-manager'; - Browser Bundle: The classes are attached to the
windowobject (e.g.,window.ConsentManager).
Sources: src/index.ts:1-5, src/bundle.ts:1-8
Summary
The ConsentManager class is the foundational block for handling cookie consent. It provides a robust system for defining consent categories, persisting user choices via cookies, and notifying other application modules of changes through an event-driven API. Its clear separation of concerns allows it to be a reliable "source of truth" for user consent, which is then consumed by UI components like GrantsInterface and DOM manipulators like DOMConnector to create a complete consent management solution.