CookieConsent

DraftAccessible

The cookie consent component informs users about cookie usage. This banner is shown when they visit a website or an application for the first time.

API

Common properties

These properties are used by the standalone class, the Cookie consent context, and the useCookieConsent hook.

Common texts, groups and cookie data can be found in minimal sitesettings example. The file contains all user interface strings, language options, descriptions for common cookie groups, and details about common Helsinki cookies. There is also an example hel.fi sitesettings example with all the translations. The file contains all user interface strings, language options, descriptions for common cookie groups, and details about common Helsinki cookies. You can also override parts of it and add your project-specific groups and cookies. Remember to replace the INSERT_YOUR_DOMAIN_NAME_HERE.hel.fi -strings in the settings file with the domain name of your service.

Options

Table 1: Options properties
PropertyRequiredDescription
focusTargetSelectorNoSelector for the element that will receive focus once the banner is closed.
languageNoFalls back to 'en'.
pageContentSelectorNoDefaults to 'body'.
settingsPageSelectorNoIf this string is set and matching element is found on page, instead of banner, show a full page cookie settings replacing the matched element. Example: '#hds-cookie-consent-full-page'.
spacerParentSelectorNoDefaults to 'body'.
submitEventNoIf set to true, triggers a window level event hds-cookie-consent-changed with detail.acceptedGroups before closing banner. If not set, reloads page instead. Defaults to false, but is always true in React context and hooks.
targetSelectorNoDefaults to 'body'.

Site settings

Table 2: Site settings properties
PropertyRequiredDescription
cookieNameYesName of cookie where consents are stored to.
fallbackLanguageNoTells which language to use if the requested language is not available.
groupsWhitelistedForApiNoListed groups can be updated by calling the setGroupsStatusToAccepted([])
languagesYesList of languages.
monitorIntervalNoMonitoring rate in milliseconds. Must be larger than 50.
optionalGroupsNoList of optional cookie groups and their descriptions.
removeNoDefaults to false.
robotCookiesNoListed cookies are not shown to the user but should be allowed to be stored. For example, Siteimprove can set cookies while testing the site.
requiredGroupsYesList of required cookie groups and their descriptions.
siteNameNoName of the site to identify where the settings belong.

Detailed info about properties

Note that the user's consent is required for all types of stored information. Information can be stored to cookies, localStorage, sessionStorage, indexedDB, and cache storage. The word "cookie" is used for all storage types in the settings and in this documentation.

Table 3: Cookie group properties
PropertyDescription
group[].cookiesList of cookies in this group.
group[].descriptionDescription of the group in all languages.
group[].groupIdUnique id for the group.
group[].titleTitle of the group in all languages.
Table 4: Cookie properties
PropertyDescription
cookie[].nameStorage name of the item stored in cookies or other storage types.
cookie[].hostDomain where it is used.
cookie[].descriptionCookie usage description in all used languages.
cookie[].expirationCookie expiration time in all used languages.
cookie[].storageTypeWhere the cookie is stored.
1 = cookies,
2 = localStorage,
3 = sessionStorage,
4 = IndexedDB,
5 = Cache Storage.
Languages
Table 4: Language properties
PropertyDescription
language[].codeAbbreviation of the language, for example en or fi.
language[].directionDirection the language is read, for example ltr.
language[].titleName of the language, for example English.
Strings and language

The following strings can be overridden if needed. Note that you also need to provide translations if you override these. It is recommended to use the provided strings.

Table 7: Table heading string overrides
PropertyDescription
translations.acceptedAtText telling when the consent for a group was given.
translations.approveAllConsentsButton text for giving consent to all cookies. Shown when settings are closed and the user cannot give optional consents.
translations.approveOnlyRequiredConsentsButton text for giving consent to only to required cookies. All optional cookie consents are revoked.
translations.approveRequiredAndSelectedConsentsButton text for giving consent to required cookies and selected cookies. Shown when settings are open.
translations.bannerAriaLabelAssistive text for screenreaders about the cookie banner.
translations.descriptionMain description. The most common override because this is service-specific.
translations.formHeadingHeading shown in the details. Seen when settings are opened.
translations.formTextDescription shown in the details. Seen when settings are opened.
translations.headingTop level heading.
translations.hideDetailsButton text for hiding details about a group.
translations.hideCookieSettingsText on the show/hide settings -button when settings are shown.
translations.highlightedGroupText shown when a specific group is highlighted and must be accepted.
translations.highlightedGroupAriaAria-label for a notification about a group.
translations.notificationAriaLabelAria-label for a notification.
translations.settingsSavedText shown when the settings are saved.
translations.showCookieSettingsText on the show/hide settings -button when settings are hidden.
translations.showDetailsButton text for showing details about a group.
translations.storageType1Translation for "cookie". Seen when settings are opened.
translations.storageType2Translation for "localStorage". Seen when settings are opened.
translations.storageType3Translation for "sessionStorage". Seen when settings are opened.
translations.storageType4Translation for "IndexedDB". Seen when settings are opened.
translations.storageType5Translation for "Cache Storage". Seen when settings are opened.
translations.tableHeadingsDescriptionTitle of the “description” column in the cookie description.
translations.tableHeadingsExpirationText of the Period of validity column in the cookie description.
translations.tableHeadingsHostNameTitle of the “hostName” column in the cookie description.
translations.tableHeadingsNameTitle of the “name” column in the cookie description.
translations.tableHeadingsTypeTitle of the “expiration” column in the cookie description.

The consent banner language should be updated to match the language of the page.

Table 8: Properties of the CookieConsentCore instance
PropertyDescriptionType
getAllConsentStatusesReturns an array of consents in the format of [{group:string, consented:boolean}]. group is the name of the consent group, and consented is true if the user has given consent for it.() => [{group:string, consented:boolean}]
getConsentStatusReturns true if the user has given consents to given group.(groupName:string) => boolean
openBannerOpens the banner on each call and optionally highlights given groups. Use when the user needs to accept a specific group to use specific content. The focusTargetSelector defines the element that will receive focus once the banner is closed.(highlightedGroups?: string[], focusTargetSelector? :string) => void
setGroupsStatusToAcceptedAsynchronous function to set specific groups as accepted. Returns true if the groups' status is successfully set to accepted, otherwise false. The given groups must have been listed in siteSettings.groupsWhitelistedForApi.(acceptedGroupsArray:string[]) => Promise<boolean>
removeBannerRemoves the banner.(highlightedGroups?: string[], focusTargetSelector? :string) => void
removePageRemoves the rendered consents. Returns true if there was a page to remove.() => boolean
renderPageRenders the consents to the element with matching id attribute with the siteSettingsId property.() => void
setLanguageSets a new language. Render the banner or page again once changed.() => void

Saving consents

Consents that the user has given are saved to a city-of-helsinki-cookie-consents cookie. A version number indicating which version of the component is in use, is stored to a city-of-helsinki-cookie-consents-version cookie. The version number has no relation to the stored consents.

Cookies are always strings and consents are stored as a JSON-formatted string such as {"cookie-id":"true","another-cookie-id":"false"}.

The ID of the cookie is stored as cookie.id. True means the user has given consent for that cookie. All required cookies are always stored true, but other sites may list a common cookie optional, so the stored consent is not true by default.

Callbacks

The React context and hooks have the onChange callback. The cookie consent class dispatches events that can be listened also without React.

Events

The cookie consent class dispatches three kinds of events:

  • hds-cookie-consent-ready is dispatched when the class instance is ready and has loaded settings and consents.
  • hds-cookie-consent-unapproved-item-found is dispatched when the monitoring system finds an unapproved stored item.
  • hds-cookie-consent-changed is dispatched if the options.submitEvent is set to true and users change their consents. If not set, the Browser page is reloaded instead.

Note: the React context, hooks, and components always set submitEvent to true.

Events are dispatched with window.dispatchEvent and can be listened with window.addEventListener. Events are dispatched in React and vanilla-js versions.

Properties of the custon window events

Table 9: Properties of the monitoring event
PropertyDescriptionTypeDefault
typeThe event type.stringhds-cookie-consent-unapproved-item-found
detail.storageTypeStorage type where the unapproved items were found.cookie, localStorage, sessionStorage, indexedDB or cacheStorage-
detail.keysKeys of the unapproved itemsstring-
detail.acceptedGroupsAccepted consent groups.string[][]
Table 10: Properties of the change event
PropertyDescriptionTypeDefault
typeThe event type.stringhds-cookie-consent-changed
detail.acceptedGroupsAccepted consent groups.string[][]
Table 11: Properties of the ready event
PropertyDescriptionTypeDefault
typeThe event type.stringhds-cookie-consent-ready

Properties of the React change events

The hds-cookie-consent-ready callback is not called with any arguments. Other callback receive the same arguments.

Table 12: Properties of the CookieConsentChangeEvent
PropertyDescriptionTypeDefault
typeType of the event. Event types are listed in events.string-
acceptedGroupsArray of accepted group names.string[][]
storageTypeOnly in monitor events. Type of storage where the unapproved item was found.string-
storageKeysOnly in monitor events. Keys of the unapproved items.string[]-

CSS variables

The current height of the banner is set to a CSS variable in the html element.

<html style="--hds-cookie-consent-height: 123px;">

The variable is useful when adjusting the position of elements that could overlay the cookie consent banner. It's removed when the banner is closed.

Using without React

The hds-js and standalone versions work in any javascript environment.

import { CookieConsentCore } from 'hds-js';
const siteSettings = 'url to the settings json or settings as an object';
const options = {
// options
};
const instance = await CookieConsentCore.create(siteSettings, options);
// the banner opens automatically when needed and options.settingsPageId is not set

Note that the CookieConsentCore.create is an asynchronous function.

It is recommended to set options.submitEvents to true when using the page version. Otherwise the whole page is reloaded after save and the user will not see a notification about successful save and may not notify changes.

The whole page is also reloaded when using the banner without options.submitEvents, but the banner is closed when the consents are stored and before the page reloads.

When events are used, the changes done by the user should be handled with event listeners.

React context

The recommended way to use cookie consents in React is with the CookieConsentContext. The context compares stored consents to the site settings and does not render its children until consents are parsed. This is an asyncronous operation and ensures consents are always available to all child components.

import { CookieConsentContextProvider, CookieConsentChangeEvent } from 'hds-react';
const onChange = (e: CookieConsentChangeEvent) => {
// listen to changes here
};
const options = {
// set options here
};
const siteSettings = {
// set site settings here
};
<CookieConsentContextProvider
onChange={onChange}
options={options}
siteSettings={siteSettings}
></CookieConsentContextProvider>;

Internally, the context uses the useCookieConsents hook and returns the same object the hook returns.

Hooks requiring the React context

Table 13: Cookie consent hooks
HookDescriptionArguments
useCookieContentContext()Returns the context that internally uses the useCookieConsent hook and returns the same object.-
useCookieConsentsInstance()Returns the cookie consent core instance.-
useCookieConsents()Returns an array of consents in the format of [{group:string, consented:boolean}]. group is the name of the consent group, and consented is true if the user has given consent for it.-
useGroupConsent()Use this hook to query if the user has given consent to a single group.(group:string)
useCookieBanner()Add this hook anywhere the banner should be shown if necessary consents have not been given. Preferably use the CookieBanner component.-
useCookieSettingsPage()Add this hook where the settings page content should be shown. Preferably use the CookieSettingsPage component.-

useCookieConsentEvents hook

The cookie consent class dispatches window level events. These can be listened to with window.addEventListener. The useCookieConsentEvents hook does this and also handles the removal of the event listeners when the component unmounts. The hook also returns a disposer function to manually remove the event listeners.

Table 14: Properties of the useCookieConsentEvents
PropertyDescriptionTypeValue
onChangeRequired. Called when the consents change.(e:Event) => voidA change event.
onReadyRequired. Called when the class instance is ready.() => void-
onMonitorEventRequired. Called when the monitoring system finds an unapproved stored item.(e:Event) => voidA change event.

useCookieConsent hook

This hook creates the class instance, listens to events, and renders the parent component when consents or isReady are changed. The CookieConsentContext uses this hook, so there is no need to use this hook and the context at the same time. Both can be used, but they share the same class instance. Other context related hooks and components use this hook and its returned functions automatically. Usually there is no need to use this hook manually.

import { useCookieConsent, CookieConsentChangeEvent } from 'hds-react';
const MyComponent = ()=>{
const onChange = (e:CookieConsentChangeEvent) => {
// listen to changes here
};
const options = {
// set options here
};
const siteSettings = {
// set site settings here
};
const settingsPageId = 'site-settings;
const {isReady } = useCookieConsent({onChange, options, siteSettings, settingsPageId})
if(!isReady){
return null;
}
return (<p>Ready</p>)
}

The context does not render its children if the returned isReady property is not true. It is true when settings have been loaded, parsed and compared to the stored consents of the user. This is the safest way to ensure all consents are loaded before components rely on the data.

Table 15: Properties of the useCookieConsent hook
PropertyDescription
onChangeSee callbacks.
optionsSee options.
siteSettingsSee siteSettings.
settingsPageIdThe id of the element where the settings are rendered.
Table 16: Return type of the useCookieConsent hook
PropertyDescriptionTypeDefault value
isReadyIndicates are the settings loaded, parsed, and compared to stored consents.booleanfalse
consentsGiven consents. Required consents are always true, even if banner is still open.Array<{group:string, consented:boolean}>[]
instanceInstance of the cookie consent class.Class instancenull
openBannerOpens the banner on each call and optionally highlights given groups. Use when the user needs to accept a specific group to use specific content. The focusTargetSelector defines the element that will receive focus once the banner is closed.(highlightedGroups?: string[], focusTargetSelector? :string)=>void -
openBannerIfNeededOpens the banner if all necessary consents have not been given.()=>void -
renderPageRenders the consents to the element with matching id attribute with the siteSettingsId property.()=>void-
removePageRemoves the rendered consents.()=>void-
settingsPageIdThe same value as passed in the settingsPageId property. Used by the useCookieSettingsPage and CookieSettingsPage.stringhds-cookie-consent-full-page
languageCurrent language passed in options.stringen

React components

CookieBanner

Renders the banner, but only if the user has not given all necessary consents. Add this component to all pages except where the CookieSettingsPage is used. This component requires the Cookie Consent context.

CookieSettingsPage

Renders only the contents of the cookie banner, so the same content can be used in the banner and also on a settings page. Do not use the CookieBanner on the same page or the user might see two places to edit consents. This component requires the Cookie Consent context.